context
stringlengths
2.52k
185k
gt
stringclasses
1 value
// ------------------------------------------------------------------------------------------------ // KingTomato Script // -- // // Summary: // // Because I didn't have ALL *grin* the events I wanted to have with presto pack, I added a // few more. You can find the syntax to use them below. These events include some like // eventBottomPrint, eventTopPrint, eventCenterPrint, (All useful to retrieve a current // weapon). Additionally, you can catch menu text (as in TAB menu). Very cool for things // like hacking admin :P // // Events: // eventCenterPrint(%msg, %timeout); // eventBottomPrint(%msg, %timeout); // eventTopPrint(%msg, %timeout); // Returns the print message with the message and the time to be shown for. // eventClientInput(%team, %msg); // This event triggers when the user types something into the chat or team chat box. You // can then parse the message how ever you want, inclusing returning mute to stop the // displaying of the message. // eventNewMenu(%menuTitle) // Triggers when the tab menu is either opened, or the menu changes (due to item // selection, or what ever) // eventAddMenuItem(%menuItem, %menuCommand) // Triggers when an item is added to the menu. Each 5menuItem will be in the form of // something like "1Change Teams Observer" with a %menuCommand of something like // "changeteams" // eventInfoLine(%line, %text) // Triggers when a line in the bottom right box of the tab menu is set or updated // eventVote(%vote) // Triggers when the user votes one way or the other. %vote will be passed as either // yes or no. // eventModInfo(%version, %name, %mod, %info, %favKey) // Triggers on a connection, and will return the information sent from the server // about itself. Will pass the following information: // %version - Version of server (ex: 1.11) // %name - Server name // %mod - Server mod // %info - Server Info // %favKey - Name of the key used to mark favorites. // eventTime(%seconds) // This will trigger every time the server sends an "update time" message to // the client. This usually occurs every 20 seconds on a map with a time limit, // and will return a negative number (negative sybmolising time left). // %seconds - Number of seconds on map. // // ----------------------------------------------------------------------------------------------------- $Script::Creator = "KingTomato"; $Script::Version = "1.4"; $Script::Description = "Extended events library designed to include bottomPrint, topPrint, centerPrint, " @ "Input Commands, Bot Commands, and more! Please read file for more information"; // ----------------------------------------------------------------------------------------------------- // eventCenterPrint(%msg, %timeout); // eventBottomPrint(%msg, %timeout); // eventTopPrint(%msg, %timeout); // Returns the print message with the message and the time to be shown for. // ----------------------------------------------------------------------------------------------------- function remoteCP(%manager, %msg, %timeout) { if (%manager == 2048) { $centerPrintId++; if (%timeout) schedule("clearCenterPrint(" @ $centerPrintId @ ");", %timeout); Client::centerPrint(PrintProtect::Clean(%msg), 0); Event::Trigger(eventcenterPrint, String::DoubleSlashes(%msg), %timeout); } } function remoteBP(%manager, %msg, %timeout) { if (%manager == 2048) { $centerPrintId++; if (%timeout) schedule("clearCenterPrint(" @ $centerPrintId @ ");", %timeout); Client::centerPrint(PrintProtect::Clean(%msg), 1); Event::Trigger(eventBottomPrint, String::DoubleSlashes(%msg), %timeout); } } function remoteTP(%manager, %msg, %timeout) { if (%manager == 2048) { $centerPrintId++; if (%timeout) schedule("clearCenterPrint(" @ $centerPrintId @ ");", %timeout); Client::centerPrint(PrintProtect::Clean(%msg), 2); Event::Trigger(eventTopPrint, String::DoubleSlashes(%msg), %timeout); } } // ------------------------------------------------------------------------------------------------ // eventClientInput(%team, %message) // This event triggers when the user types something into the chat or team chat box. You // can then parse the message how ever you want, inclusing returning mute to stop the // displaying of the message. // ------------------------------------------------------------------------------------------------ function say(%team, %msg) { %returns = Event::Trigger(eventClientInput, %team, %msg); if (Event::Returned(%returns, mute)) return; %msg = Acronym::Replace(%msg); // Flood Protect Addition if ($FloodProtect::Enabled) { %timeNow = getIntegerTime(false) >> 5; %delta = $FloodProtect::Time - %timeNow; remoteBP(2048, "<jc><f2>-Flood Protection Enabled-\n" @"To prevent further delay, your message " @"has been stopped until the flood limit is reached.\n\n" @"Time up in <f0>" @ %delta @ "<f2> seconds", 10); return; } // End Flood Protect Addition remoteEval(2048, say, %team, %msg); } // ------------------------------------------------------------------------------------------------ // eventInventoryText(%text) // When the inventory text is altered // ------------------------------------------------------------------------------------------------ function remoteITXT(%manager, %msg) { if(%manager == 2048) Control::setValue(EnergyDisplayText, %msg); Event::Trigger(eventInventoryText, %msg); } // ------------------------------------------------------------------------------------------------ // eventNewMenu(%menuTitle) // Triggers when the tab menu is either opened, or the menu changes (due to item // selection, or what ever) // ------------------------------------------------------------------------------------------------ function remoteNewMenu(%server, %title) { if(%server != 2048) return; if(isObject(CurServerMenu)) deleteObject(CurServerMenu); newObject(CurServerMenu, ChatMenu, %title); setCMMode(PlayChatMenu, 0); setCMMode(CurServerMenu, 1); Event::Trigger(eventNewMenu, %title); } // ------------------------------------------------------------------------------------------------ // eventAddMenuItem(%menuItem, %menuCommand) // Triggers when an item is added to the menu. Each 5menuItem will be in the form of // something like "1Change Teams Observer" with a %menuCommand of something like // "changeteams" // ------------------------------------------------------------------------------------------------ function remoteAddMenuItem(%server, %title, %code) { if(%server != 2048) return; addCMCommand(CurServerMenu, %title, clientMenuSelect, %code); Event::Trigger(eventAddMenuItem, %title, %code); } // ------------------------------------------------------------------------------------------------ // eventInfoLine(%line, %text) // Triggers when a line in the bottom right box of the tab menu is set or updated // ------------------------------------------------------------------------------------------------ function remoteSetInfoLine(%mgr, %lineNum, %text) { if(%mgr != 2048) return; if (%lineNum == 1) { if (%text == "") Control::setVisible(InfoCtrlBox, FALSE); else Control::setVisible(InfoCtrlBox, TRUE); } Control::setText("InfoCtrlLine" @ %lineNum, %text); Event::Trigger(eventInfoLine, %lineNum, %text); } // ------------------------------------------------------------------------------------------------ // eventVote(%vote) // Triggers when the user votes one way or the other. %vote will be passed as either // yes or no. // ------------------------------------------------------------------------------------------------ function voteYes() { remoteEval(2048, VoteYes); Event::Trigger(eventVote, yes); } function voteNo() { remoteEval(2048, VoteNo); Event::Trigger(eventVote, no); } // ------------------------------------------------------------------------------------------------ // eventModInfo(%version, %name, %mod, %info, %favKey) // Triggers on a connection, and will return the information sent from the server // about itself. Will pass the following information: // %version - Version of server (ex: 1.11) // %name - Server name // %mod - Server mod // %info - Server Info // %favKey - Name of the key used to mark favorites. // ------------------------------------------------------------------------------------------------ function remoteSVInfo(%server, %version, %hostname, %mod, %info, %favKey) { if(%server == 2048) { $ServerVersion = %version; $ServerName = %hostname; $modList = %mod; $ServerMod = $modList; $ServerInfo = %info; $ServerFavoritesKey = %favKey; EvalSearchPath(); Event::Trigger(eventModInfo, %version, %name, %mod, %info, %favKey); } } // ------------------------------------------------------------------------------------------------ // eventTime(%seconds) // This will trigger every time the server sends an "update time" message to // the client. This usually occurs every 20 seconds on a map with a time limit, // and will return a negative number (negative sybmolising time left). // %seconds - Number of seconds on map. // ------------------------------------------------------------------------------------------------ function remoteSetTime(%server, %time) { if(%server == 2048) { setHudTimer(%time); Event::Trigger(eventTime, %time); } }
/* 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. */ #define USE_TRACING #define DEBUG using System; using System.IO; using System.Xml; using System.Collections; using System.Configuration; using System.Net; using System.Web; using NUnit.Framework; using Google.GData.Client; using Google.GData.Client.UnitTests; using Google.GData.Blogger; namespace Google.GData.Client.LiveTests { [TestFixture] [Category("LiveTest")] public class BloggerTestSuite : BaseLiveTestClass { /// <summary> /// test Uri for google calendarURI /// </summary> protected string bloggerURI; ////////////////////////////////////////////////////////////////////// /// <summary>default empty constructor</summary> ////////////////////////////////////////////////////////////////////// public BloggerTestSuite() { } ////////////////////////////////////////////////////////////////////// /// <summary>the setup method</summary> ////////////////////////////////////////////////////////////////////// [SetUp] public override void InitTest() { base.InitTest(); GDataGAuthRequestFactory authFactory = this.factory as GDataGAuthRequestFactory; if (authFactory != null) { authFactory.Handler = this.strAuthHandler; } FeedCleanup(this.bloggerURI, this.userName, this.passWord, VersionDefaults.Major); } ///////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////// /// <summary>the end it all method</summary> ////////////////////////////////////////////////////////////////////// [TearDown] public override void EndTest() { Tracing.ExitTracing(); FeedCleanup(this.bloggerURI, this.userName, this.passWord, VersionDefaults.Major); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>private void ReadConfigFile()</summary> /// <returns> </returns> ////////////////////////////////////////////////////////////////////// protected override void ReadConfigFile() { base.ReadConfigFile(); if (unitTestConfiguration.Contains("bloggerURI") == true) { this.bloggerURI = (string) unitTestConfiguration["bloggerURI"]; Tracing.TraceInfo("Read bloggerURI value: " + this.bloggerURI); } } ///////////////////////////////////////////////////////////////////////////// public override string ServiceName { get { return "blogger"; } } ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void GoogleAuthenticationTest() { Tracing.TraceMsg("Entering Blogger AuthenticationTest"); BloggerQuery query = new BloggerQuery(); BloggerService service = new BloggerService(this.ApplicationName); int iCount; if (this.bloggerURI != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); BloggerFeed blogFeed = service.Query(query); ObjectModelHelper.DumpAtomObject(blogFeed,CreateDumpFileName("AuthenticationTest")); iCount = blogFeed.Entries.Count; String strTitle = "Dinner time" + Guid.NewGuid().ToString(); if (blogFeed != null && blogFeed.Entries.Count > 0) { BloggerEntry entry = ObjectModelHelper.CreateAtomEntry(1) as BloggerEntry; // blogger does not like labels yet. entry.Categories.Clear(); entry.Title.Text = strTitle; entry.Categories.Clear(); entry.IsDraft = true; entry.Updated = Utilities.EmptyDate; entry.Published = Utilities.EmptyDate; BloggerEntry newEntry = blogFeed.Insert(entry); iCount++; Tracing.TraceMsg("Created blogger entry"); // try to get just that guy..... BloggerQuery singleQuery = new BloggerQuery(); singleQuery.Uri = new Uri(newEntry.SelfUri.ToString()); BloggerFeed newFeed = service.Query(singleQuery); BloggerEntry sameGuy = newFeed.Entries[0] as BloggerEntry; Tracing.TraceMsg("retrieved blogger entry"); Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical"); Assert.IsTrue(sameGuy.IsDraft == true); } blogFeed = service.Query(query); Assert.AreEqual(iCount, blogFeed.Entries.Count, "Feed should have one more entry, it has: " + blogFeed.Entries.Count); if (blogFeed != null && blogFeed.Entries.Count > 0) { // look for the one with dinner time... foreach (AtomEntry entry in blogFeed.Entries) { Tracing.TraceMsg("Entrie title: " + entry.Title.Text); if (String.Compare(entry.Title.Text, strTitle)==0) { entry.Content.Content = "Maybe stay until breakfast"; entry.Content.Type = "text"; entry.Update(); Tracing.TraceMsg("Updated entry"); } } } blogFeed = service.Query(query); Assert.AreEqual(iCount, blogFeed.Entries.Count, "Feed should have one more entry, it has: " + blogFeed.Entries.Count); if (blogFeed != null && blogFeed.Entries.Count > 0) { // look for the one with dinner time... foreach (AtomEntry entry in blogFeed.Entries) { Tracing.TraceMsg("Entrie title: " + entry.Title.Text); if (String.Compare(entry.Title.Text, strTitle)==0) { entry.Delete(); iCount--; Tracing.TraceMsg("deleted entry"); } } } blogFeed = service.Query(query); Assert.AreEqual(iCount, blogFeed.Entries.Count, "Feed should have the same count again, it has: " + blogFeed.Entries.Count); service.Credentials = null; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>checks for xhtml persistence</summary> ////////////////////////////////////////////////////////////////////// [Ignore ("Currently broken on the server")] [Test] public void BloggerXHTMLTest() { Tracing.TraceMsg("Entering BloggerXHTMLTest"); FeedQuery query = new FeedQuery(); BloggerService service = new BloggerService(this.ApplicationName); if (this.bloggerURI != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); AtomFeed feed = service.Query(query); String strTitle = "Dinner time" + Guid.NewGuid().ToString(); if (feed != null) { // get the first entry String xhtmlContent = "<div><b>this is an xhtml test text</b></div>"; AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1); entry.Categories.Clear(); entry.Title.Text = strTitle; entry.Content.Type = "xhtml"; entry.Content.Content = xhtmlContent; AtomEntry newEntry = feed.Insert(entry); Tracing.TraceMsg("Created blogger entry"); // try to get just that guy..... FeedQuery singleQuery = new FeedQuery(); singleQuery.Uri = new Uri(newEntry.SelfUri.ToString()); AtomFeed newFeed = service.Query(singleQuery); AtomEntry sameGuy = newFeed.Entries[0]; Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical"); Assert.IsTrue(sameGuy.Content.Type.Equals("xhtml")); Assert.IsTrue(sameGuy.Content.Content.Equals(xhtmlContent)); } service.Credentials = null; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>checks for xhtml persistence</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerHTMLTest() { Tracing.TraceMsg("Entering BloggerHTMLTest"); FeedQuery query = new FeedQuery(); BloggerService service = new BloggerService(this.ApplicationName); if (this.bloggerURI != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); AtomFeed feed = service.Query(query); String strTitle = "Dinner time" + Guid.NewGuid().ToString(); if (feed != null) { // get the first entry String htmlContent = "<div>&lt;b&gt;this is an html test text&lt;/b&gt;</div>"; AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1); entry.Categories.Clear(); entry.Title.Text = strTitle; entry.Content.Type = "html"; entry.Content.Content = htmlContent; AtomEntry newEntry = feed.Insert(entry); Tracing.TraceMsg("Created blogger entry"); // try to get just that guy..... FeedQuery singleQuery = new FeedQuery(); singleQuery.Uri = new Uri(newEntry.SelfUri.ToString()); AtomFeed newFeed = service.Query(singleQuery); AtomEntry sameGuy = newFeed.Entries[0]; Assert.IsTrue(sameGuy.Title.Text.Equals(newEntry.Title.Text), "both titles should be identical"); Assert.IsTrue(sameGuy.Content.Type.Equals("html")); String input = HttpUtility.HtmlDecode(htmlContent); String output = HttpUtility.HtmlDecode(sameGuy.Content.Content); Assert.IsTrue(input.Equals(output), "The input string should be equal the output string"); } service.Credentials = null; } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>tests if we can access a public feed</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerPublicFeedTest() { Tracing.TraceMsg("Entering BloggerPublicFeedTest"); FeedQuery query = new FeedQuery(); BloggerService service = new BloggerService(this.ApplicationName); String publicURI = (String) this.externalHosts[0]; if (publicURI != null) { service.RequestFactory = this.factory; query.Uri = new Uri(publicURI); AtomFeed feed = service.Query(query); if (feed != null) { // look for the one with dinner time... foreach (AtomEntry entry in feed.Entries) { Assert.IsTrue(entry.ReadOnly, "The entry should be readonly"); } } } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>tests if we can access a public feed</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerVersion2Test() { Tracing.TraceMsg("Entering BloggerVersion2Test"); BloggerQuery query = new BloggerQuery(); BloggerService service = new BloggerService(this.ApplicationName); string title = "V1" + Guid.NewGuid().ToString(); service.ProtocolMajor = 1; service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); // insert a new entry in version 1 AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1); entry.Categories.Clear(); entry.Title.Text = title; entry.IsDraft = true; entry.ProtocolMajor = 12; AtomEntry returnedEntry = service.Insert(new Uri(this.bloggerURI), entry); Assert.IsTrue(returnedEntry.ProtocolMajor == service.ProtocolMajor); Assert.IsTrue(entry.IsDraft); Assert.IsTrue(returnedEntry.IsDraft); BloggerFeed feed = service.Query(query); Assert.IsTrue(feed.ProtocolMajor == service.ProtocolMajor); if (feed != null) { Assert.IsTrue(feed.TotalResults >= feed.Entries.Count, "totalresults should be >= number of entries"); Assert.IsTrue(feed.Entries.Count > 0, "We should have some entries"); } service.ProtocolMajor = 2; feed = service.Query(query); Assert.IsTrue(feed.ProtocolMajor == service.ProtocolMajor); if (feed != null) { Assert.IsTrue(feed.Entries.Count > 0, "We should have some entries"); Assert.IsTrue(feed.TotalResults >= feed.Entries.Count, "totalresults should be >= number of entries"); foreach (BloggerEntry e in feed.Entries) { if (e.Title.Text == title) { Assert.IsTrue(e.ProtocolMajor == 2); Assert.IsTrue(e.IsDraft); } } } } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>tests the etag functionallity for updates</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerETagTest() { Tracing.TraceMsg("Entering BloggerETagTest"); BloggerQuery query = new BloggerQuery(); BloggerService service = new BloggerService(this.ApplicationName); service.ProtocolMajor = 2; string title = "V1" + Guid.NewGuid().ToString(); service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); // insert a new entry in version 1 AtomEntry entry = ObjectModelHelper.CreateAtomEntry(1); entry.Categories.Clear(); entry.Title.Text = title; entry.IsDraft = true; BloggerEntry returnedEntry = service.Insert(new Uri(this.bloggerURI), entry) as BloggerEntry; Assert.IsTrue(returnedEntry.ProtocolMajor == service.ProtocolMajor); Assert.IsTrue(entry.IsDraft); Assert.IsTrue(returnedEntry.IsDraft); Assert.IsTrue(returnedEntry.Etag != null); string etagOld = returnedEntry.Etag; returnedEntry.Content.Content = "This is a test"; BloggerEntry newEntry = returnedEntry.Update() as BloggerEntry; Assert.IsTrue(newEntry.Etag != null); Assert.IsTrue(newEntry.Etag != etagOld); } ///////////////////////////////////////////////////////////////////////////// ////////////////////////////////////////////////////////////////////// /// <summary>runs an authentication test</summary> ////////////////////////////////////////////////////////////////////// [Test] public void BloggerStressTest() { Tracing.TraceMsg("Entering Blogger GoogleStressTest"); FeedQuery query = new FeedQuery(); BloggerService service = new BloggerService(this.ApplicationName); if (this.bloggerURI != null) { if (this.userName != null) { service.Credentials = new GDataCredentials(this.userName, this.passWord); } service.RequestFactory = this.factory; query.Uri = new Uri(this.bloggerURI); AtomFeed blogFeed = service.Query(query); ObjectModelHelper.DumpAtomObject(blogFeed,CreateDumpFileName("AuthenticationTest")); if (blogFeed != null) { for (int i=0; i< 30; i++) { AtomEntry entry = ObjectModelHelper.CreateAtomEntry(i); entry.Categories.Clear(); entry.Title.Text = "Title " + i; entry.Content.Content = "Some text..."; entry.Content.Type = "html"; blogFeed.Insert(entry); } } } } ///////////////////////////////////////////////////////////////////////////// } ///////////////////////////////////////////////////////////////////////////// }
using UnityEditor; using UnityEditor.IMGUI.Controls; using System.Collections.Generic; using System.IO; namespace UnityEngine.AssetBundles { [System.Serializable] public class AssetBundleBuildTab { const string kBuildPrefPrefix = "ABBBuild:"; // gui vars ValidBuildTarget m_buildTarget = ValidBuildTarget.StandaloneWindows; CompressOptions m_compression = CompressOptions.StandardCompression; string m_outputPath = string.Empty; bool m_useDefaultPath = true; string m_streamingPath = "Assets/StreamingAssets"; [SerializeField] bool m_advancedSettings; [SerializeField] Vector2 m_scrollPosition; class ToggleData { public ToggleData(bool s, string title, string tooltip, BuildAssetBundleOptions opt = BuildAssetBundleOptions.None) { content = new GUIContent(title, tooltip); state = EditorPrefs.GetBool(PrefKey, s); option = opt; } public string PrefKey { get { return kBuildPrefPrefix + content.text; } } public bool state; public GUIContent content; public BuildAssetBundleOptions option; } List<ToggleData> m_toggleData; ToggleData m_ForceRebuild; ToggleData m_CopyToStreaming; GUIContent m_TargetContent; GUIContent m_CompressionContent; public enum CompressOptions { Uncompressed = 0, StandardCompression, ChunkBasedCompression, } GUIContent[] m_CompressionOptions = { new GUIContent("No Compression"), new GUIContent("Standard Compression (LZMA)"), new GUIContent("Chunk Based Compression (LZ4)") }; int[] m_CompressionValues = { 0, 1, 2 }; public AssetBundleBuildTab() { m_advancedSettings = false; } public void OnEnable(Rect pos, EditorWindow parent) { m_buildTarget = (ValidBuildTarget)EditorPrefs.GetInt(kBuildPrefPrefix + "BuildTarget", (int)m_buildTarget); m_compression = (CompressOptions)EditorPrefs.GetInt(kBuildPrefPrefix + "Compression", (int)m_compression); m_toggleData = new List<ToggleData>(); m_toggleData.Add(new ToggleData( false, "Exclude Type Information", "Do not include type information within the asset bundle (don't write type tree).", BuildAssetBundleOptions.DisableWriteTypeTree)); m_toggleData.Add(new ToggleData( false, "Force Rebuild", "Force rebuild the asset bundles", BuildAssetBundleOptions.ForceRebuildAssetBundle)); m_toggleData.Add(new ToggleData( false, "Ignore Type Tree Changes", "Ignore the type tree changes when doing the incremental build check.", BuildAssetBundleOptions.IgnoreTypeTreeChanges)); m_toggleData.Add(new ToggleData( false, "Append Hash", "Append the hash to the assetBundle name.", BuildAssetBundleOptions.AppendHashToAssetBundleName)); m_toggleData.Add(new ToggleData( false, "Strict Mode", "Do not allow the build to succeed if any errors are reporting during it.", BuildAssetBundleOptions.StrictMode)); m_toggleData.Add(new ToggleData( false, "Dry Run Build", "Do a dry run build.", BuildAssetBundleOptions.DryRunBuild)); m_ForceRebuild = new ToggleData( false, "Clear Folders", "Will wipe out all contents of build directory as well as StreamingAssets/AssetBundles if you are choosing to copy build there."); m_CopyToStreaming = new ToggleData( false, "Copy to StreamingAssets", "After build completes, will copy all build content to " + m_streamingPath + " for use in stand-alone player."); m_TargetContent = new GUIContent("Build Target", "Choose target platform to build for."); m_CompressionContent = new GUIContent("Compression", "Choose no compress, standard (LZMA), or chunk based (LZ4)"); m_useDefaultPath = EditorPrefs.GetBool(kBuildPrefPrefix + "DefaultOutputBuildPath", m_useDefaultPath); } public void Update() { } public void OnGUI(Rect pos) { m_scrollPosition = EditorGUILayout.BeginScrollView(m_scrollPosition); bool newState = false; //basic options EditorGUILayout.Space(); GUILayout.BeginVertical(); ValidBuildTarget tgt = (ValidBuildTarget)EditorGUILayout.EnumPopup(m_TargetContent, m_buildTarget); if (tgt != m_buildTarget) { m_buildTarget = tgt; EditorPrefs.SetInt(kBuildPrefPrefix + "BuildTarget", (int)m_buildTarget); if(m_useDefaultPath) { m_outputPath = "AssetBundles/"; m_outputPath += m_buildTarget.ToString(); EditorUserBuildSettings.SetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath", m_outputPath); } } ////output path EditorGUILayout.Space(); GUILayout.BeginHorizontal(); var newPath = EditorGUILayout.TextField("Output Path", m_outputPath); if (newPath != m_outputPath) { m_useDefaultPath = false; m_outputPath = newPath; EditorUserBuildSettings.SetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath", m_outputPath); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); GUILayout.FlexibleSpace(); if (GUILayout.Button("Browse", GUILayout.MaxWidth(75f))) BrowseForFolder(); if (GUILayout.Button("Reset", GUILayout.MaxWidth(75f))) ResetPathToDefault(); if (string.IsNullOrEmpty(m_outputPath)) m_outputPath = EditorUserBuildSettings.GetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath"); GUILayout.EndHorizontal(); EditorGUILayout.Space(); newState = GUILayout.Toggle( m_ForceRebuild.state, m_ForceRebuild.content); if (newState != m_ForceRebuild.state) { EditorPrefs.SetBool(m_ForceRebuild.PrefKey, newState); m_ForceRebuild.state = newState; } newState = GUILayout.Toggle( m_CopyToStreaming.state, m_CopyToStreaming.content); if (newState != m_CopyToStreaming.state) { EditorPrefs.SetBool(m_CopyToStreaming.PrefKey, newState); m_CopyToStreaming.state = newState; } // advanced options EditorGUILayout.Space(); m_advancedSettings = EditorGUILayout.Foldout(m_advancedSettings, "Advanced Settings"); if(m_advancedSettings) { var indent = EditorGUI.indentLevel; EditorGUI.indentLevel = 1; CompressOptions cmp = (CompressOptions)EditorGUILayout.IntPopup( m_CompressionContent, (int)m_compression, m_CompressionOptions, m_CompressionValues); if (cmp != m_compression) { m_compression = cmp; EditorPrefs.SetInt(kBuildPrefPrefix + "Compression", (int)m_compression); } foreach (var tog in m_toggleData) { newState = EditorGUILayout.ToggleLeft( tog.content, tog.state); if (newState != tog.state) { EditorPrefs.SetBool(tog.PrefKey, newState); tog.state = newState; } } EditorGUILayout.Space(); EditorGUI.indentLevel = indent; } // build. EditorGUILayout.Space(); if (GUILayout.Button("Build") ) { ExecuteBuild(); } GUILayout.EndVertical(); EditorGUILayout.EndScrollView(); } private void ExecuteBuild() { if (string.IsNullOrEmpty(m_outputPath)) BrowseForFolder(); if (string.IsNullOrEmpty(m_outputPath)) //in case they hit "cancel" on the open browser { Debug.LogError("AssetBundle Build: No valid output path for build."); return; } if (m_ForceRebuild.state) { string message = "Do you want to delete all files in the directory " + m_outputPath; if (m_CopyToStreaming.state) message += " and " + m_streamingPath; message += "?"; if (EditorUtility.DisplayDialog("File delete confirmation", message, "Yes", "No")) { try { if (Directory.Exists(m_outputPath)) Directory.Delete(m_outputPath, true); if (m_CopyToStreaming.state) if (Directory.Exists(m_streamingPath)) Directory.Delete(m_streamingPath, true); } catch (System.Exception e) { Debug.LogException(e); } } } if (!Directory.Exists(m_outputPath)) Directory.CreateDirectory(m_outputPath); BuildAssetBundleOptions opt = BuildAssetBundleOptions.None; if (m_compression == CompressOptions.Uncompressed) opt |= BuildAssetBundleOptions.UncompressedAssetBundle; else if (m_compression == CompressOptions.ChunkBasedCompression) opt |= BuildAssetBundleOptions.ChunkBasedCompression; foreach (var tog in m_toggleData) { if (tog.state) opt |= tog.option; } BuildPipeline.BuildAssetBundles(m_outputPath, opt, (BuildTarget)m_buildTarget); AssetDatabase.Refresh(ImportAssetOptions.ForceUpdate); if(m_CopyToStreaming.state) DirectoryCopy(m_outputPath, m_streamingPath); } private static void DirectoryCopy(string sourceDirName, string destDirName) { // Get the subdirectories for the specified directory. DirectoryInfo dir = new DirectoryInfo(sourceDirName); // If the destination directory doesn't exist, create it. if (!Directory.Exists(destDirName)) { Directory.CreateDirectory(destDirName); } // Get the files in the directory and copy them to the new location. FileInfo[] files = dir.GetFiles(); foreach (FileInfo file in files) { string temppath = Path.Combine(destDirName, file.Name); file.CopyTo(temppath, false); } DirectoryInfo[] dirs = dir.GetDirectories(); foreach (DirectoryInfo subdir in dirs) { string temppath = Path.Combine(destDirName, subdir.Name); DirectoryCopy(subdir.FullName, temppath); } } private void BrowseForFolder() { m_useDefaultPath = false; EditorPrefs.SetBool(kBuildPrefPrefix + "DefaultOutputBuildPath", m_useDefaultPath); var newPath = EditorUtility.OpenFolderPanel("Bundle Folder", m_outputPath, string.Empty); if (!string.IsNullOrEmpty(newPath)) { var gamePath = System.IO.Path.GetFullPath("."); gamePath = gamePath.Replace("\\", "/"); if (newPath.StartsWith(gamePath)) newPath = newPath.Remove(0, gamePath.Length+1); m_outputPath = newPath; EditorUserBuildSettings.SetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath", m_outputPath); } } private void ResetPathToDefault() { m_useDefaultPath = true; EditorPrefs.SetBool(kBuildPrefPrefix + "DefaultOutputBuildPath", m_useDefaultPath); m_outputPath = "AssetBundles/"; m_outputPath += m_buildTarget.ToString(); EditorUserBuildSettings.SetPlatformSettings(EditorUserBuildSettings.activeBuildTarget.ToString(), "AssetBundleOutputPath", m_outputPath); } //Note: this is the provided BuildTarget enum with some entries removed as they are invalid in the dropdown public enum ValidBuildTarget { //NoTarget = -2, --doesn't make sense //iPhone = -1, --deprecated //BB10 = -1, --deprecated //MetroPlayer = -1, --deprecated StandaloneOSXUniversal = 2, StandaloneOSXIntel = 4, StandaloneWindows = 5, WebPlayer = 6, WebPlayerStreamed = 7, iOS = 9, PS3 = 10, XBOX360 = 11, Android = 13, StandaloneLinux = 17, StandaloneWindows64 = 19, WebGL = 20, WSAPlayer = 21, StandaloneLinux64 = 24, StandaloneLinuxUniversal = 25, WP8Player = 26, StandaloneOSXIntel64 = 27, BlackBerry = 28, Tizen = 29, PSP2 = 30, PS4 = 31, PSM = 32, XboxOne = 33, SamsungTV = 34, N3DS = 35, WiiU = 36, tvOS = 37, Switch = 38 } } }
/* Copyright 2019 Esri Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Data; using System.Collections.Generic; using System.Text.RegularExpressions; using System.Xml; using System.IO; using System.Threading; using System.Timers; using System.Drawing; using System.Drawing.Imaging; using System.Windows.Forms; using System.Runtime.InteropServices; using ESRI.ArcGIS.ADF.BaseClasses; using ESRI.ArcGIS.ADF.CATIDs; using ESRI.ArcGIS.esriSystem; using ESRI.ArcGIS.Carto; using ESRI.ArcGIS.Geometry; using ESRI.ArcGIS.Display; using ESRI.ArcGIS.Controls; using ESRI.ArcGIS.EngineCore; using ESRI.ArcGIS.Geodatabase; using ESRI.ArcGIS.DataSourcesFile; namespace RSSWeatherGraphicTracker { #region WeatherItemEventArgs class members public sealed class WeatherItemEventArgs : EventArgs { private int m_iconId; private long m_zipCode; private double m_x; private double m_y; private int m_iconWidth; private int m_iconHeight; public WeatherItemEventArgs(int iconId, long zipCode, double X, double Y, int iconWidth, int iconHeight) { m_iconId = iconId; m_zipCode = zipCode; m_x = X; m_y = Y; m_iconWidth = iconWidth; m_iconHeight = iconHeight; } public int IconID { get { return m_iconId; } } public long ZipCode { get { return m_zipCode; } } public double mapY { get { return m_y; } } public double mapX { get { return m_x; } } } #endregion //declare delegates for the event handling public delegate void WeatherItemAdded(object sender, WeatherItemEventArgs args); public delegate void WeatherItemsUpdated(object sender, EventArgs args); class RSSWeather { private sealed class InvokeHelper : Control { //delegate used to pass the invoked method to the main thread public delegate void RefreshWeatherItemHelper(WeatherItemEventArgs weatherItemInfo); private RSSWeather m_weather = null; public InvokeHelper(RSSWeather rssWeather) { m_weather = rssWeather; CreateHandle(); CreateControl(); } public void RefreshWeatherItem(WeatherItemEventArgs weatherItemInfo) { try { // Invoke the RefreshInternal through its delegate if (!this.IsDisposed && this.IsHandleCreated) Invoke(new RefreshWeatherItemHelper(RefreshWeatherItemInvoked), new object[] { weatherItemInfo }); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } private void RefreshWeatherItemInvoked(WeatherItemEventArgs weatherItemInfo) { if (m_weather != null) m_weather.UpdateTracker(weatherItemInfo); } } #region class members private System.Timers.Timer m_timer = null; private Thread m_updateThread = null; private string m_iconFolder = string.Empty; private DataTable m_weatherItemTable = null; private DataTable m_symbolTable = null; private DataTable m_locations = null; private string m_dataFolder = string.Empty; private string m_installationFolder = string.Empty; private IPoint m_point = null; private ISpatialReference m_SRWGS84 = null; private IBasicMap m_mapOrGlobe = null; private ISimpleTextSymbol m_textSymbol = null; private IGraphicTracker m_graphicTracker = null; private InvokeHelper m_invokeHelper = null; //weather items events public event WeatherItemAdded OnWeatherItemAdded; public event WeatherItemsUpdated OnWeatherItemsUpdated; #endregion public RSSWeather() { //get the directory for the cache. If it does not exist, create it. m_dataFolder = System.IO.Path.Combine(System.IO.Path.GetTempPath(), "RSSWeather"); if (!System.IO.Directory.Exists(m_dataFolder)) { System.IO.Directory.CreateDirectory(m_dataFolder); } m_iconFolder = m_dataFolder; m_installationFolder = ESRI.ArcGIS.RuntimeManager.ActiveRuntime.Path; } public void Init(IBasicMap mapOrGlobe) { System.Diagnostics.Trace.WriteLine("Init - Thread ID: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()); if (mapOrGlobe == null) return; m_mapOrGlobe = mapOrGlobe; try { //initialize the tables (main table as well as the symbols table) InitializeTables(); //get the location list from a featureclass (US major cities) and synchronize it with the //cached information in case it exists. if (null == m_locations) InitializeLocations(); m_point = new PointClass(); m_SRWGS84 = CreateGeographicSpatialReference(); m_point.SpatialReference = m_SRWGS84; m_textSymbol = new TextSymbolClass() as ISimpleTextSymbol; m_textSymbol.Font = ToFontDisp(new Font("Tahoma", 10.0f, FontStyle.Bold)); m_textSymbol.Size = 10.0; m_textSymbol.Color = (IColor)ToRGBColor(Color.FromArgb(0, 255, 0)); m_textSymbol.XOffset = 0.0; m_textSymbol.YOffset = 16.0; m_graphicTracker = new GraphicTrackerClass(); m_graphicTracker.Initialize(mapOrGlobe as object); if (m_weatherItemTable.Rows.Count > 0) PopulateGraphicTracker(); m_invokeHelper = new InvokeHelper(this); this.OnWeatherItemAdded += new WeatherItemAdded(OnWeatherItemAddedEvent); //instantiate the timer for the weather update thread m_timer = new System.Timers.Timer(1000); m_timer.Elapsed += new ElapsedEventHandler(OnUpdateTimer); //enable the update timer m_timer.Enabled = true; } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } public void Remove() { this.OnWeatherItemAdded -= new WeatherItemAdded(OnWeatherItemAddedEvent); m_invokeHelper = null; m_timer.Enabled = false; // wait for the update thread to exit m_updateThread.Join(); m_graphicTracker.RemoveAll(); m_graphicTracker = null; } public void UpdateTracker(WeatherItemEventArgs weatherItemInfo) { System.Diagnostics.Trace.WriteLine("UpdateTracker - Thread ID: " + System.Threading.Thread.CurrentThread.ManagedThreadId.ToString()); if (m_graphicTracker == null) throw new Exception("Graphic tracker is not initialized!"); // 1. lock the m_weatherItemTable and get the record DataRow row; lock (m_weatherItemTable) { row = m_weatherItemTable.Rows.Find(weatherItemInfo.ZipCode); if (row == null) return; // 2. get the symbol for the item IGraphicTrackerSymbol symbol = GetSymbol(weatherItemInfo.IconID, Convert.ToString(row[7])); if (symbol == null) return; string label = string.Format("{0}, {1}?F", Convert.ToString(row[2]), Convert.ToString(row[5])); // 3. check whether it has a tracker ID (not equals -1) int trackerID = Convert.ToInt32(row[15]); //m_graphicTracker.SuspendUpdate = true; m_point.PutCoords(weatherItemInfo.mapX, weatherItemInfo.mapY); m_point.SpatialReference = m_SRWGS84; m_point.Project(m_mapOrGlobe.SpatialReference); if (trackerID == -1) // new tracker { trackerID = m_graphicTracker.Add(m_point as IGeometry, symbol); m_graphicTracker.SetTextSymbol(trackerID, m_textSymbol); row[15] = trackerID; } else // existing tracker { m_graphicTracker.MoveTo(trackerID, m_point.X, m_point.Y, 0); m_graphicTracker.SetSymbol(trackerID, symbol); } m_graphicTracker.SetLabel(trackerID, label); row.AcceptChanges(); //m_graphicTracker.SuspendUpdate = false; } } #region private utility methods void PopulateGraphicTracker() { m_graphicTracker.SuspendUpdate = true; foreach (DataRow row in m_weatherItemTable.Rows) { IGraphicTrackerSymbol symbol = GetSymbol(Convert.ToInt32(row[8]), Convert.ToString(row[7])); if (symbol == null) continue; string label = string.Format("{0}, {1}?F", Convert.ToString(row[2]), Convert.ToString(row[5])); m_point.PutCoords(Convert.ToDouble(row[4]), Convert.ToDouble(row[3])); int trackerID = m_graphicTracker.Add(m_point as IGeometry, symbol); m_graphicTracker.SetTextSymbol(trackerID, m_textSymbol); m_graphicTracker.SetScaleMode(trackerID, esriGTScale.esriGTScaleAuto); m_graphicTracker.SetOrientationMode(trackerID, esriGTOrientation.esriGTOrientationAutomatic); m_graphicTracker.SetElevationMode(trackerID, esriGTElevation.esriGTElevationClampToGround); m_graphicTracker.SetLabel(trackerID, label); row[15] = trackerID; row.AcceptChanges(); } m_graphicTracker.SuspendUpdate = false; } /// <summary> /// create a WGS1984 geographic coordinate system. /// In this case, the underlying data provided by the service is in WGS1984. /// </summary> /// <returns></returns> private ISpatialReference CreateGeographicSpatialReference() { ISpatialReferenceFactory spatialRefFatcory = new SpatialReferenceEnvironmentClass(); IGeographicCoordinateSystem geoCoordSys; geoCoordSys = spatialRefFatcory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984); geoCoordSys.SetFalseOriginAndUnits(-180.0, -180.0, 5000000.0); geoCoordSys.SetZFalseOriginAndUnits(0.0, 100000.0); geoCoordSys.SetMFalseOriginAndUnits(0.0, 100000.0); return geoCoordSys as ISpatialReference; } /// <summary> /// run the thread that does the update of the weather data /// </summary> /// <param name="sender"></param> /// <param name="e"></param> private void OnUpdateTimer(object sender, ElapsedEventArgs e) { m_timer.Interval = 2700000; //(45 minutes) m_updateThread = new Thread(new ThreadStart(ThreadProc)); //run the update thread m_updateThread.Start(); } /// <summary> /// the main update thread for the data. /// </summary> /// <remarks>Since the information is coming from a web service which might /// take a while to respond, it is not logical to let the application hang while waiting /// for response. Therefore, running the request on a different thread frees the application to /// continue working while waiting for a response. /// Please note that in this case, synchronization of shared resources must be addressed, /// otherwise you might end up getting unexpected results.</remarks> private void ThreadProc() { try { long lZipCode; //iterate through all the records in the main table and update it against //the information from the website. foreach (DataRow r in m_locations.Rows) { //put the thread to sleep in order not to overwhelm the RSS website //System.Threading.Thread.Sleep(200); //get the zip code of the record (column #1) lZipCode = Convert.ToInt32(r[1]); //make the request and update the item AddWeatherItem(lZipCode, 0.0, 0.0); } //serialize the tables onto the local machine DataSet ds = new DataSet(); ds.Tables.Add(m_weatherItemTable); ds.WriteXml(System.IO.Path.Combine(m_dataFolder, "Weather.xml")); ds.Tables.Remove(m_weatherItemTable); ds.Dispose(); GC.Collect(); //fire an event to notify update of the weather items if(OnWeatherItemsUpdated != null) OnWeatherItemsUpdated(this, new EventArgs()); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } /// <summary> /// given a bitmap url, saves it on the local machine and returns its size /// </summary> /// <param name="iconPath"></param> /// <param name="width"></param> /// <param name="height"></param> private Bitmap DownloadIcon(string iconPath, out int width, out int height) { //if the icon does not exist on the local machine, get it from RSS site string iconFileName = System.IO.Path.Combine(m_iconFolder, System.IO.Path.GetFileNameWithoutExtension(iconPath) + ".png"); width = 0; height = 0; Bitmap bitmap = null; if (!File.Exists(iconFileName)) { using (System.Net.WebClient webClient = new System.Net.WebClient()) { //open a readable stream to download the bitmap using (System.IO.Stream stream = webClient.OpenRead(iconPath)) { bitmap = new Bitmap(stream, true); //save the image as a bitmap in the icons folder bitmap.Save(iconFileName, ImageFormat.Png); //get the bitmap's dimensions width = bitmap.Width; height = bitmap.Height; } } } else { //get the bitmap's dimensions { bitmap = new Bitmap(iconFileName); width = bitmap.Width; height = bitmap.Height; } } return bitmap; } /// <summary> /// get the specified symbol from the symbols table. /// </summary> /// <param name="iconCode"></param> /// <param name="dbr"></param> /// <returns></returns> private IGraphicTrackerSymbol GetSymbol(int iconCode, string iconPath) { IGraphicTrackerSymbol symbol; int iconWidth, iconHeight; Bitmap bitmap = null; //search for an existing symbol in the table DataRow r = m_symbolTable.Rows.Find(iconCode); if (r == null) //in case that the symbol does not exist in the table, create a new entry { r = m_symbolTable.NewRow(); r[1] = iconCode; //Initialize the picture marker symbol symbol = InitializeSymbol(iconPath, out iconWidth, out iconHeight, out bitmap); if (null == symbol) return null; //update the symbol table lock (m_symbolTable) { r[2] = symbol; r[3] = iconWidth; r[4] = iconHeight; r[5] = bitmap; m_symbolTable.Rows.Add(r); } } else { if (r[2] is DBNull) //in case that the record exists but the symbol hasn't been initialized { //Initialize the symbol symbol = InitializeSymbol(iconPath, out iconWidth, out iconHeight, out bitmap); if (null == symbol) return null; //update the symbol table lock (m_symbolTable) { r[2] = symbol; r[5] = bitmap; r.AcceptChanges(); } } else //the record exists in the table and the symbol has been initialized //get the symbol symbol = r[2] as IGraphicTrackerSymbol; } //return the requested symbol return symbol; } /// <summary> /// Initialize a character marker symbol for a given bitmap path /// </summary> /// <param name="iconPath"></param> /// <param name="iconWidth"></param> /// <param name="iconHeight"></param> /// <returns></returns> private IGraphicTrackerSymbol InitializeSymbol(string iconPath, out int iconWidth, out int iconHeight, out Bitmap bitmap) { iconWidth = iconHeight = 0; bitmap = null; try { //make sure that the icon exit on dist or else download it DownloadIcon(iconPath, out iconWidth, out iconHeight); string iconFileName = System.IO.Path.Combine(m_iconFolder, System.IO.Path.GetFileNameWithoutExtension(iconPath) + ".png"); if (!System.IO.File.Exists(iconFileName)) return null; IGraphicTrackerSymbol symbol = m_graphicTracker.CreateSymbolFromPath(iconFileName, iconFileName); return symbol; } catch { return null; } } /// <summary> /// Makes a request against RSS Weather service and add update the table /// </summary> /// <param name="zipCode"></param> /// <param name="Lat"></param> /// <param name="Lon"></param> private void AddWeatherItem(long zipCode, double Lat, double Lon) { try { string cityName; double lat, lon; int temp; string condition; string desc; string iconPath; string day; string date; int low; int high; int iconCode; int iconWidth = 52; //default values int iconHeight = 52; Bitmap bitmap = null; DataRow dbr = m_weatherItemTable.Rows.Find(zipCode); if (dbr != null) { // get the date DateTime updateDate = Convert.ToDateTime(dbr[14]); TimeSpan ts = DateTime.Now - updateDate; // if the item had been updated in the past 15 minutes, simply bail out. if (ts.TotalMinutes < 15) return; } //the base URL for the service string url = "http://xml.weather.yahoo.com/forecastrss?p="; //the RegEx used to extract the icon path from the HTML tag string regxQry = "(http://(\\\")?(.*?\\.gif))"; XmlTextReader reader = null; XmlDocument doc; XmlNode node; try { //make the request and get the result back into XmlReader reader = new XmlTextReader(url + zipCode.ToString()); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); return; } //load the XmlReader to an xml doc doc = new XmlDocument(); doc.Load(reader); //set an XmlNamespaceManager since we have to make explicit namespace searches XmlNamespaceManager xmlnsManager = new System.Xml.XmlNamespaceManager(doc.NameTable); //Add the namespaces used in the xml doc to the XmlNamespaceManager. xmlnsManager.AddNamespace("yweather", "http://xml.weather.yahoo.com/ns/rss/1.0"); xmlnsManager.AddNamespace("geo", "http://www.w3.org/2003/01/geo/wgs84_pos#"); //make sure that the node exists node = doc.DocumentElement.SelectSingleNode("/rss/channel/yweather:location/@city", xmlnsManager); if (null == node) return; //get the city name cityName = doc.DocumentElement.SelectSingleNode("/rss/channel/yweather:location/@city", xmlnsManager).InnerXml; if (Lat == 0.0 && Lon == 0.0) { //in case that the caller did not specify a coordinate, get the default coordinate from the service lat = Convert.ToDouble(doc.DocumentElement.SelectSingleNode("/rss/channel/item/geo:lat", xmlnsManager).InnerXml); lon = Convert.ToDouble(doc.DocumentElement.SelectSingleNode("/rss/channel/item/geo:long", xmlnsManager).InnerXml); } else { lat = Lat; lon = Lon; } //extract the rest of the information from the RSS response condition = doc.DocumentElement.SelectSingleNode("/rss/channel/item/yweather:condition/@text", xmlnsManager).InnerXml; iconCode = Convert.ToInt32(doc.DocumentElement.SelectSingleNode("/rss/channel/item/yweather:condition/@code", xmlnsManager).InnerXml); temp = Convert.ToInt32(doc.DocumentElement.SelectSingleNode("/rss/channel/item/yweather:condition/@temp", xmlnsManager).InnerXml); desc = doc.DocumentElement.SelectSingleNode("/rss/channel/item/description").InnerXml; day = doc.DocumentElement.SelectSingleNode("/rss/channel/item/yweather:forecast/@day", xmlnsManager).InnerXml; date = doc.DocumentElement.SelectSingleNode("/rss/channel/item/yweather:forecast/@date", xmlnsManager).InnerXml; low = Convert.ToInt32(doc.DocumentElement.SelectSingleNode("/rss/channel/item/yweather:forecast/@low", xmlnsManager).InnerXml); high = Convert.ToInt32(doc.DocumentElement.SelectSingleNode("/rss/channel/item/yweather:forecast/@high", xmlnsManager).InnerXml); //use regex in order to extract the icon name from the html script Match m = Regex.Match(desc, regxQry); if (m.Success) { iconPath = m.Value; //add the icon ID to the symbology table DataRow tr = m_symbolTable.Rows.Find(iconCode); if (null == tr) { //get the icon from the website bitmap = DownloadIcon(iconPath, out iconWidth, out iconHeight); //create a new record tr = m_symbolTable.NewRow(); tr[1] = iconCode; tr[3] = iconWidth; tr[4] = iconHeight; tr[5] = bitmap; //update the symbol table. The initialization of the symbol cannot take place in here, since //this code gets executed on a background thread. lock (m_symbolTable) { m_symbolTable.Rows.Add(tr); } } else //get the icon's dimensions from the table { //get the icon's dimensions from the table iconWidth = Convert.ToInt32(tr[3]); iconHeight = Convert.ToInt32(tr[4]); } } else { iconPath = ""; } //test whether the record already exists in the table. if (null == dbr) //in case that the record does not exist { //create a new record dbr = m_weatherItemTable.NewRow(); if (!m_weatherItemTable.Columns[0].AutoIncrement) dbr[0] = Convert.ToInt32(DateTime.Now.Millisecond); //add the item to the table lock (m_weatherItemTable) { dbr[1] = zipCode; dbr[2] = cityName; dbr[3] = lat; dbr[4] = lon; dbr[5] = temp; dbr[6] = condition; dbr[7] = iconPath; dbr[8] = iconCode; dbr[9] = day; dbr[10] = date; dbr[11] = low; dbr[12] = high; dbr[13] = false; dbr[14] = DateTime.Now; dbr[15] = -1; m_weatherItemTable.Rows.Add(dbr); } } else //in case that the record exists, just update it { //update the record lock (m_weatherItemTable) { dbr[5] = temp; dbr[6] = condition; dbr[7] = iconPath; dbr[8] = iconCode; dbr[9] = day; dbr[10] = date; dbr[11] = low; dbr[12] = high; dbr[14] = DateTime.Now; dbr.AcceptChanges(); } } //fire an event to notify the user that the item has been updated if (OnWeatherItemAdded != null) { WeatherItemEventArgs weatherItemEventArgs = new WeatherItemEventArgs(iconCode, zipCode, lon, lat, iconWidth, iconHeight); OnWeatherItemAdded(this, weatherItemEventArgs); } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine("AddWeatherItem: " + ex.Message); } } private IRgbColor ToRGBColor(System.Drawing.Color color) { IRgbColor rgbColor = new RgbColorClass(); rgbColor.Red = color.R; rgbColor.Green = color.G; rgbColor.Blue = color.B; return rgbColor; } private stdole.IFontDisp ToFontDisp(System.Drawing.Font font) { stdole.IFont aFont; aFont = new stdole.StdFontClass(); aFont.Name = font.Name; aFont.Size = (decimal)font.Size; aFont.Bold = font.Bold; aFont.Italic = font.Italic; aFont.Strikethrough = font.Strikeout; aFont.Underline = font.Underline; return aFont as stdole.IFontDisp; } /// <summary> /// initialize the main table as well as the symbols table. /// The base class calls new on the table and adds a default ID field. /// </summary> private void InitializeTables() { string path = System.IO.Path.Combine(m_dataFolder, "Weather.xml"); //In case that there is no existing cache on the local machine, create the table. if (!System.IO.File.Exists(path)) { //create the table the table in addition to the default 'ID' and 'Geometry' m_weatherItemTable = new DataTable("RECORDS"); m_weatherItemTable.Columns.Add("ID", typeof(long)); //0 m_weatherItemTable.Columns.Add("ZIPCODE", typeof(long)); //1 m_weatherItemTable.Columns.Add("CITYNAME", typeof(string)); //2 m_weatherItemTable.Columns.Add("LAT", typeof(double)); //3 m_weatherItemTable.Columns.Add("LON", typeof(double)); //4 m_weatherItemTable.Columns.Add("TEMP", typeof(int)); //5 m_weatherItemTable.Columns.Add("CONDITION", typeof(string)); //6 m_weatherItemTable.Columns.Add("ICONNAME", typeof(string)); //7 m_weatherItemTable.Columns.Add("ICONID", typeof(int)); //8 m_weatherItemTable.Columns.Add("DAY", typeof(string)); //9 m_weatherItemTable.Columns.Add("DATE", typeof(string)); //10 m_weatherItemTable.Columns.Add("LOW", typeof(string)); //11 m_weatherItemTable.Columns.Add("HIGH", typeof(string)); //12 m_weatherItemTable.Columns.Add("SELECTED", typeof(bool)); //13 m_weatherItemTable.Columns.Add("UPDATEDATE", typeof(DateTime)); //14 m_weatherItemTable.Columns.Add("TRACKERID", typeof(long)); //15 //set the ID column to be auto increment m_weatherItemTable.Columns[0].AutoIncrement = true; m_weatherItemTable.Columns[0].ReadOnly = true; //the zipCode column must be the unique and nut allow null m_weatherItemTable.Columns[1].Unique = true; // set the ZIPCODE primary key for the table m_weatherItemTable.PrimaryKey = new DataColumn[] { m_weatherItemTable.Columns["ZIPCODE"] }; } else //in case that the local cache exists, simply load the tables from the cache. { DataSet ds = new DataSet(); ds.ReadXml(path); m_weatherItemTable = ds.Tables["RECORDS"]; if (null == m_weatherItemTable) throw new Exception("Cannot find 'RECORDS' table"); if (16 != m_weatherItemTable.Columns.Count) throw new Exception("Table 'RECORDS' does not have all required columns"); m_weatherItemTable.Columns[0].ReadOnly = true; // set the ZIPCODE primary key for the table m_weatherItemTable.PrimaryKey = new DataColumn[] { m_weatherItemTable.Columns["ZIPCODE"] }; //synchronize the locations table foreach (DataRow r in m_weatherItemTable.Rows) { try { //in case that the locations table does not exists, create and initialize it if (null == m_locations) InitializeLocations(); //get the zipcode for the record string zip = Convert.ToString(r[1]); //make sure that there is no existing record with that zipCode already in the //locations table. DataRow[] rows = m_locations.Select("ZIPCODE = " + zip); if (0 == rows.Length) { DataRow rec = m_locations.NewRow(); rec[1] = Convert.ToInt64(r[1]); //zip code rec[2] = Convert.ToString(r[2]); //city name //add the new record to the locations table lock (m_locations) { m_locations.Rows.Add(rec); } } } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } //dispose the DS ds.Tables.Remove(m_weatherItemTable); ds.Dispose(); GC.Collect(); } //initialize the symbol map table m_symbolTable = new DataTable("Symbology"); //add the columns to the table m_symbolTable.Columns.Add("ID", typeof(int)); //0 m_symbolTable.Columns.Add("ICONID", typeof(int)); //1 m_symbolTable.Columns.Add("SYMBOL", typeof(IGraphicTrackerSymbol)); //2 m_symbolTable.Columns.Add("SYMBOLWIDTH", typeof(int)); //3 m_symbolTable.Columns.Add("SYMBOLHEIGHT", typeof(int)); //4 m_symbolTable.Columns.Add("BITMAP", typeof(Bitmap)); //5 //set the ID column to be auto increment m_symbolTable.Columns[0].AutoIncrement = true; m_symbolTable.Columns[0].ReadOnly = true; m_symbolTable.Columns[1].AllowDBNull = false; m_symbolTable.Columns[1].Unique = true; //set ICONID as the primary key for the table m_symbolTable.PrimaryKey = new DataColumn[] { m_symbolTable.Columns["ICONID"] }; } /// <summary> /// Initialize the location table. Gets the location from a featureclass /// </summary> private void InitializeLocations() { //create a new instance of the location table m_locations = new DataTable(); //add fields to the table m_locations.Columns.Add("ID", typeof(int)); m_locations.Columns.Add("ZIPCODE", typeof(long)); m_locations.Columns.Add("CITYNAME", typeof(string)); m_locations.Columns[0].AutoIncrement = true; m_locations.Columns[0].ReadOnly = true; //set ZIPCODE as the primary key for the table m_locations.PrimaryKey = new DataColumn[] { m_locations.Columns["ZIPCODE"] }; PopulateLocationsTable(); } /// <summary> /// Load the information from the MajorCities featureclass to the locations table /// </summary> private void PopulateLocationsTable() { string path = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments); path = System.IO.Path.Combine(path, @"ArcGIS\data\USZipCodeData\"); //open the featureclass IWorkspaceFactory wf = new ShapefileWorkspaceFactoryClass() as IWorkspaceFactory; IWorkspace ws = wf.OpenFromFile(path, 0); IFeatureWorkspace fw = ws as IFeatureWorkspace; IFeatureClass featureClass = fw.OpenFeatureClass("ZipCode_Boundaries_US_Major_Cities"); //map the name and zip fields int zipIndex = featureClass.FindField("ZIP"); int nameIndex = featureClass.FindField("NAME"); string cityName; long zip; try { //iterate through the features and add the information to the table IFeatureCursor fCursor = null; fCursor = featureClass.Search(null, true); IFeature feature = fCursor.NextFeature(); int index = 0; while (null != feature) { object obj = feature.get_Value(nameIndex); if (obj == null) continue; cityName = Convert.ToString(obj); obj = feature.get_Value(zipIndex); if (obj == null) continue; zip = long.Parse(Convert.ToString(obj)); if (zip <= 0) continue; //add the current location to the location table DataRow r = m_locations.Rows.Find(zip); if (null == r) { r = m_locations.NewRow(); r[1] = zip; r[2] = cityName; lock (m_locations) { m_locations.Rows.Add(r); } } feature = fCursor.NextFeature(); index++; } //release the feature cursor Marshal.ReleaseComObject(fCursor); } catch (Exception ex) { System.Diagnostics.Trace.WriteLine(ex.Message); } } /// <summary> /// weather ItemAdded event handler /// </summary> /// <param name="sender"></param> /// <param name="args"></param> /// <remarks>gets fired when an item is added to the table</remarks> private void OnWeatherItemAddedEvent(object sender, WeatherItemEventArgs args) { // use the invoke helper since this event gets fired on a different thread m_invokeHelper.RefreshWeatherItem(args); } #endregion } }
#region License, Terms and Author(s) // // ELMAH - Error Logging Modules and Handlers for ASP.NET // Copyright (c) 2004-9 Atif Aziz. All rights reserved. // // Author(s): // // Scott Wilson <sw@scratchstudio.net> // Atif Aziz, http://www.raboof.com // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion [assembly: Elmah.Scc("$Id: XmlFileErrorLog.cs 641 2009-06-01 17:38:40Z azizatif $")] namespace Elmah { #region Imports using System; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.CompilerServices; using System.Text; using System.Xml; using System.Collections.Generic; using IDictionary = System.Collections.IDictionary; #endregion /// <summary> /// An <see cref="ErrorLog"/> implementation that uses XML files stored on /// disk as its backing store. /// </summary> public class XmlFileErrorLog : ErrorLog { private readonly string _logPath; /// <summary> /// Initializes a new instance of the <see cref="XmlFileErrorLog"/> class /// using a dictionary of configured settings. /// </summary> public XmlFileErrorLog(IDictionary config) { if (config == null) throw new ArgumentNullException("config"); var logPath = config.Find("logPath", string.Empty); if (logPath.Length == 0) { // // For compatibility reasons with older version of this // implementation, we also try "LogPath". // logPath = config.Find("LogPath", string.Empty); if (logPath.Length == 0) throw new ApplicationException("Log path is missing for the XML file-based error log."); } if (logPath.StartsWith("~/")) logPath = MapPath(logPath); _logPath = logPath; } /// <remarks> /// This method is excluded from inlining so that if /// HostingEnvironment does not need JIT-ing if it is not implicated /// by the caller. /// </remarks> [ MethodImpl(MethodImplOptions.NoInlining) ] private static string MapPath(string path) { return System.Web.Hosting.HostingEnvironment.MapPath(path); } /// <summary> /// Initializes a new instance of the <see cref="XmlFileErrorLog"/> class /// to use a specific path to store/load XML files. /// </summary> public XmlFileErrorLog(string logPath) { if (logPath == null) throw new ArgumentNullException("logPath"); if (logPath.Length == 0) throw new ArgumentException(null, "logPath"); _logPath = logPath; } /// <summary> /// Gets the path to where the log is stored. /// </summary> public virtual string LogPath { get { return _logPath; } } /// <summary> /// Gets the name of this error log implementation. /// </summary> public override string Name { get { return "XML File-Based Error Log"; } } /// <summary> /// Logs an error to the database. /// </summary> /// <remarks> /// Logs an error as a single XML file stored in a folder. XML files are named with a /// sortable date and a unique identifier. Currently the XML files are stored indefinately. /// As they are stored as files, they may be managed using standard scheduled jobs. /// </remarks> public override string Log(Error error) { var errorId = Guid.NewGuid().ToString(); var timeStamp = DateTime.UtcNow.ToString("yyyy-MM-ddHHmmssZ", CultureInfo.InvariantCulture); var path = Path.Combine(LogPath, string.Format(@"error-{0}-{1}.xml", timeStamp, errorId)); using (var writer = new XmlTextWriter(path, Encoding.UTF8)) { writer.Formatting = Formatting.Indented; writer.WriteStartElement("error"); writer.WriteAttributeString("errorId", errorId); ErrorXml.Encode(error, writer); writer.WriteEndElement(); writer.Flush(); } return errorId; } /// <summary> /// Returns a page of errors from the folder in descending order /// of logged time as defined by the sortable filenames. /// </summary> public override int GetErrors(int pageIndex, int pageSize, IList<ErrorLogEntry> errorEntryList) { if (pageIndex < 0) throw new ArgumentOutOfRangeException("pageIndex", pageIndex, null); if (pageSize < 0) throw new ArgumentOutOfRangeException("pageSize", pageSize, null); var logPath = LogPath; var dir = new DirectoryInfo(logPath); var infos = dir.GetFiles("error-*.xml"); if (!infos.Any()) return 0; var files = dir.GetFiles("error-*.xml") .Where(info => IsUserFile(info.Attributes)) .OrderBy(info => info.Name, StringComparer.OrdinalIgnoreCase) .Select(info => Path.Combine(logPath, info.Name)) .Reverse() .ToArray(); if (errorEntryList != null) { var entries = files.Skip(pageIndex * pageSize) .Take(pageSize) .Select(file => { using (var reader = XmlReader.Create(file)) { if (!reader.IsStartElement("error")) return null; var id = reader.GetAttribute("errorId"); var error = ErrorXml.Decode(reader); return new ErrorLogEntry(this, id, error); } }); foreach (var entry in entries) errorEntryList.Add(entry); } return files.Length; // Return total } /// <summary> /// Returns the specified error from the filesystem, or throws an exception if it does not exist. /// </summary> public override ErrorLogEntry GetError(string id) { try { id = (new Guid(id)).ToString(); // validate GUID } catch (FormatException e) { throw new ArgumentException(e.Message, id, e); } var file = new DirectoryInfo(LogPath).GetFiles(string.Format("error-*-{0}.xml", id)) .FirstOrDefault(); if (file == null) throw new FileNotFoundException(string.Format("Cannot locate error file for error with ID {0}.", id)); if (!IsUserFile(file.Attributes)) return null; using (var reader = XmlReader.Create(file.FullName)) return new ErrorLogEntry(this, id, ErrorXml.Decode(reader)); } private static bool IsUserFile(FileAttributes attributes) { return 0 == (attributes & (FileAttributes.Directory | FileAttributes.Hidden | FileAttributes.System)); } } }
using UnityEngine; using UnityEditor; public class Create3DAssets : MonoBehaviour { public Texture3D texture3D; public Texture2D texture2D; public int n; public Light _light; public float absorption; public float lightIntensityScale; //public bool onlyGenerateTexture3D; public string texture3DName = "pyroclasticNoise"; private Mesh m; // Use this for initialization public void Start () { /*if (onlyGenerateTexture3D) { Generate3DTexture(); save3DTexture(); } */ CreateMesh(); //Generate3DTexture(); Vector4 localEyePos = transform.worldToLocalMatrix.MultiplyPoint(Camera.main.transform.position); Vector4 localLightPos = transform.worldToLocalMatrix.MultiplyPoint(_light.transform.position); Renderer renderer = GetComponent<Renderer>().GetComponent<Renderer>(); renderer.material.SetVector("g_eyePos", localEyePos); renderer.material.SetVector("g_lightPos", localLightPos); renderer.material.SetFloat("g_lightIntensity", _light.intensity); renderer.material.SetFloat("g_absorption", absorption); } void LateUpdate() { //if (onlyGenerateTexture3D) //return; Renderer renderer = GetComponent<Renderer>().GetComponent<Renderer>(); Vector4 localEyePos = transform.worldToLocalMatrix.MultiplyPoint(Camera.main.transform.position); localEyePos += new Vector4(0.5f,0.5f,0.5f,0.0f); renderer.material.SetVector("g_eyePos", localEyePos); Vector4 localLightPos = transform.worldToLocalMatrix.MultiplyPoint( _light.transform.position); renderer.material.SetVector("g_lightPos", localLightPos); renderer.material.SetFloat("g_lightIntensity", _light.intensity * lightIntensityScale); } private Mesh CreateMesh() { m = new Mesh(); CreateCube(m); m.RecalculateBounds(); MeshFilter mf = (MeshFilter)transform.GetComponent(typeof(MeshFilter)); mf.mesh = m; return m; } void CreateCube(Mesh m) { Vector3[] vertices = new Vector3[24]; Vector2[] uv = new Vector2[24]; Color[] colors = new Color[24]; Vector3[] normals = new Vector3[24]; int[] triangles = new int[36]; int i = 0; int ti = 0; //Front vertices[i] = new Vector3(-0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(0,0,0); i++; vertices[i] = new Vector3(0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(1,0,0); i++; vertices[i] = new Vector3(0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(1,1,0); i++; vertices[i] = new Vector3(-0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(0,1,0); i++; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-3; triangles[ti++] = i-4; triangles[ti++] = i-1; triangles[ti++] = i-2; //Back vertices[i] = new Vector3(-0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(0,0,1); i++; vertices[i] = new Vector3(0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(1,0,1); i++; vertices[i] = new Vector3(0.5f,0.5f,0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(1,1,1); i++; vertices[i] = new Vector3(-0.5f,0.5f,0.5f); normals[i] = new Vector3(0,0,-1); colors[i] = new Color(0,1,1); i++; triangles[ti++] = i-4; triangles[ti++] = i-3; triangles[ti++] = i-2; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-1; //Top vertices[i] = new Vector3(-0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,1,0); i++; vertices[i] = new Vector3(0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,1,0); i++; vertices[i] = new Vector3(0.5f,0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,1,1); i++; vertices[i] = new Vector3(-0.5f,0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,1,1); i++; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-3; triangles[ti++] = i-4; triangles[ti++] = i-1; triangles[ti++] = i-2; //Bottom vertices[i] = new Vector3(-0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,0,0); i++; vertices[i] = new Vector3(0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,0,0); i++; vertices[i] = new Vector3(0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,0,1); i++; vertices[i] = new Vector3(-0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,0,1); i++; triangles[ti++] = i-4; triangles[ti++] = i-3; triangles[ti++] = i-2; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-1; //Right vertices[i] = new Vector3(0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,0,0); i++; vertices[i] = new Vector3(0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,1,0); i++; vertices[i] = new Vector3(0.5f,0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,1,1); i++; vertices[i] = new Vector3(0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(1,0,1); i++; triangles[ti++] = i-4; triangles[ti++] = i-3; triangles[ti++] = i-2; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-1; //Left vertices[i] = new Vector3(-0.5f,-0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,0,0); i++; vertices[i] = new Vector3(-0.5f,0.5f,-0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,1,0); i++; vertices[i] = new Vector3(-0.5f,0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,1,1); i++; vertices[i] = new Vector3(-0.5f,-0.5f,0.5f); normals[i] = new Vector3(0,1,0); colors[i] = new Color(0,0,1); i++; triangles[ti++] = i-4; triangles[ti++] = i-2; triangles[ti++] = i-3; triangles[ti++] = i-4; triangles[ti++] = i-1; triangles[ti++] = i-2; m.vertices = vertices; m.colors = colors; //Putting uv's into the normal channel to get the //Vector3 type m.uv = uv; m.normals = normals; m.triangles = triangles; } public void Generate2DTexture() { texture2D = new Texture2D(n,n,TextureFormat.ARGB32,true); int size = n*n; Color[] cols = new Color[size]; float u,v; int idx = 0; Color c = Color.white; for(int i = 0; i < n; i++) { u = i/(float)n; for(int j = 0; j < n; j++, ++idx) { v = j/(float)n; float noise = Mathf.PerlinNoise(u,v); c.r = c.g = c.b = noise; cols[idx] = c; } } texture2D.SetPixels(cols); texture2D.Apply(); Renderer renderer = GetComponent<Renderer>().GetComponent<Renderer>(); renderer.material.SetTexture("g_tex", texture2D); //Color[] cs = texture3D.GetPixels(); //for(int i = 0; i < 10; i++) // Debug.Log (cs[i]); } public void Generate3DTexture() { float r = 0.3f; texture3D = new Texture3D(n,n,n,TextureFormat.ARGB32,true); int size = n * n * n; Color[] cols = new Color[size]; int idx = 0; Color c = Color.white; float frequency = 0.01f / n; float center = n / 2.0f + 0.5f; for(int i = 0; i < n; i++) { for(int j = 0; j < n; j++) { for(int k = 0; k < n; k++, ++idx) { float dx = center-i; float dy = center-j; float dz = center-k; float off = Mathf.Abs(Perlin.Turbulence(i*frequency, j*frequency, k*frequency, 6)); float d = Mathf.Sqrt(dx*dx+dy*dy+dz*dz)/(n); //c.r = c.g = c.b = c.a = ((d-off) < r)?1.0f:0.0f; float p = d-off; c.r = c.g = c.b = c.a = Mathf.Clamp01(r - p); cols[idx] = c; } } } //for(int i = 0; i < size; i++) // Debug.Log (newC[i]); texture3D.SetPixels(cols); texture3D.Apply(); Renderer renderer = GetComponent<Renderer>().GetComponent<Renderer>(); renderer.material.SetTexture("g_densityTex", texture3D); texture3D.filterMode = FilterMode.Trilinear; texture3D.wrapMode = TextureWrapMode.Clamp; texture3D.anisoLevel = 1; //Color[] cs = texture3D.GetPixels(); //for(int i = 0; i < 10; i++) // Debug.Log (cs[i]); } private void save3DTexture() { string path = "Assets/Textures3D/" + texture3DName + ".asset"; Texture3D tmp = (Texture3D)AssetDatabase.LoadAssetAtPath(path, typeof(Texture3D)); if (tmp) { AssetDatabase.DeleteAsset(path); tmp = null; } AssetDatabase.CreateAsset(texture3D, path); AssetDatabase.SaveAssets(); } }
// File generated from our OpenAPI spec namespace Stripe { using System; using System.Collections.Generic; using Newtonsoft.Json; using Stripe.Infrastructure; /// <summary> /// A <c>Payout</c> object is created when you receive funds from Stripe, or when you /// initiate a payout to either a bank account or debit card of a <a /// href="https://stripe.com/docs/connect/bank-debit-card-payouts">connected Stripe /// account</a>. You can retrieve individual payouts, as well as list all payouts. Payouts /// are made on <a href="https://stripe.com/docs/connect/manage-payout-schedule">varying /// schedules</a>, depending on your country and industry. /// /// Related guide: <a href="https://stripe.com/docs/payouts">Receiving Payouts</a>. /// </summary> public class Payout : StripeEntity<Payout>, IHasId, IHasMetadata, IHasObject, IBalanceTransactionSource { /// <summary> /// Unique identifier for the object. /// </summary> [JsonProperty("id")] public string Id { get; set; } /// <summary> /// String representing the object's type. Objects of the same type share the same value. /// </summary> [JsonProperty("object")] public string Object { get; set; } /// <summary> /// Amount (in %s) to be transferred to your bank account or debit card. /// </summary> [JsonProperty("amount")] public long Amount { get; set; } /// <summary> /// Date the payout is expected to arrive in the bank. This factors in delays like weekends /// or bank holidays. /// </summary> [JsonProperty("arrival_date")] [JsonConverter(typeof(UnixDateTimeConverter))] public DateTime ArrivalDate { get; set; } = Stripe.Infrastructure.DateTimeUtils.UnixEpoch; /// <summary> /// Returns <c>true</c> if the payout was created by an <a /// href="https://stripe.com/docs/payouts#payout-schedule">automated payout schedule</a>, /// and <c>false</c> if it was <a /// href="https://stripe.com/docs/payouts#manual-payouts">requested manually</a>. /// </summary> [JsonProperty("automatic")] public bool Automatic { get; set; } #region Expandable BalanceTransaction /// <summary> /// (ID of the BalanceTransaction) /// ID of the balance transaction that describes the impact of this payout on your account /// balance. /// </summary> [JsonIgnore] public string BalanceTransactionId { get => this.InternalBalanceTransaction?.Id; set => this.InternalBalanceTransaction = SetExpandableFieldId(value, this.InternalBalanceTransaction); } /// <summary> /// (Expanded) /// ID of the balance transaction that describes the impact of this payout on your account /// balance. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public BalanceTransaction BalanceTransaction { get => this.InternalBalanceTransaction?.ExpandedObject; set => this.InternalBalanceTransaction = SetExpandableFieldObject(value, this.InternalBalanceTransaction); } [JsonProperty("balance_transaction")] [JsonConverter(typeof(ExpandableFieldConverter<BalanceTransaction>))] internal ExpandableField<BalanceTransaction> InternalBalanceTransaction { get; set; } #endregion /// <summary> /// Time at which the object was created. Measured in seconds since the Unix epoch. /// </summary> [JsonProperty("created")] [JsonConverter(typeof(UnixDateTimeConverter))] public DateTime Created { get; set; } = Stripe.Infrastructure.DateTimeUtils.UnixEpoch; /// <summary> /// Three-letter <a href="https://www.iso.org/iso-4217-currency-codes.html">ISO currency /// code</a>, in lowercase. Must be a <a href="https://stripe.com/docs/currencies">supported /// currency</a>. /// </summary> [JsonProperty("currency")] public string Currency { get; set; } /// <summary> /// An arbitrary string attached to the object. Often useful for displaying to users. /// </summary> [JsonProperty("description")] public string Description { get; set; } #region Expandable Destination /// <summary> /// (ID of the IExternalAccount) /// ID of the bank account or card the payout was sent to. /// </summary> [JsonIgnore] public string DestinationId { get => this.InternalDestination?.Id; set => this.InternalDestination = SetExpandableFieldId(value, this.InternalDestination); } /// <summary> /// (Expanded) /// ID of the bank account or card the payout was sent to. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public IExternalAccount Destination { get => this.InternalDestination?.ExpandedObject; set => this.InternalDestination = SetExpandableFieldObject(value, this.InternalDestination); } [JsonProperty("destination")] [JsonConverter(typeof(ExpandableFieldConverter<IExternalAccount>))] internal ExpandableField<IExternalAccount> InternalDestination { get; set; } #endregion #region Expandable FailureBalanceTransaction /// <summary> /// (ID of the BalanceTransaction) /// If the payout failed or was canceled, this will be the ID of the balance transaction /// that reversed the initial balance transaction, and puts the funds from the failed payout /// back in your balance. /// </summary> [JsonIgnore] public string FailureBalanceTransactionId { get => this.InternalFailureBalanceTransaction?.Id; set => this.InternalFailureBalanceTransaction = SetExpandableFieldId(value, this.InternalFailureBalanceTransaction); } /// <summary> /// (Expanded) /// If the payout failed or was canceled, this will be the ID of the balance transaction /// that reversed the initial balance transaction, and puts the funds from the failed payout /// back in your balance. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public BalanceTransaction FailureBalanceTransaction { get => this.InternalFailureBalanceTransaction?.ExpandedObject; set => this.InternalFailureBalanceTransaction = SetExpandableFieldObject(value, this.InternalFailureBalanceTransaction); } [JsonProperty("failure_balance_transaction")] [JsonConverter(typeof(ExpandableFieldConverter<BalanceTransaction>))] internal ExpandableField<BalanceTransaction> InternalFailureBalanceTransaction { get; set; } #endregion /// <summary> /// Error code explaining reason for payout failure if available. See <a /// href="https://stripe.com/docs/api#payout_failures">Types of payout failures</a> for a /// list of failure codes. /// </summary> [JsonProperty("failure_code")] public string FailureCode { get; set; } /// <summary> /// Message to user further explaining reason for payout failure if available. /// </summary> [JsonProperty("failure_message")] public string FailureMessage { get; set; } /// <summary> /// Has the value <c>true</c> if the object exists in live mode or the value <c>false</c> if /// the object exists in test mode. /// </summary> [JsonProperty("livemode")] public bool Livemode { get; set; } /// <summary> /// Set of <a href="https://stripe.com/docs/api/metadata">key-value pairs</a> that you can /// attach to an object. This can be useful for storing additional information about the /// object in a structured format. /// </summary> [JsonProperty("metadata")] public Dictionary<string, string> Metadata { get; set; } /// <summary> /// The method used to send this payout, which can be <c>standard</c> or <c>instant</c>. /// <c>instant</c> is only supported for payouts to debit cards. (See <a /// href="https://stripe.com/blog/instant-payouts-for-marketplaces">Instant payouts for /// marketplaces</a> for more information.). /// </summary> [JsonProperty("method")] public string Method { get; set; } #region Expandable OriginalPayout /// <summary> /// (ID of the Payout) /// If the payout reverses another, this is the ID of the original payout. /// </summary> [JsonIgnore] public string OriginalPayoutId { get => this.InternalOriginalPayout?.Id; set => this.InternalOriginalPayout = SetExpandableFieldId(value, this.InternalOriginalPayout); } /// <summary> /// (Expanded) /// If the payout reverses another, this is the ID of the original payout. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public Payout OriginalPayout { get => this.InternalOriginalPayout?.ExpandedObject; set => this.InternalOriginalPayout = SetExpandableFieldObject(value, this.InternalOriginalPayout); } [JsonProperty("original_payout")] [JsonConverter(typeof(ExpandableFieldConverter<Payout>))] internal ExpandableField<Payout> InternalOriginalPayout { get; set; } #endregion #region Expandable ReversedBy /// <summary> /// (ID of the Payout) /// If the payout was reversed, this is the ID of the payout that reverses this payout. /// </summary> [JsonIgnore] public string ReversedById { get => this.InternalReversedBy?.Id; set => this.InternalReversedBy = SetExpandableFieldId(value, this.InternalReversedBy); } /// <summary> /// (Expanded) /// If the payout was reversed, this is the ID of the payout that reverses this payout. /// /// For more information, see the <a href="https://stripe.com/docs/expand">expand documentation</a>. /// </summary> [JsonIgnore] public Payout ReversedBy { get => this.InternalReversedBy?.ExpandedObject; set => this.InternalReversedBy = SetExpandableFieldObject(value, this.InternalReversedBy); } [JsonProperty("reversed_by")] [JsonConverter(typeof(ExpandableFieldConverter<Payout>))] internal ExpandableField<Payout> InternalReversedBy { get; set; } #endregion /// <summary> /// The source balance this payout came from. One of <c>card</c>, <c>fpx</c>, or /// <c>bank_account</c>. /// </summary> [JsonProperty("source_type")] public string SourceType { get; set; } /// <summary> /// Extra information about a payout to be displayed on the user's bank statement. /// </summary> [JsonProperty("statement_descriptor")] public string StatementDescriptor { get; set; } /// <summary> /// Current status of the payout: <c>paid</c>, <c>pending</c>, <c>in_transit</c>, /// <c>canceled</c> or <c>failed</c>. A payout is <c>pending</c> until it is submitted to /// the bank, when it becomes <c>in_transit</c>. The status then changes to <c>paid</c> if /// the transaction goes through, or to <c>failed</c> or <c>canceled</c> (within 5 business /// days). Some failed payouts may initially show as <c>paid</c> but then change to /// <c>failed</c>. /// </summary> [JsonProperty("status")] public string Status { get; set; } /// <summary> /// Can be <c>bank_account</c> or <c>card</c>. /// One of: <c>bank_account</c>, or <c>card</c>. /// </summary> [JsonProperty("type")] public string Type { get; set; } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABILITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Threading; using System.Threading.Tasks; using System.Windows.Automation; using Microsoft.PythonTools; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.TestTools.UnitTesting; using Microsoft.VisualStudioTools; using TestUtilities; using TestUtilities.UI; using TestUtilities.UI.Python; namespace PythonToolsUITests { public class BuildTasksUITests { internal void Execute(PythonProjectNode projectNode, string commandName) { Console.WriteLine("Executing command {0}", commandName); var t = projectNode.Site.GetUIThread().InvokeTask(() => projectNode._customCommands.First(cc => cc.DisplayLabel == commandName).ExecuteAsync(projectNode)); t.GetAwaiter().GetResult(); } internal Task ExecuteAsync(PythonProjectNode projectNode, string commandName) { Console.WriteLine("Executing command {0} asynchronously", commandName); return projectNode.Site.GetUIThread().InvokeTask(() => projectNode._customCommands.First(cc => cc.DisplayLabel == commandName).ExecuteAsync(projectNode)); } internal void OpenProject(VisualStudioApp app, string slnName, PythonVersion python, out PythonProjectNode projectNode, out EnvDTE.Project dteProject) { dteProject = app.OpenProject(app.CopyProjectForTest("TestData\\Targets\\" + slnName)); var pn = projectNode = dteProject.GetPythonProject(); var fact = projectNode.InterpreterFactories.Where(x => x.Configuration.Id == python.Id).FirstOrDefault(); Assert.IsNotNull(fact, "Project does not contain expected interpreter"); app.ServiceProvider.GetUIThread().Invoke(() => pn.ActiveInterpreter = fact); dteProject.Save(); } public void CustomCommandsAdded(VisualStudioApp app, PythonVersion python) { PythonProjectNode node; EnvDTE.Project proj; OpenProject(app, "Commands1.sln", python, out node, out proj); AssertUtil.ContainsExactly( node._customCommands.Select(cc => cc.DisplayLabel), "Test Command 1", "Test Command 2" ); app.OpenSolutionExplorer().FindItem("Solution 'Commands1' (1 project)", "Commands1").Select(); var menuBar = app.FindByAutomationId("MenuBar").AsWrapper(); Assert.IsNotNull(menuBar, "Unable to find menu bar"); var projectMenu = menuBar.FindByName("Project").AsWrapper(); Assert.IsNotNull(projectMenu, "Unable to find Project menu"); projectMenu.Element.EnsureExpanded(); try { foreach (var name in node._customCommands.Select(cc => cc.DisplayLabelWithoutAccessKeys)) { Assert.IsNotNull(projectMenu.FindByName(name), name + " not found"); } } finally { try { // Try really really hard to collapse and deselect the // Project menu, since VS will keep it selected and it // may not come back for some reason... projectMenu.Element.Collapse(); Keyboard.PressAndRelease(System.Windows.Input.Key.Escape); Keyboard.PressAndRelease(System.Windows.Input.Key.Escape); } catch { // ...but don't try so hard that we fail if we can't // simulate keypresses. } } } public void CustomCommandsWithResourceLabel(VisualStudioApp app, PythonVersion python) { PythonProjectNode node; EnvDTE.Project proj; OpenProject(app, "Commands2.sln", python, out node, out proj); AssertUtil.ContainsExactly( node._customCommands.Select(cc => cc.Label), "resource:PythonToolsUITests;PythonToolsUITests.Resources;CommandName" ); AssertUtil.ContainsExactly( node._customCommands.Select(cc => cc.DisplayLabel), "Command from Resource" ); } public void CustomCommandsReplWithResourceLabel(PythonVisualStudioApp app, PythonVersion python) { PythonProjectNode node; EnvDTE.Project proj; OpenProject(app, "Commands2.sln", python, out node, out proj); Execute(node, "Command from Resource"); using (var repl = app.GetInteractiveWindow("Repl from Resource")) { Assert.IsNotNull(repl, "Could not find repl window"); repl.WaitForTextEnd( "Program.py completed", ">" ); } using (var repl = app.GetInteractiveWindow("resource:PythonToolsUITests;PythonToolsUITests.Resources;ReplName")) { Assert.IsNull(repl); } } public void CustomCommandsRunInRepl(PythonVisualStudioApp app, PythonVersion python) { PythonProjectNode node; EnvDTE.Project proj; OpenProject(app, "Commands1.sln", python, out node, out proj); Execute(node, "Test Command 2"); using (var repl = app.GetInteractiveWindow("Test Repl")) { Assert.IsNotNull(repl, "Could not find repl window"); repl.WaitForTextEnd( "Program.py completed", ">" ); } app.Dte.Solution.Close(); using (var repl = app.GetInteractiveWindow("Test Repl")) { Assert.IsNull(repl, "Repl window was not closed"); } } public void CustomCommandsRunProcessInRepl(PythonVisualStudioApp app, PythonVersion python) { PythonProjectNode node; EnvDTE.Project proj; OpenProject(app, "Commands3.sln", python, out node, out proj); Execute(node, "Write to Repl"); using (var repl = app.GetInteractiveWindow("Test Repl")) { Assert.IsNotNull(repl, "Could not find repl window"); repl.WaitForTextEnd( string.Format("({0}, {1})", python.Configuration.Version.Major, python.Configuration.Version.Minor), ">" ); } } private static void ExpectOutputWindowText(VisualStudioApp app, string expected) { var outputWindow = app.Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"), new PropertyCondition(AutomationElement.NameProperty, "Output") ) ); Assert.IsNotNull(outputWindow, "Output Window was not opened"); var outputText = ""; for (int retries = 100; !outputText.Contains(expected) && retries > 0; --retries) { Thread.Sleep(100); outputText = outputWindow.FindFirst(TreeScope.Descendants, new PropertyCondition(AutomationElement.ClassNameProperty, "WpfTextView") ).AsWrapper().GetValue(); } Console.WriteLine("Output Window: " + outputText); Assert.IsTrue(outputText.Contains(expected), string.Format("Expected to see:\r\n\r\n{0}\r\n\r\nActual content:\r\n\r\n{1}", expected, outputText)); } public void CustomCommandsRunProcessInOutput(PythonVisualStudioApp app, PythonVersion python) { PythonProjectNode node; EnvDTE.Project proj; OpenProject(app, "Commands3.sln", python, out node, out proj); Execute(node, "Write to Output"); var outputWindow = app.Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"), new PropertyCondition(AutomationElement.NameProperty, "Output") ) ); Assert.IsNotNull(outputWindow, "Output Window was not opened"); ExpectOutputWindowText(app, string.Format("({0}, {1})", python.Configuration.Version.Major, python.Configuration.Version.Minor)); } public void CustomCommandsRunProcessInConsole(PythonVisualStudioApp app, PythonVersion python) { PythonProjectNode node; EnvDTE.Project proj; OpenProject(app, "Commands3.sln", python, out node, out proj); var existingProcesses = new HashSet<int>(Process.GetProcessesByName("cmd").Select(p => p.Id)); Execute(node, "Write to Console"); Process newProcess = null; for (int retries = 100; retries > 0 && newProcess == null; --retries) { Thread.Sleep(100); newProcess = Process.GetProcessesByName("cmd").Where(p => !existingProcesses.Contains(p.Id)).FirstOrDefault(); } Assert.IsNotNull(newProcess, "Process did not start"); try { newProcess.CloseMainWindow(); newProcess.WaitForExit(1000); if (newProcess.HasExited) { newProcess = null; } } finally { if (newProcess != null) { newProcess.Kill(); } } } public void CustomCommandsErrorList(PythonVisualStudioApp app, PythonVersion python) { PythonProjectNode node; EnvDTE.Project proj; OpenProject(app, "ErrorCommand.sln", python, out node, out proj); var expectedItems = new[] { new { Document = "Program.py", Line = 0, Column = 1, Category = __VSERRORCATEGORY.EC_ERROR, Message = "This is an error with a relative path." }, new { Document = Path.Combine(node.ProjectHome, "Program.py"), Line = 2, Column = 3, Category = __VSERRORCATEGORY.EC_WARNING, Message = "This is a warning with an absolute path." }, new { Document = ">>>", Line = 4, Column = -1, Category = __VSERRORCATEGORY.EC_ERROR, Message = "This is an error with an invalid path." }, }; Execute(node, "Produce Errors"); var items = app.WaitForErrorListItems(3); Console.WriteLine("Got errors:"); foreach (var item in items) { string document, text; Assert.AreEqual(0, item.Document(out document), "HRESULT getting document"); Assert.AreEqual(0, item.get_Text(out text), "HRESULT getting message"); Console.WriteLine(" {0}: {1}", document ?? "(null)", text ?? "(null)"); } Assert.AreEqual(expectedItems.Length, items.Count); // Second invoke should replace the error items in the list, not add new ones to those already existing. Execute(node, "Produce Errors"); items = app.WaitForErrorListItems(3); Assert.AreEqual(expectedItems.Length, items.Count); items.Sort(Comparer<IVsTaskItem>.Create((x, y) => { int lx, ly; x.Line(out lx); y.Line(out ly); return lx.CompareTo(ly); })); for (int i = 0; i < expectedItems.Length; ++i) { var item = items[i]; var expectedItem = expectedItems[i]; string document, message; item.get_Text(out message); item.Document(out document); int line, column; item.Line(out line); item.Column(out column); uint category; ((IVsErrorItem)item).GetCategory(out category); Assert.AreEqual(expectedItem.Document, document); Assert.AreEqual(expectedItem.Line, line); Assert.AreEqual(expectedItem.Column, column); Assert.AreEqual(expectedItem.Message, message); Assert.AreEqual(expectedItem.Category, (__VSERRORCATEGORY)category); } app.ServiceProvider.GetUIThread().Invoke((Action)delegate { items[0].NavigateTo(); }); var doc = app.Dte.ActiveDocument; Assert.IsNotNull(doc); Assert.AreEqual("Program.py", doc.Name); var textDoc = (EnvDTE.TextDocument)doc.Object("TextDocument"); Assert.AreEqual(1, textDoc.Selection.ActivePoint.Line); Assert.AreEqual(2, textDoc.Selection.ActivePoint.DisplayColumn); } public void CustomCommandsRequiredPackages(PythonVisualStudioApp app, PythonVersion python) { using (var dis = app.SelectDefaultInterpreter(python, "virtualenv")) { PythonProjectNode node; EnvDTE.Project proj; OpenProject(app, "CommandRequirePackages.sln", python, out node, out proj); string envName; var env = app.CreateProjectVirtualEnvironment(proj, out envName); env.Select(); app.Dte.ExecuteCommand("Python.ActivateEnvironment"); // Ensure that no error dialog appears app.WaitForNoDialog(TimeSpan.FromSeconds(5.0)); // First, execute the command and cancel it. var task = ExecuteAsync(node, "Require Packages"); try { var dialogHandle = app.WaitForDialog(task); if (dialogHandle == IntPtr.Zero) { if (task.IsFaulted && task.Exception != null) { Assert.Fail("Unexpected exception in package install confirmation dialog:\n{0}", task.Exception); } else { Assert.AreNotEqual(IntPtr.Zero, dialogHandle); } } using (var dialog = new AutomationDialog(app, AutomationElement.FromHandle(dialogHandle))) { var label = dialog.FindByAutomationId("CommandLink_1000"); Assert.IsNotNull(label); string expectedLabel = "The following packages will be installed using pip:\r\n" + "\r\n" + "ptvsd\r\n" + "azure==0.1"; ; Assert.AreEqual(expectedLabel, label.Current.HelpText); dialog.Cancel(); try { task.Wait(1000); Assert.Fail("Command was not canceled after dismissing the package install confirmation dialog"); } catch (AggregateException ex) { if (!(ex.InnerException is TaskCanceledException)) { throw; } } } } finally { if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted) { if (task.Wait(10000)) { task.Dispose(); } } else { task.Dispose(); } } // Then, execute command and allow it to proceed. task = ExecuteAsync(node, "Require Packages"); try { var dialogHandle = app.WaitForDialog(task); if (dialogHandle == IntPtr.Zero) { if (task.IsFaulted && task.Exception != null) { Assert.Fail("Unexpected exception in package install confirmation dialog:\n{0}", task.Exception); } else { Assert.AreNotEqual(IntPtr.Zero, dialogHandle); } } using (var dialog = new AutomationDialog(app, AutomationElement.FromHandle(dialogHandle))) { dialog.ClickButtonAndClose("CommandLink_1000", nameIsAutomationId: true); } task.Wait(); var ver = python.Version.ToVersion(); ExpectOutputWindowText(app, string.Format("pass {0}.{1}", ver.Major, ver.Minor)); } finally { if (!task.IsCanceled && !task.IsCompleted && !task.IsFaulted) { if (task.Wait(10000)) { task.Dispose(); } } else { task.Dispose(); } } } } public void CustomCommandsSearchPath(PythonVisualStudioApp app, PythonVersion python) { var expectedSearchPath = string.Format("['{0}', '{1}', '{2}']", // Includes CWD (ProjectHome) first TestData.GetPath(@"TestData\Targets\Package\Subpackage").Replace("\\", "\\\\"), // Specified as '..\..' from ProjectHome TestData.GetPath(@"TestData\Targets").Replace("\\", "\\\\"), // Specified as '..' from ProjectHome TestData.GetPath(@"TestData\Targets\Package").Replace("\\", "\\\\") ); PythonProjectNode node; EnvDTE.Project proj; OpenProject(app, "CommandSearchPath.sln", python, out node, out proj); Execute(node, "Import From Search Path"); var outputWindow = app.Element.FindFirst(TreeScope.Descendants, new AndCondition( new PropertyCondition(AutomationElement.ClassNameProperty, "GenericPane"), new PropertyCondition(AutomationElement.NameProperty, "Output") ) ); Assert.IsNotNull(outputWindow, "Output Window was not opened"); ExpectOutputWindowText(app, expectedSearchPath); } } }
// 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 Internal.TypeSystem; using Debug = System.Diagnostics.Debug; namespace Internal.Runtime { /// <summary> /// Utility class for encoding GCDescs. GCDesc is a runtime structure used by the /// garbage collector that describes the GC layout of a memory region. /// </summary> public struct GCDescEncoder { /// <summary> /// Retrieves size of the GCDesc that describes the instance GC layout for the given type. /// </summary> public static int GetGCDescSize(TypeDesc type) { if (type.IsArray) { TypeDesc elementType = ((ArrayType)type).ElementType; if (elementType.IsGCPointer) { // For efficiency this is special cased and encoded as one serie. return 3 * type.Context.Target.PointerSize; } else if (elementType.IsDefType) { var defType = (DefType)elementType; if (defType.ContainsGCPointers) { GCPointerMap pointerMap = GCPointerMap.FromInstanceLayout(defType); if (pointerMap.IsAllGCPointers) { // For efficiency this is special cased and encoded as one serie. return 3 * type.Context.Target.PointerSize; } else { int numSeries = pointerMap.NumSeries; Debug.Assert(numSeries > 0); return (numSeries + 2) * type.Context.Target.PointerSize; } } } } else { var defType = (DefType)type; if (defType.ContainsGCPointers) { int numSeries = GCPointerMap.FromInstanceLayout(defType).NumSeries; Debug.Assert(numSeries > 0); return (numSeries * 2 + 1) * type.Context.Target.PointerSize; } } return 0; } public static void EncodeGCDesc<T>(ref T builder, TypeDesc type) where T : struct, ITargetBinaryWriter { int initialBuilderPosition = builder.CountBytes; if (type.IsArray) { TypeDesc elementType = ((ArrayType)type).ElementType; // 2 means m_pEEType and _numComponents. Syncblock is sort of appended at the end of the object layout in this case. int baseSize = 2 * builder.TargetPointerSize; if (type.IsMdArray) { // Multi-dim arrays include upper and lower bounds for each rank baseSize += 2 * type.Context.GetWellKnownType(WellKnownType.Int32).GetElementSize() * ((ArrayType)type).Rank; } if (elementType.IsGCPointer) { EncodeAllGCPointersArrayGCDesc(ref builder, baseSize); } else if (elementType.IsDefType) { var elementDefType = (DefType)elementType; if (elementDefType.ContainsGCPointers) { GCPointerMap pointerMap = GCPointerMap.FromInstanceLayout(elementDefType); if (pointerMap.IsAllGCPointers) { EncodeAllGCPointersArrayGCDesc(ref builder, baseSize); } else { EncodeArrayGCDesc(ref builder, pointerMap, baseSize); } } } } else { var defType = (DefType)type; if (defType.ContainsGCPointers) { // Computing the layout for the boxed version if this is a value type. int offs = defType.IsValueType ? builder.TargetPointerSize : 0; // Include syncblock int objectSize = defType.InstanceByteCount + offs + builder.TargetPointerSize; EncodeStandardGCDesc(ref builder, GCPointerMap.FromInstanceLayout(defType), objectSize, offs); } } Debug.Assert(initialBuilderPosition + GetGCDescSize(type) == builder.CountBytes); } public static void EncodeStandardGCDesc<T>(ref T builder, GCPointerMap map, int size, int delta) where T : struct, ITargetBinaryWriter { Debug.Assert(size >= map.Size); int pointerSize = builder.TargetPointerSize; int numSeries = 0; for (int cellIndex = map.Size - 1; cellIndex >= 0; cellIndex--) { if (map[cellIndex]) { numSeries++; int seriesSize = pointerSize; while (cellIndex > 0 && map[cellIndex - 1]) { seriesSize += pointerSize; cellIndex--; } builder.EmitNaturalInt(seriesSize - size); builder.EmitNaturalInt(cellIndex * pointerSize + delta); } } Debug.Assert(numSeries > 0); builder.EmitNaturalInt(numSeries); } // Arrays of all GC references are encoded as special kind of GC desc for efficiency private static void EncodeAllGCPointersArrayGCDesc<T>(ref T builder, int baseSize) where T : struct, ITargetBinaryWriter { builder.EmitNaturalInt(-3 * builder.TargetPointerSize); builder.EmitNaturalInt(baseSize); // NumSeries builder.EmitNaturalInt(1); } private static void EncodeArrayGCDesc<T>(ref T builder, GCPointerMap map, int baseSize) where T : struct, ITargetBinaryWriter { // NOTE: This format cannot properly represent element types with sizes >= 64k bytes. // We guard it with an assert, but it is the responsibility of the code using this // to cap array component sizes. EEType only has a UInt16 field for component sizes too. int numSeries = 0; int leadingNonPointerCount = 0; int pointerSize = builder.TargetPointerSize; for (int cellIndex = 0; cellIndex < map.Size && !map[cellIndex]; cellIndex++) { leadingNonPointerCount++; } int nonPointerCount = leadingNonPointerCount; for (int cellIndex = map.Size - 1; cellIndex >= leadingNonPointerCount; cellIndex--) { if (map[cellIndex]) { numSeries++; int pointerCount = 1; while (cellIndex > leadingNonPointerCount && map[cellIndex - 1]) { cellIndex--; pointerCount++; } Debug.Assert(pointerCount < 64 * 1024); builder.EmitHalfNaturalInt((short)pointerCount); Debug.Assert(nonPointerCount * pointerSize < 64 * 1024); builder.EmitHalfNaturalInt((short)(nonPointerCount * pointerSize)); nonPointerCount = 0; } else { nonPointerCount++; } } Debug.Assert(numSeries > 0); builder.EmitNaturalInt(baseSize + leadingNonPointerCount * pointerSize); builder.EmitNaturalInt(-numSeries); } } }
using System; using System.Threading.Tasks; namespace Eto.Forms { /// <summary> /// Hint to tell the platform how to display the dialog /// </summary> /// <remarks> /// This tells the platform how you prefer to display the dialog. Each platform /// may support only certain modes and will choose the appropriate mode based on the hint /// given. /// </remarks> [Flags] public enum DialogDisplayMode { /// <summary> /// The default display mode for modal dialogs in the platform /// </summary> /// <remarks> /// This uses the ideal display mode given the state of the application and the owner window that is passed in /// </remarks> Default = 0, /// <summary> /// Display the dialog attached to the owner window, if supported (e.g. OS X) /// </summary> Attached = 0x01, /// <summary> /// Display the dialog as a separate window (e.g. Windows/Linux only supports this mode) /// </summary> Separate = 0x02, /// <summary> /// Display in navigation if available /// </summary> Navigation = 0x04 } /// <summary> /// Custom modal dialog with a specified result type /// </summary> /// <remarks> /// This provides a way to show a modal dialog with custom contents to the user. /// A dialog will block user input from the owner form until the dialog is closed. /// </remarks> /// <seealso cref="Dialog"/> /// <typeparam name="T">Type result type of the dialog</typeparam> public class Dialog<T> : Dialog { /// <summary> /// Gets or sets the result of the dialog /// </summary> /// <value>The result.</value> public T Result { get; set; } /// <summary> /// Shows the dialog and blocks until the user closes the dialog /// </summary> /// <returns>The result of the modal dialog</returns> public new T ShowModal() { base.ShowModal(); return Result; } /// <summary> /// Shows the dialog modally asynchronously /// </summary> /// <returns>The result of the modal dialog</returns> public new Task<T> ShowModalAsync() { return base.ShowModalAsync() .ContinueWith(t => Result, TaskContinuationOptions.OnlyOnRanToCompletion); } /// <summary> /// Shows the dialog and blocks until the user closes the dialog /// </summary> /// <remarks> /// The <paramref name="owner"/> specifies the control on the window that will be blocked from user input until /// the dialog is closed. /// </remarks> /// <returns>The result of the modal dialog</returns> /// <param name="owner">The owner control that is showing the form</param> public new T ShowModal(Control owner) { base.ShowModal(owner); return Result; } /// <summary> /// Shows the dialog modally asynchronously /// </summary> /// <remarks> /// The <paramref name="owner"/> specifies the control on the window that will be blocked from user input until /// the dialog is closed. /// </remarks> /// <param name="owner">The owner control that is showing the form</param> public new Task<T> ShowModalAsync(Control owner) { return base.ShowModalAsync(owner) .ContinueWith(t => Result, TaskContinuationOptions.OnlyOnRanToCompletion); } /// <summary> /// Close the dialog with the specified result /// </summary> /// <param name="result">Result to return to the caller</param> public void Close(T result) { Result = result; Close(); } } /// <summary> /// Custom modal dialog /// </summary> /// <remarks> /// This provides a way to show a modal dialog with custom contents to the user. /// A dialog will block user input from the owner form until the dialog is closed. /// </remarks> /// <seealso cref="Form"/> /// <seealso cref="Dialog{T}"/> [Handler(typeof(Dialog.IHandler))] public class Dialog : Window { new IHandler Handler { get { return (IHandler)base.Handler; } } /// <summary> /// Gets or sets the display mode hint /// </summary> /// <value>The display mode.</value> public DialogDisplayMode DisplayMode { get { return Handler.DisplayMode; } set { Handler.DisplayMode = value; } } /// <summary> /// Gets or sets the abort button. /// </summary> /// <remarks> /// On some platforms, the abort button would be called automatically if the user presses the escape key /// </remarks> /// <value>The abort button.</value> public Button AbortButton { get { return Handler.AbortButton; } set { Handler.AbortButton = value; } } /// <summary> /// Gets or sets the default button. /// </summary> /// <remarks> /// On some platforms, the abort button would be called automatically if the user presses the return key /// on the form /// </remarks> /// <value>The default button.</value> public Button DefaultButton { get { return Handler.DefaultButton; } set { Handler.DefaultButton = value; } } /// <summary> /// Shows the dialog modally, blocking the current thread until it is closed. /// </summary> /// <remarks> /// The <paramref name="owner"/> specifies the control on the window that will be blocked from user input until /// the dialog is closed. /// Calling this method is identical to setting the <see cref="Window.Owner"/> property and calling <see cref="ShowModal()"/>. /// </remarks> /// <param name="owner">The owner control that is showing the form</param> public void ShowModal(Control owner) { Owner = owner != null ? owner.ParentWindow : null; ShowModal(); } /// <summary> /// Shows the dialog modally, blocking the current thread until it is closed. /// </summary> public void ShowModal() { bool loaded = Loaded; if (!loaded) { OnPreLoad(EventArgs.Empty); OnLoad(EventArgs.Empty); OnDataContextChanged(EventArgs.Empty); OnLoadComplete(EventArgs.Empty); } Application.Instance.AddWindow(this); Handler.ShowModal(); } /// <summary> /// Shows the dialog modally asynchronously /// </summary> /// <remarks> /// The <paramref name="owner"/> specifies the control on the window that will be blocked from user input until /// the dialog is closed. /// Calling this method is identical to setting the <see cref="Window.Owner"/> property and calling <see cref="ShowModalAsync()"/>. /// </remarks> /// <param name="owner">The owner control that is showing the form</param> public Task ShowModalAsync(Control owner) { Owner = owner != null ? owner.ParentWindow : null; return ShowModalAsync(); } /// <summary> /// Shows the dialog modally asynchronously /// </summary> public Task ShowModalAsync() { bool loaded = Loaded; if (!loaded) { OnPreLoad(EventArgs.Empty); OnLoad(EventArgs.Empty); OnDataContextChanged(EventArgs.Empty); OnLoadComplete(EventArgs.Empty); } Application.Instance.AddWindow(this); return Handler.ShowModalAsync(); } /// <summary> /// Handler interface for the <see cref="Dialog"/> class /// </summary> public new interface IHandler : Window.IHandler { /// <summary> /// Gets or sets the display mode hint /// </summary> /// <value>The display mode.</value> DialogDisplayMode DisplayMode { get; set; } /// <summary> /// Shows the dialog modally, blocking the current thread until it is closed. /// </summary> void ShowModal(); /// <summary> /// Shows the dialog modally asynchronously /// </summary> Task ShowModalAsync(); /// <summary> /// Gets or sets the default button. /// </summary> /// <remarks> /// On some platforms, the abort button would be called automatically if the user presses the return key /// on the form /// </remarks> /// <value>The default button.</value> Button DefaultButton { get; set; } /// <summary> /// Gets or sets the abort button. /// </summary> /// <remarks> /// On some platforms, the abort button would be called automatically if the user presses the escape key /// </remarks> /// <value>The abort button.</value> Button AbortButton { get; set; } } } }
/* * Exchange Web Services Managed API * * 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. */ namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using MapiTypeConverterMap = System.Collections.Generic.Dictionary<MapiPropertyType, MapiTypeConverterMapEntry>; /// <summary> /// Utility class to convert between MAPI Property type values and strings. /// </summary> internal class MapiTypeConverter { /// <summary> /// Assume DateTime values are in UTC. /// </summary> private const DateTimeStyles UtcDataTimeStyles = DateTimeStyles.AdjustToUniversal | DateTimeStyles.AssumeUniversal; /// <summary> /// Map from MAPI property type to converter entry. /// </summary> private static LazyMember<MapiTypeConverterMap> mapiTypeConverterMap = new LazyMember<MapiTypeConverterMap>( delegate() { MapiTypeConverterMap map = new MapiTypeConverterMap(); map.Add( MapiPropertyType.ApplicationTime, new MapiTypeConverterMapEntry(typeof(double))); map.Add( MapiPropertyType.ApplicationTimeArray, new MapiTypeConverterMapEntry(typeof(double)) { IsArray = true }); var byteConverter = new MapiTypeConverterMapEntry(typeof(byte[])) { Parse = (s) => string.IsNullOrEmpty(s) ? null : Convert.FromBase64String(s), ConvertToString = (o) => Convert.ToBase64String((byte[])o), }; map.Add( MapiPropertyType.Binary, byteConverter); var byteArrayConverter = new MapiTypeConverterMapEntry(typeof(byte[])) { Parse = (s) => string.IsNullOrEmpty(s) ? null : Convert.FromBase64String(s), ConvertToString = (o) => Convert.ToBase64String((byte[])o), IsArray = true }; map.Add( MapiPropertyType.BinaryArray, byteArrayConverter); var boolConverter = new MapiTypeConverterMapEntry(typeof(bool)) { Parse = (s) => Convert.ChangeType(s, typeof(bool), CultureInfo.InvariantCulture), ConvertToString = (o) => ((bool)o).ToString(CultureInfo.InvariantCulture).ToLower(), }; map.Add( MapiPropertyType.Boolean, boolConverter); var clsidConverter = new MapiTypeConverterMapEntry(typeof(Guid)) { Parse = (s) => new Guid(s), ConvertToString = (o) => ((Guid)o).ToString(), }; map.Add( MapiPropertyType.CLSID, clsidConverter); var clsidArrayConverter = new MapiTypeConverterMapEntry(typeof(Guid)) { Parse = (s) => new Guid(s), ConvertToString = (o) => ((Guid)o).ToString(), IsArray = true }; map.Add( MapiPropertyType.CLSIDArray, clsidArrayConverter); map.Add( MapiPropertyType.Currency, new MapiTypeConverterMapEntry(typeof(Int64))); map.Add( MapiPropertyType.CurrencyArray, new MapiTypeConverterMapEntry(typeof(Int64)) { IsArray = true }); map.Add( MapiPropertyType.Double, new MapiTypeConverterMapEntry(typeof(double))); map.Add( MapiPropertyType.DoubleArray, new MapiTypeConverterMapEntry(typeof(double)) { IsArray = true }); map.Add( MapiPropertyType.Error, new MapiTypeConverterMapEntry(typeof(Int32))); map.Add( MapiPropertyType.Float, new MapiTypeConverterMapEntry(typeof(float))); map.Add( MapiPropertyType.FloatArray, new MapiTypeConverterMapEntry(typeof(float)) { IsArray = true }); map.Add( MapiPropertyType.Integer, new MapiTypeConverterMapEntry(typeof(Int32)) { Parse = (s) => MapiTypeConverter.ParseMapiIntegerValue(s) }); map.Add( MapiPropertyType.IntegerArray, new MapiTypeConverterMapEntry(typeof(Int32)) { IsArray = true }); map.Add( MapiPropertyType.Long, new MapiTypeConverterMapEntry(typeof(Int64))); map.Add( MapiPropertyType.LongArray, new MapiTypeConverterMapEntry(typeof(Int64)) { IsArray = true }); var objectConverter = new MapiTypeConverterMapEntry(typeof(string)) { Parse = (s) => s }; map.Add( MapiPropertyType.Object, objectConverter); var objectArrayConverter = new MapiTypeConverterMapEntry(typeof(string)) { Parse = (s) => s, IsArray = true }; map.Add( MapiPropertyType.ObjectArray, objectArrayConverter); map.Add( MapiPropertyType.Short, new MapiTypeConverterMapEntry(typeof(Int16))); map.Add( MapiPropertyType.ShortArray, new MapiTypeConverterMapEntry(typeof(Int16)) { IsArray = true }); var stringConverter = new MapiTypeConverterMapEntry(typeof(string)) { Parse = (s) => s }; map.Add( MapiPropertyType.String, stringConverter); var stringArrayConverter = new MapiTypeConverterMapEntry(typeof(string)) { Parse = (s) => s, IsArray = true }; map.Add( MapiPropertyType.StringArray, stringArrayConverter); var sysTimeConverter = new MapiTypeConverterMapEntry(typeof(DateTime)) { Parse = (s) => DateTime.Parse(s, CultureInfo.InvariantCulture, UtcDataTimeStyles), ConvertToString = (o) => EwsUtilities.DateTimeToXSDateTime((DateTime)o) // Can't use DataTime.ToString() }; map.Add( MapiPropertyType.SystemTime, sysTimeConverter); var sysTimeArrayConverter = new MapiTypeConverterMapEntry(typeof(DateTime)) { IsArray = true, Parse = (s) => DateTime.Parse(s, CultureInfo.InvariantCulture, UtcDataTimeStyles), ConvertToString = (o) => EwsUtilities.DateTimeToXSDateTime((DateTime)o) // Can't use DataTime.ToString() }; map.Add( MapiPropertyType.SystemTimeArray, sysTimeArrayConverter); return map; }); /// <summary> /// Converts the string list to array. /// </summary> /// <param name="mapiPropType">Type of the MAPI property.</param> /// <param name="strings">Strings.</param> /// <returns>Array of objects.</returns> internal static Array ConvertToValue(MapiPropertyType mapiPropType, IEnumerable<string> strings) { EwsUtilities.ValidateParam(strings, "strings"); MapiTypeConverterMapEntry typeConverter = MapiTypeConverterMap[mapiPropType]; Array array = Array.CreateInstance(typeConverter.Type, strings.Count<string>()); int index = 0; foreach (string stringValue in strings) { object value = typeConverter.ConvertToValueOrDefault(stringValue); array.SetValue(value, index++); } return array; } /// <summary> /// Converts a string to value consistent with MAPI type. /// </summary> /// <param name="mapiPropType">Type of the MAPI property.</param> /// <param name="stringValue">String to convert to a value.</param> /// <returns></returns> internal static object ConvertToValue(MapiPropertyType mapiPropType, string stringValue) { return MapiTypeConverterMap[mapiPropType].ConvertToValue(stringValue); } /// <summary> /// Converts a value to a string. /// </summary> /// <param name="mapiPropType">Type of the MAPI property.</param> /// <param name="value">Value to convert to string.</param> /// <returns>String value.</returns> internal static string ConvertToString(MapiPropertyType mapiPropType, object value) { return (value == null) ? string.Empty : MapiTypeConverterMap[mapiPropType].ConvertToString(value); } /// <summary> /// Change value to a value of compatible type. /// </summary> /// <param name="mapiType">Type of the mapi property.</param> /// <param name="value">The value.</param> /// <returns>Compatible value.</returns> internal static object ChangeType(MapiPropertyType mapiType, object value) { EwsUtilities.ValidateParam(value, "value"); return MapiTypeConverterMap[mapiType].ChangeType(value); } /// <summary> /// Converts a MAPI Integer value. /// </summary> /// <remarks> /// Usually the value is an integer but there are cases where the value has been "schematized" to an /// Enumeration value (e.g. NoData) which we have no choice but to fallback and represent as a string. /// </remarks> /// <param name="s">The string value.</param> /// <returns>Integer value or the original string if the value could not be parsed as such.</returns> internal static object ParseMapiIntegerValue(string s) { int intValue; if (Int32.TryParse(s, NumberStyles.Integer, CultureInfo.InvariantCulture, out intValue)) { return intValue; } else { return s; } } /// <summary> /// Determines whether MapiPropertyType is an array type. /// </summary> /// <param name="mapiType">Type of the mapi.</param> /// <returns>True if this is an array type.</returns> internal static bool IsArrayType(MapiPropertyType mapiType) { return MapiTypeConverterMap[mapiType].IsArray; } /// <summary> /// Gets the MAPI type converter map. /// </summary> /// <value>The MAPI type converter map.</value> internal static MapiTypeConverterMap MapiTypeConverterMap { get { return mapiTypeConverterMap.Member; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ShiftLeftLogical128BitLaneByte1() { var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneByte1(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local class works test.RunClassLclFldScenario(); // Validates passing an instance member of a class works test.RunClassFldScenario(); // Validates passing the field of a local struct works test.RunStructLclFldScenario(); // Validates passing an instance member of a struct works test.RunStructFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class ImmUnaryOpTest__ShiftLeftLogical128BitLaneByte1 { private struct TestStruct { public Vector128<Byte> _fld; public static TestStruct Create() { var testStruct = new TestStruct(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref testStruct._fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); return testStruct; } public void RunStructFldScenario(ImmUnaryOpTest__ShiftLeftLogical128BitLaneByte1 testClass) { var result = Sse2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(testClass._dataTable.outArrayPtr, result); testClass.ValidateResult(_fld, testClass._dataTable.outArrayPtr); } } private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Byte>>() / sizeof(Byte); private static Byte[] _data = new Byte[Op1ElementCount]; private static Vector128<Byte> _clsVar; private Vector128<Byte> _fld; private SimpleUnaryOpTest__DataTable<Byte, Byte> _dataTable; static ImmUnaryOpTest__ShiftLeftLogical128BitLaneByte1() { for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _clsVar), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); } public ImmUnaryOpTest__ShiftLeftLogical128BitLaneByte1() { Succeeded = true; for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)8; } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<Byte>, byte>(ref _fld), ref Unsafe.As<Byte, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<Byte>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (byte)8; } _dataTable = new SimpleUnaryOpTest__DataTable<Byte, Byte>(_data, new Byte[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse2.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_UnsafeRead)); var result = Sse2.ShiftLeftLogical128BitLane( Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_Load)); var result = Sse2.ShiftLeftLogical128BitLane( Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunBasicScenario_LoadAligned)); var result = Sse2.ShiftLeftLogical128BitLane( Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)), 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_UnsafeRead)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_Load)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunReflectionScenario_LoadAligned)); var result = typeof(Sse2).GetMethod(nameof(Sse2.ShiftLeftLogical128BitLane), new Type[] { typeof(Vector128<Byte>), typeof(byte) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)), (byte)1 }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Byte>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClsVarScenario)); var result = Sse2.ShiftLeftLogical128BitLane( _clsVar, 1 ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_UnsafeRead)); var firstOp = Unsafe.Read<Vector128<Byte>>(_dataTable.inArrayPtr); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_Load)); var firstOp = Sse2.LoadVector128((Byte*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { TestLibrary.TestFramework.BeginScenario(nameof(RunLclVarScenario_LoadAligned)); var firstOp = Sse2.LoadAlignedVector128((Byte*)(_dataTable.inArrayPtr)); var result = Sse2.ShiftLeftLogical128BitLane(firstOp, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunClassLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassLclFldScenario)); var test = new ImmUnaryOpTest__ShiftLeftLogical128BitLaneByte1(); var result = Sse2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunClassFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunClassFldScenario)); var result = Sse2.ShiftLeftLogical128BitLane(_fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunStructLclFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructLclFldScenario)); var test = TestStruct.Create(); var result = Sse2.ShiftLeftLogical128BitLane(test._fld, 1); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunStructFldScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunStructFldScenario)); var test = TestStruct.Create(); test.RunStructFldScenario(this); } public void RunUnsupportedScenario() { TestLibrary.TestFramework.BeginScenario(nameof(RunUnsupportedScenario)); bool succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { succeeded = true; } if (!succeeded) { Succeeded = false; } } private void ValidateResult(Vector128<Byte> firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { Byte[] inArray = new Byte[Op1ElementCount]; Byte[] outArray = new Byte[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<Byte>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Byte, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Byte>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(Byte[] firstOp, Byte[] result, [CallerMemberName] string method = "") { bool succeeded = true; if (result[0] != 0) { succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != 8) { succeeded = false; break; } } } if (!succeeded) { TestLibrary.TestFramework.LogInformation($"{nameof(Sse2)}.{nameof(Sse2.ShiftLeftLogical128BitLane)}<Byte>(Vector128<Byte><9>): {method} failed:"); TestLibrary.TestFramework.LogInformation($" firstOp: ({string.Join(", ", firstOp)})"); TestLibrary.TestFramework.LogInformation($" result: ({string.Join(", ", result)})"); TestLibrary.TestFramework.LogInformation(string.Empty); Succeeded = false; } } } }
using Bridge.Contract; using System.Collections.Generic; namespace Bridge.Translator { public class AssemblyInfo : IAssemblyInfo { public const string DEFAULT_FILENAME = "---"; public const string DEFAULT_OUTPUT = "$(OutDir)/bridge/"; public AssemblyInfo() { this.Dependencies = new List<IPluginDependency>(); this.DefineConstants = new List<string>(); this.Logging = new LoggingOptions(); this.Reflection = new ReflectionConfig(); this.ReflectionInternal = new ReflectionConfig(); this.Assembly = new AssemblyConfig(); this.Resources = new ResourceConfig(); this.Loader = new ModuleLoader(); this.Output = DEFAULT_OUTPUT; this.SourceMap = new SourceMapConfig(); this.Html = new HtmlConfig(); this.Console = new ConsoleConfig(); this.Report = new ReportConfig(); this.Rules = new CompilerRule(); this.IgnoreDuplicateTypes = false; } /// <summary> /// A file name where JavaScript is generated to. If omitted, it is [Namespace_Name].js by default. /// Example: "MyBridgeNetLibrary.js" /// Tip. You can decorate a class with a [FileName('MyClass.js')] attribute. A class script will be generated to the defined file. It supersedes a global bridge.json fileName. /// </summary> public string FileName { get; set; } /// <summary> /// The output folder path for generated JavaScript. A non-absolute path is concatenated with a project's root. /// Examples: "Bridge\\output\\", "..\\Bridge\\output\\", "c:\\Bridge\\output\\" /// </summary> public string Output { get; set; } private OutputBy outputBy = OutputBy.Project; /// <summary> /// The option to manage JavaScript output folders and files. /// See the OutputBy enum for more details. /// </summary> public OutputBy OutputBy { get { if (this.CombineScripts || !string.IsNullOrEmpty(this.FileName)) { return OutputBy.Project; } return this.outputBy; } set { this.outputBy = value; } } private FileNameCaseConvert jsFileCasing = FileNameCaseConvert.None; /// <summary> /// The option to manage JavaScript file name case converting for class grouping. /// See the FileNameCaseConvert enum for more details. /// </summary> public FileNameCaseConvert FileNameCasing { get { return this.jsFileCasing; } set { this.jsFileCasing = value; } } private JavaScriptOutputType jsOutType = JavaScriptOutputType.Both; /// <summary> /// The option to select JavaScript file output for only beautified, only minified or both versions. /// See the JavaScriptOutputType enum for more details. /// </summary> public JavaScriptOutputType OutputFormatting { get { return this.jsOutType; } set { this.jsOutType = value; } } /// <summary> /// Substrings the file name starting with the defined index. /// For example, it might be useful to get rid of the first namespace in the chain if use ByFullName or ByNamespace FilesHierarchy. /// </summary> public int StartIndexInName { get; set; } /// <summary> /// The global Module setting. The entire project is considered as one Module. /// Though, you are still able to define a Module attribute on the class level. /// </summary> public Module Module { get; set; } /// <summary> /// The list of module dependencies. /// </summary> public List<IPluginDependency> Dependencies { get; set; } /// <summary> /// The executable file to be launched before building. The path will be concatenated with the project's root. /// For example, it might be used for cleaning up the output directory - "Bridge\\builder\\clean.bat". /// </summary> public string BeforeBuild { get; set; } /// <summary> /// The executable file to be launched after building. The path will be concatenated with the project's root. /// For example, it might be used for copying the generated JavaScript files to a Web application - "Bridge\\builder\\copy.bat" /// </summary> public string AfterBuild { get; set; } public bool AutoPropertyToField { get; set; } public string PluginsPath { get; set; } public bool GenerateTypeScript { get; set; } private Bridge.Contract.DocumentationMode generateDocumentation = Bridge.Contract.DocumentationMode.Basic; public Bridge.Contract.DocumentationMode GenerateDocumentation { get { return this.generateDocumentation; } set { this.generateDocumentation = value; } } /// <summary> /// The BuildArguments will be added to the command line that build project files. It is useful for debugging, logging etc. /// For example, "/fileLogger /fileLoggerParameters:Append;" /// </summary> public string BuildArguments { get; set; } /// <summary> /// Deletes files from output directory using pattern "*.js|*.d.ts" before build (before extracting scripts after translation). /// It is useful to replace BeforeBuild event if it just contain commands to clean the output folder. /// Default value is null. It can be used either as string or bool value. True means "*.js|*.d.ts" /// </summary> public string CleanOutputFolderBeforeBuild { get; set; } /// <summary> /// Sets pattern for cleaning output directory. /// </summary> public string CleanOutputFolderBeforeBuildPattern { get; set; } public string Configuration { get; set; } public List<string> DefineConstants { get; set; } public string Locales { get; set; } public string LocalesOutput { get; set; } public string LocalesFileName { get; set; } public bool CombineLocales { get; set; } public bool CombineScripts { get; set; } public bool UseTypedArrays { get; set; } public bool IgnoreCast { get; set; } public LoggingOptions Logging { get; set; } public OverflowMode? OverflowMode { get; set; } public bool? NoLoggerTimeStamps { get; set; } public bool StrictNullChecks { get; set; } public IReflectionConfig Reflection { get; set; } internal IReflectionConfig ReflectionInternal { get; set; } public AssemblyConfig Assembly { get; set; } public ResourceConfig Resources { get; set; } public IModuleLoader Loader { get; set; } public NamedFunctionMode NamedFunctions { get; set; } [Newtonsoft.Json.JsonConverter(typeof(SourceMapConfigConverter))] public SourceMapConfig SourceMap { get; set; } [Newtonsoft.Json.JsonConverter(typeof(HtmlConfigConverter))] public HtmlConfig Html { get; set; } [Newtonsoft.Json.JsonConverter(typeof(ConsoleConfigConverter))] public ConsoleConfig Console { get; set; } [Newtonsoft.Json.JsonConverter(typeof(ReportConfigConverter))] public ReportConfig Report { get; set; } public CompilerRule Rules { get; set; } public string ReferencesPath { get; set; } public string[] References { get; set; } /// <summary> /// Skips loading types off assemblies when they have already been loaded. /// If false, throws an exception when a same type comes from more than /// one assembly. /// </summary> public bool IgnoreDuplicateTypes { get; set; } } }
using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Linq; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Provides access to configuration variables for a repository. /// </summary> public class Configuration : IDisposable, IEnumerable<ConfigurationEntry<string>> { private readonly FilePath globalConfigPath; private readonly FilePath xdgConfigPath; private readonly FilePath systemConfigPath; private readonly Repository repository; private ConfigurationSafeHandle configHandle; /// <summary> /// Needed for mocking purposes. /// </summary> protected Configuration() { } internal Configuration(Repository repository, string globalConfigurationFileLocation, string xdgConfigurationFileLocation, string systemConfigurationFileLocation) { this.repository = repository; globalConfigPath = globalConfigurationFileLocation ?? Proxy.git_config_find_global(); xdgConfigPath = xdgConfigurationFileLocation ?? Proxy.git_config_find_xdg(); systemConfigPath = systemConfigurationFileLocation ?? Proxy.git_config_find_system(); Init(); } private void Init() { configHandle = Proxy.git_config_new(); if (repository != null) { //TODO: push back this logic into libgit2. // As stated by @carlosmn "having a helper function to load the defaults and then allowing you // to modify it before giving it to git_repository_open_ext() would be a good addition, I think." // -- Agreed :) string repoConfigLocation = Path.Combine(repository.Info.Path, "config"); Proxy.git_config_add_file_ondisk(configHandle, repoConfigLocation, ConfigurationLevel.Local); Proxy.git_repository_set_config(repository.Handle, configHandle); } if (globalConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, globalConfigPath, ConfigurationLevel.Global); } if (xdgConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, xdgConfigPath, ConfigurationLevel.Xdg); } if (systemConfigPath != null) { Proxy.git_config_add_file_ondisk(configHandle, systemConfigPath, ConfigurationLevel.System); } } /// <summary> /// Access configuration values without a repository. Generally you want to access configuration via an instance of <see cref="Repository"/> instead. /// </summary> /// <param name="globalConfigurationFileLocation">Path to a Global configuration file. If null, the default path for a global configuration file will be probed.</param> /// <param name="xdgConfigurationFileLocation">Path to a XDG configuration file. If null, the default path for a XDG configuration file will be probed.</param> /// <param name="systemConfigurationFileLocation">Path to a System configuration file. If null, the default path for a system configuration file will be probed.</param> public Configuration(string globalConfigurationFileLocation = null, string xdgConfigurationFileLocation = null, string systemConfigurationFileLocation = null) : this(null, globalConfigurationFileLocation, xdgConfigurationFileLocation, systemConfigurationFileLocation) { } /// <summary> /// Determines which configuration file has been found. /// </summary> public virtual bool HasConfig(ConfigurationLevel level) { using (ConfigurationSafeHandle snapshot = Snapshot ()) using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) { return handle != null; } } #region IDisposable Members /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// Saves any open configuration files. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } #endregion /// <summary> /// Unset a configuration variable (key and value). /// </summary> /// <param name="key">The key to unset.</param> /// <param name="level">The configuration file which should be considered as the target of this operation</param> public virtual void Unset(string key, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { Proxy.git_config_delete(h, key); } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> protected virtual void Dispose(bool disposing) { configHandle.SafeDispose(); } /// <summary> /// Get a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// The same escalation logic than in git.git will be used when looking for the key in the config files: /// - local: the Git file in the current repository /// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`) /// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`) /// - system: the system-wide Git file /// /// The first occurence of the key will be returned. /// </para> /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get&lt;bool&gt;("core.bare").Value; /// </code> /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key</param> /// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns> public virtual ConfigurationEntry<T> Get<T>(string key) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle snapshot = Snapshot()) { return Proxy.git_config_get_entry<T>(snapshot, key); } } /// <summary> /// Get a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to get the value for this in a .git\config file: /// /// <code> /// [core] /// bare = true /// </code> /// /// You would call: /// /// <code> /// bool isBare = repo.Config.Get&lt;bool&gt;("core.bare").Value; /// </code> /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key</param> /// <param name="level">The configuration file into which the key should be searched for</param> /// <returns>The <see cref="ConfigurationEntry{T}"/>, or null if not set</returns> public virtual ConfigurationEntry<T> Get<T>(string key, ConfigurationLevel level) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle snapshot = Snapshot()) using (ConfigurationSafeHandle handle = RetrieveConfigurationHandle(level, false, snapshot)) { if (handle == null) { return null; } return Proxy.git_config_get_entry<T>(handle, key); } } /// <summary> /// Set a configuration value for a key. Keys are in the form 'section.name'. /// <para> /// For example in order to set the value for this in a .git\config file: /// /// [test] /// boolsetting = true /// /// You would call: /// /// repo.Config.Set("test.boolsetting", true); /// </para> /// </summary> /// <typeparam name="T">The configuration value type</typeparam> /// <param name="key">The key parts</param> /// <param name="value">The value</param> /// <param name="level">The configuration file which should be considered as the target of this operation</param> public virtual void Set<T>(string key, T value, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(key, "key"); using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, configHandle)) { if (!configurationTypedUpdater.ContainsKey(typeof(T))) { throw new ArgumentException(string.Format(CultureInfo.InvariantCulture, "Generic Argument of type '{0}' is not supported.", typeof(T).FullName)); } configurationTypedUpdater[typeof(T)](key, value, h); } } /// <summary> /// Find configuration entries matching <paramref name="regexp"/>. /// </summary> /// <param name="regexp">A regular expression.</param> /// <param name="level">The configuration file into which the key should be searched for.</param> /// <returns>Matching entries.</returns> public virtual IEnumerable<ConfigurationEntry<string>> Find(string regexp, ConfigurationLevel level = ConfigurationLevel.Local) { Ensure.ArgumentNotNullOrEmptyString(regexp, "regexp"); using (ConfigurationSafeHandle snapshot = Snapshot()) using (ConfigurationSafeHandle h = RetrieveConfigurationHandle(level, true, snapshot)) { return Proxy.git_config_iterator_glob(h, regexp, BuildConfigEntry).ToList(); } } private ConfigurationSafeHandle RetrieveConfigurationHandle(ConfigurationLevel level, bool throwIfStoreHasNotBeenFound, ConfigurationSafeHandle fromHandle) { ConfigurationSafeHandle handle = null; if (fromHandle != null) { handle = Proxy.git_config_open_level(fromHandle, level); } if (handle == null && throwIfStoreHasNotBeenFound) { throw new LibGit2SharpException( string.Format(CultureInfo.InvariantCulture, "No {0} configuration file has been found.", Enum.GetName(typeof(ConfigurationLevel), level))); } return handle; } private static Action<string, object, ConfigurationSafeHandle> GetUpdater<T>(Action<ConfigurationSafeHandle, string, T> setter) { return (key, val, handle) => setter(handle, key, (T)val); } private readonly static IDictionary<Type, Action<string, object, ConfigurationSafeHandle>> configurationTypedUpdater = new Dictionary<Type, Action<string, object, ConfigurationSafeHandle>> { { typeof(int), GetUpdater<int>(Proxy.git_config_set_int32) }, { typeof(long), GetUpdater<long>(Proxy.git_config_set_int64) }, { typeof(bool), GetUpdater<bool>(Proxy.git_config_set_bool) }, { typeof(string), GetUpdater<string>(Proxy.git_config_set_string) }, }; /// <summary> /// Returns an enumerator that iterates through the configuration entries. /// </summary> /// <returns>An <see cref="IEnumerator{T}"/> object that can be used to iterate through the configuration entries.</returns> public virtual IEnumerator<ConfigurationEntry<string>> GetEnumerator() { return BuildConfigEntries().GetEnumerator(); } System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return ((IEnumerable<ConfigurationEntry<string>>)this).GetEnumerator(); } private IEnumerable<ConfigurationEntry<string>> BuildConfigEntries() { return Proxy.git_config_foreach(configHandle, BuildConfigEntry); } private static ConfigurationEntry<string> BuildConfigEntry(IntPtr entryPtr) { var entry = entryPtr.MarshalAs<GitConfigEntry>(); return new ConfigurationEntry<string>(LaxUtf8Marshaler.FromNative(entry.namePtr), LaxUtf8Marshaler.FromNative(entry.valuePtr), (ConfigurationLevel)entry.level); } /// <summary> /// Builds a <see cref="Signature"/> based on current configuration. /// <para> /// Name is populated from the user.name setting, and is "unknown" if unspecified. /// Email is populated from the user.email setting, and is built from /// <see cref="Environment.UserName"/> and <see cref="Environment.UserDomainName"/> if unspecified. /// </para> /// <para> /// The same escalation logic than in git.git will be used when looking for the key in the config files: /// - local: the Git file in the current repository /// - global: the Git file specific to the current interactive user (usually in `$HOME/.gitconfig`) /// - xdg: another Git file specific to the current interactive user (usually in `$HOME/.config/git/config`) /// - system: the system-wide Git file /// </para> /// </summary> /// <param name="now">The timestamp to use for the <see cref="Signature"/>.</param> /// <returns>The signature.</returns> public virtual Signature BuildSignature(DateTimeOffset now) { return BuildSignature(now, false); } internal Signature BuildSignature(DateTimeOffset now, bool shouldThrowIfNotFound) { var name = Get<string>("user.name"); var email = Get<string>("user.email"); if (shouldThrowIfNotFound) { if (name == null || string.IsNullOrEmpty(name.Value)) { throw new LibGit2SharpException( "Can not find Name setting of the current user in Git configuration."); } if (email == null || string.IsNullOrEmpty(email.Value)) { throw new LibGit2SharpException( "Can not find Email setting of the current user in Git configuration."); } } var nameForSignature = name == null || string.IsNullOrEmpty(name.Value) ? "unknown" : name.Value; var emailForSignature = email == null || string.IsNullOrEmpty(email.Value) ? string.Format("{0}@{1}", Environment.UserName, Environment.UserDomainName) : email.Value; return new Signature(nameForSignature, emailForSignature, now); } private ConfigurationSafeHandle Snapshot() { return Proxy.git_config_snapshot(configHandle); } } } /* This is extra31 */
using System; namespace Amib.Threading { /// <summary> /// Summary description for WIGStartInfo. /// </summary> public class WIGStartInfo { private bool _useCallerCallContext = SmartThreadPool.DefaultUseCallerCallContext; private bool _useCallerHttpContext = SmartThreadPool.DefaultUseCallerHttpContext; private bool _disposeOfStateObjects = SmartThreadPool.DefaultDisposeOfStateObjects; private CallToPostExecute _callToPostExecute = SmartThreadPool.DefaultCallToPostExecute; private PostExecuteWorkItemCallback _postExecuteWorkItemCallback = SmartThreadPool.DefaultPostExecuteWorkItemCallback; private WorkItemPriority _workItemPriority = SmartThreadPool.DefaultWorkItemPriority; private bool _startSuspended = SmartThreadPool.DefaultStartSuspended; private bool _fillStateWithArgs = SmartThreadPool.DefaultFillStateWithArgs; public WIGStartInfo() { } public WIGStartInfo(WIGStartInfo wigStartInfo) { _useCallerCallContext = wigStartInfo._useCallerCallContext; _useCallerHttpContext = wigStartInfo._useCallerHttpContext; _disposeOfStateObjects = wigStartInfo._disposeOfStateObjects; _callToPostExecute = wigStartInfo._callToPostExecute; _postExecuteWorkItemCallback = wigStartInfo._postExecuteWorkItemCallback; _workItemPriority = wigStartInfo._workItemPriority; _startSuspended = wigStartInfo._startSuspended; _fillStateWithArgs = wigStartInfo._fillStateWithArgs; } /// <summary> /// Get/Set if to use the caller's security context /// </summary> public virtual bool UseCallerCallContext { get { return _useCallerCallContext; } set { _useCallerCallContext = value; } } /// <summary> /// Get/Set if to use the caller's HTTP context /// </summary> public virtual bool UseCallerHttpContext { get { return _useCallerHttpContext; } set { _useCallerHttpContext = value; } } /// <summary> /// Get/Set if to dispose of the state object of a work item /// </summary> public virtual bool DisposeOfStateObjects { get { return _disposeOfStateObjects; } set { _disposeOfStateObjects = value; } } /// <summary> /// Get/Set the run the post execute options /// </summary> public virtual CallToPostExecute CallToPostExecute { get { return _callToPostExecute; } set { _callToPostExecute = value; } } /// <summary> /// Get/Set the default post execute callback /// </summary> public virtual PostExecuteWorkItemCallback PostExecuteWorkItemCallback { get { return _postExecuteWorkItemCallback; } set { _postExecuteWorkItemCallback = value; } } /// <summary> /// Get/Set if the work items execution should be suspended until the Start() /// method is called. /// </summary> public virtual bool StartSuspended { get { return _startSuspended; } set { _startSuspended = value; } } /// <summary> /// Get/Set the default priority that a work item gets when it is enqueued /// </summary> public virtual WorkItemPriority WorkItemPriority { get { return _workItemPriority; } set { _workItemPriority = value; } } /// <summary> /// Get/Set the if QueueWorkItem of Action<...>/Func<...> fill the /// arguments as an object array into the state of the work item. /// The arguments can be access later by IWorkItemResult.State. /// </summary> public virtual bool FillStateWithArgs { get { return _fillStateWithArgs; } set { _fillStateWithArgs = value; } } /// <summary> /// Get a readonly version of this WIGStartInfo /// </summary> /// <returns>Returns a readonly reference to this WIGStartInfoRO</returns> public WIGStartInfo AsReadOnly() { return new WIGStartInfoRO(this); } #region WIGStartInfoRO class /// <summary> /// A readonly version of WIGStartInfo /// </summary> private class WIGStartInfoRO : WIGStartInfo { private readonly WIGStartInfo _wigStartInfoRO; public WIGStartInfoRO(WIGStartInfo wigStartInfoRO) { _wigStartInfoRO = wigStartInfoRO; } /// <summary> /// Get if to use the caller's security context /// </summary> public override bool UseCallerCallContext { get { return _wigStartInfoRO.UseCallerCallContext; } set { throw new NotSupportedException("This is a readonly instance and set is not supported"); } } /// <summary> /// Get if to use the caller's HTTP context /// </summary> public override bool UseCallerHttpContext { get { return _wigStartInfoRO.UseCallerHttpContext; } set { throw new NotSupportedException("This is a readonly instance and set is not supported"); } } /// <summary> /// Get if to dispose of the state object of a work item /// </summary> public override bool DisposeOfStateObjects { get { return _wigStartInfoRO.DisposeOfStateObjects; } set { throw new NotSupportedException("This is a readonly instance and set is not supported"); } } /// <summary> /// Get the run the post execute options /// </summary> public override CallToPostExecute CallToPostExecute { get { return _wigStartInfoRO.CallToPostExecute; } set { throw new NotSupportedException("This is a readonly instance and set is not supported"); } } /// <summary> /// Get the default post execute callback /// </summary> public override PostExecuteWorkItemCallback PostExecuteWorkItemCallback { get { return _wigStartInfoRO.PostExecuteWorkItemCallback; } set { throw new NotSupportedException("This is a readonly instance and set is not supported"); } } /// <summary> /// Get if the work items execution should be suspended until the Start() /// method is called. /// </summary> public override bool StartSuspended { get { return _wigStartInfoRO.StartSuspended; } set { throw new NotSupportedException("This is a readonly instance and set is not supported"); } } /// <summary> /// Get the default priority that a work item gets when it is enqueued /// </summary> public override WorkItemPriority WorkItemPriority { get { return _wigStartInfoRO.WorkItemPriority; } set { throw new NotSupportedException("This is a readonly instance and set is not supported"); } } /// <summary> /// Indicate if QueueWorkItem of Action<...>/Func<...> fill the /// arguments as an object array into the state of the work item. /// The arguments can be access later by IWorkItemResult.State. /// </summary> public override bool FillStateWithArgs { get { return _wigStartInfoRO.FillStateWithArgs; } set { throw new NotSupportedException("This is a readonly instance and set is not supported"); } } } #endregion } }
// // Program.cs // // Author: Jeffrey Stedfast <jeff@xamarin.com> // // Copyright (c) 2014 Xamarin Inc. (www.xamarin.com) // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // using System; using System.Net; using System.Linq; using System.Threading; using System.Collections.Generic; using MailKit.Net.Imap; using MailKit; namespace ImapIdle { class Program { public static void Main (string[] args) { using (var client = new ImapClient (new ProtocolLogger (Console.OpenStandardError ()))) { client.Connect ("imap.gmail.com", 993, true); // Remove the XOAUTH2 authentication mechanism since we don't have an OAuth2 token. client.AuthenticationMechanisms.Remove ("XOAUTH2"); client.Authenticate ("username@gmail.com", "password"); client.Inbox.Open (FolderAccess.ReadOnly); // Get the summary information of all of the messages (suitable for displaying in a message list). var messages = client.Inbox.Fetch (0, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId).ToList (); // Keep track of messages being expunged so that when the CountChanged event fires, we can tell if it's // because new messages have arrived vs messages being removed (or some combination of the two). client.Inbox.MessageExpunged += (sender, e) => { var folder = (ImapFolder) sender; if (e.Index < messages.Count) { var message = messages[e.Index]; Console.WriteLine ("{0}: expunged message {1}: Subject: {2}", folder, e.Index, message.Envelope.Subject); // Note: If you are keeping a local cache of message information // (e.g. MessageSummary data) for the folder, then you'll need // to remove the message at e.Index. messages.RemoveAt (e.Index); } else { Console.WriteLine ("{0}: expunged message {1}: Unknown message.", folder, e.Index); } }; // Keep track of changes to the number of messages in the folder (this is how we'll tell if new messages have arrived). client.Inbox.CountChanged += (sender, e) => { // Note: the CountChanged event will fire when new messages arrive in the folder and/or when messages are expunged. var folder = (ImapFolder) sender; Console.WriteLine ("The number of messages in {0} has changed.", folder); // Note: because we are keeping track of the MessageExpunged event and updating our // 'messages' list, we know that if we get a CountChanged event and folder.Count is // larger than messages.Count, then it means that new messages have arrived. if (folder.Count > messages.Count) { Console.WriteLine ("{0} new messages have arrived.", folder.Count - messages.Count); // Note: your first instict may be to fetch these new messages now, but you cannot do // that in an event handler (the ImapFolder is not re-entrant). // // If this code had access to the 'done' CancellationTokenSource (see below), it could // cancel that to cause the IDLE loop to end. } }; // Keep track of flag changes. client.Inbox.MessageFlagsChanged += (sender, e) => { var folder = (ImapFolder) sender; Console.WriteLine ("{0}: flags for message {1} have changed to: {2}.", folder, e.Index, e.Flags); }; Console.WriteLine ("Hit any key to end the IDLE loop."); using (var done = new CancellationTokenSource ()) { // Note: when the 'done' CancellationTokenSource is cancelled, it ends to IDLE loop. var thread = new Thread (IdleLoop); thread.Start (new IdleState (client, done.Token)); Console.ReadKey (); done.Cancel (); thread.Join (); } if (client.Inbox.Count > messages.Count) { Console.WriteLine ("The new messages that arrived during IDLE are:"); foreach (var message in client.Inbox.Fetch (messages.Count, -1, MessageSummaryItems.Full | MessageSummaryItems.UniqueId)) Console.WriteLine ("Subject: {0}", message.Envelope.Subject); } client.Disconnect (true); } } class IdleState { readonly object mutex = new object (); CancellationTokenSource timeout; /// <summary> /// Get the cancellation token. /// </summary> /// <remarks> /// <para>The cancellation token is the brute-force approach to cancelling the IDLE and/or NOOP command.</para> /// <para>Using the cancellation token will typically drop the connection to the server and so should /// not be used unless the client is in the process of shutting down or otherwise needs to /// immediately abort communication with the server.</para> /// </remarks> /// <value>The cancellation token.</value> public CancellationToken CancellationToken { get; private set; } /// <summary> /// Get the done token. /// </summary> /// <remarks> /// <para>The done token tells the <see cref="Program.IdleLoop"/> that the user has requested to end the loop.</para> /// <para>When the done token is cancelled, the <see cref="Program.IdleLoop"/> will gracefully come to an end by /// cancelling the timeout and then breaking out of the loop.</para> /// </remarks> /// <value>The done token.</value> public CancellationToken DoneToken { get; private set; } /// <summary> /// Get the IMAP client. /// </summary> /// <value>The IMAP client.</value> public ImapClient Client { get; private set; } /// <summary> /// Check whether or not either of the CancellationToken's have been cancelled. /// </summary> /// <value><c>true</c> if cancellation was requested; otherwise, <c>false</c>.</value> public bool IsCancellationRequested { get { return CancellationToken.IsCancellationRequested || DoneToken.IsCancellationRequested; } } /// <summary> /// Initializes a new instance of the <see cref="IdleState"/> class. /// </summary> /// <param name="client">The IMAP client.</param> /// <param name="doneToken">The user-controlled 'done' token.</param> /// <param name="cancellationToken">The brute-force cancellation token.</param> public IdleState (ImapClient client, CancellationToken doneToken, CancellationToken cancellationToken = default (CancellationToken)) { CancellationToken = cancellationToken; DoneToken = doneToken; Client = client; // When the user hits a key, end the current timeout as well doneToken.Register (CancelTimeout); } /// <summary> /// Cancel the timeout token source, forcing ImapClient.Idle() to gracefully exit. /// </summary> void CancelTimeout () { lock (mutex) { if (timeout != null) timeout.Cancel (); } } /// <summary> /// Set the timeout source. /// </summary> /// <param name="source">The timeout source.</param> public void SetTimeoutSource (CancellationTokenSource source) { lock (mutex) { timeout = source; if (timeout != null && IsCancellationRequested) timeout.Cancel (); } } } static void IdleLoop (object state) { var idle = (IdleState) state; lock (idle.Client.SyncRoot) { // Note: since the IMAP server will drop the connection after 30 minutes, we must loop sending IDLE commands that // last ~29 minutes or until the user has requested that they do not want to IDLE anymore. // // For GMail, we use a 9 minute interval because they do not seem to keep the connection alive for more than ~10 minutes. while (!idle.IsCancellationRequested) { // Note: Starting with .NET 4.5, you can make this simpler by using the CancellationTokenSource .ctor that // takes a TimeSpan argument, thus eliminating the need to create a timer. using (var timeout = new CancellationTokenSource ()) { using (var timer = new System.Timers.Timer (9 * 60 * 1000)) { // End the IDLE command when the timer expires. timer.Elapsed += (sender, e) => timeout.Cancel (); timer.AutoReset = false; timer.Enabled = true; try { // We set the timeout source so that if the idle.DoneToken is cancelled, it can cancel the timeout idle.SetTimeoutSource (timeout); if (idle.Client.Capabilities.HasFlag (ImapCapabilities.Idle)) { // The Idle() method will not return until the timeout has elapsed or idle.CancellationToken is cancelled idle.Client.Idle (timeout.Token, idle.CancellationToken); } else { // The IMAP server does not support IDLE, so send a NOOP command instead idle.Client.NoOp (idle.CancellationToken); // Wait for the timeout to elapse or the cancellation token to be cancelled WaitHandle.WaitAny (new [] { timeout.Token.WaitHandle, idle.CancellationToken.WaitHandle }); } } catch (OperationCanceledException) { // This means that idle.CancellationToken was cancelled, not the DoneToken nor the timeout. break; } catch (ImapProtocolException) { // The IMAP server sent garbage in a response and the ImapClient was unable to deal with it. // This should never happen in practice, but it's probably still a good idea to handle it. // // Note: an ImapProtocolException almost always results in the ImapClient getting disconnected. break; } catch (ImapCommandException) { // The IMAP server responded with "NO" or "BAD" to either the IDLE command or the NOOP command. // This should never happen... but again, we're catching it for the sake of completeness. break; } finally { // We're about to Dispose() the timeout source, so set it to null. idle.SetTimeoutSource (null); } } } } } } } }
// Python Tools for Visual Studio // Copyright(c) Microsoft Corporation // All rights reserved. // // Licensed under the Apache License, Version 2.0 (the License); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at http://www.apache.org/licenses/LICENSE-2.0 // // THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS // OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY // IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, // MERCHANTABLITY OR NON-INFRINGEMENT. // // See the Apache Version 2.0 License for specific language governing // permissions and limitations under the License. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Net.Sockets; using Microsoft.PythonTools.Intellisense; using Microsoft.PythonTools.Interpreter; using Microsoft.PythonTools.Options; using Microsoft.PythonTools.Parsing; using Microsoft.PythonTools.Project; using Microsoft.VisualStudio.InteractiveWindow.Commands; using Microsoft.VisualStudio.Utilities; using Microsoft.VisualStudioTools; using Microsoft.VisualStudioTools.Project; using SR = Microsoft.PythonTools.Project.SR; namespace Microsoft.PythonTools.Repl { [InteractiveWindowRole("Execution")] [InteractiveWindowRole("Reset")] [ContentType(PythonCoreConstants.ContentType)] [ContentType(PredefinedInteractiveCommandsContentTypes.InteractiveCommandContentTypeName)] internal class PythonReplEvaluator : BasePythonReplEvaluator { private IPythonInterpreterFactory _interpreter; private readonly IInterpreterOptionsService _interpreterService; private VsProjectAnalyzer _replAnalyzer; private bool _ownsAnalyzer, _enableAttach, _supportsMultipleCompleteStatementInputs; public PythonReplEvaluator(IPythonInterpreterFactory interpreter, IServiceProvider serviceProvider, IInterpreterOptionsService interpreterService = null) : this(interpreter, serviceProvider, new DefaultPythonReplEvaluatorOptions(serviceProvider, () => serviceProvider.GetPythonToolsService().GetInteractiveOptions(interpreter)), interpreterService) { } public PythonReplEvaluator(IPythonInterpreterFactory interpreter, IServiceProvider serviceProvider, PythonReplEvaluatorOptions options, IInterpreterOptionsService interpreterService = null) : base(serviceProvider, serviceProvider.GetPythonToolsService(), options) { _interpreter = interpreter; _interpreterService = interpreterService; if (_interpreterService != null) { _interpreterService.InterpretersChanged += InterpretersChanged; } } private class UnavailableFactory : IPythonInterpreterFactory { public UnavailableFactory(string id, string version) { Id = Guid.Parse(id); Configuration = new InterpreterConfiguration(Version.Parse(version)); } public string Description { get { return Id.ToString(); } } public InterpreterConfiguration Configuration { get; private set; } public Guid Id { get; private set; } public IPythonInterpreter CreateInterpreter() { return null; } } public static IPythonReplEvaluator Create( IServiceProvider serviceProvider, string id, string version, IInterpreterOptionsService interpreterService ) { var factory = interpreterService != null ? interpreterService.FindInterpreter(id, version) : null; if (factory == null) { try { factory = new UnavailableFactory(id, version); } catch (FormatException) { return null; } } return new PythonReplEvaluator(factory, serviceProvider, interpreterService); } async void InterpretersChanged(object sender, EventArgs e) { var current = _interpreter; if (current == null) { return; } var interpreter = _interpreterService.FindInterpreter(current.Id, current.Configuration.Version); if (interpreter != null && interpreter != current) { // the interpreter has been reconfigured, we want the new settings _interpreter = interpreter; if (_replAnalyzer != null) { var oldAnalyser = _replAnalyzer; bool disposeOld = _ownsAnalyzer && oldAnalyser != null; _replAnalyzer = null; var newAnalyzer = ReplAnalyzer; if (newAnalyzer != null && oldAnalyser != null) { newAnalyzer.SwitchAnalyzers(oldAnalyser); } if (disposeOld) { oldAnalyser.Dispose(); } } // if the previous interpreter was not available, we will want // to reset afterwards if (current is UnavailableFactory) { await Reset(); } } } public IPythonInterpreterFactory Interpreter { get { return _interpreter; } } internal VsProjectAnalyzer ReplAnalyzer { get { if (_replAnalyzer == null && Interpreter != null && _interpreterService != null) { _replAnalyzer = new VsProjectAnalyzer(_serviceProvider, Interpreter, _interpreterService.Interpreters.ToArray()); _ownsAnalyzer = true; } return _replAnalyzer; } } protected override PythonLanguageVersion AnalyzerProjectLanguageVersion { get { if (_replAnalyzer != null && _replAnalyzer.Project != null) { return _replAnalyzer.Project.LanguageVersion; } return LanguageVersion; } } protected override PythonLanguageVersion LanguageVersion { get { return Interpreter != null ? Interpreter.GetLanguageVersion() : PythonLanguageVersion.None; } } internal override string DisplayName { get { return Interpreter != null ? Interpreter.Description : string.Empty; } } public bool AttachEnabled { get { return _enableAttach && !(Interpreter is UnavailableFactory); } } public override void Dispose() { if (_ownsAnalyzer && _replAnalyzer != null) { _replAnalyzer.Dispose(); _replAnalyzer = null; } base.Dispose(); } public override void Close() { base.Close(); if (_interpreterService != null) { _interpreterService.InterpretersChanged -= InterpretersChanged; } } public override bool SupportsMultipleCompleteStatementInputs { get { return _supportsMultipleCompleteStatementInputs; } } protected override void WriteInitializationMessage() { if (Interpreter is UnavailableFactory) { Window.WriteError(SR.GetString(SR.ReplEvaluatorInterpreterNotFound)); } else { base.WriteInitializationMessage(); } } protected override void Connect() { _serviceProvider.GetUIThread().MustBeCalledFromUIThread(); var configurableOptions = CurrentOptions as ConfigurablePythonReplOptions; if (configurableOptions != null) { _interpreter = configurableOptions.InterpreterFactory ?? _interpreter; } if (Interpreter == null || Interpreter is UnavailableFactory) { Window.WriteError(SR.GetString(SR.ReplEvaluatorInterpreterNotFound)); return; } else if (String.IsNullOrWhiteSpace(Interpreter.Configuration.InterpreterPath)) { Window.WriteError(SR.GetString(SR.ReplEvaluatorInterpreterNotConfigured, Interpreter.Description)); return; } var processInfo = new ProcessStartInfo(Interpreter.Configuration.InterpreterPath); #if DEBUG bool debugMode = Environment.GetEnvironmentVariable("DEBUG_REPL") != null; processInfo.CreateNoWindow = !debugMode; processInfo.UseShellExecute = debugMode; processInfo.RedirectStandardOutput = !debugMode; processInfo.RedirectStandardError = !debugMode; processInfo.RedirectStandardInput = !debugMode; #else processInfo.CreateNoWindow = true; processInfo.UseShellExecute = false; processInfo.RedirectStandardOutput = true; processInfo.RedirectStandardError = true; processInfo.RedirectStandardInput = true; #endif Socket conn; int portNum; CreateConnection(out conn, out portNum); List<string> args = new List<string>(); if (!String.IsNullOrWhiteSpace(CurrentOptions.InterpreterOptions)) { args.Add(CurrentOptions.InterpreterOptions); } var workingDir = CurrentOptions.WorkingDirectory; if (!string.IsNullOrEmpty(workingDir)) { processInfo.WorkingDirectory = workingDir; } else { processInfo.WorkingDirectory = Interpreter.Configuration.PrefixPath; } #if DEBUG if (!debugMode) { #endif var envVars = CurrentOptions.EnvironmentVariables; if (envVars != null) { foreach (var keyValue in envVars) { processInfo.EnvironmentVariables[keyValue.Key] = keyValue.Value; } } string pathEnvVar = Interpreter.Configuration.PathEnvironmentVariable ?? ""; if (!string.IsNullOrWhiteSpace(pathEnvVar)) { var searchPaths = CurrentOptions.SearchPaths; if (string.IsNullOrEmpty(searchPaths)) { if (_serviceProvider.GetPythonToolsService().GeneralOptions.ClearGlobalPythonPath) { processInfo.EnvironmentVariables[pathEnvVar] = ""; } } else if (_serviceProvider.GetPythonToolsService().GeneralOptions.ClearGlobalPythonPath) { processInfo.EnvironmentVariables[pathEnvVar] = searchPaths; } else { processInfo.EnvironmentVariables[pathEnvVar] = searchPaths + ";" + Environment.GetEnvironmentVariable(pathEnvVar); } } #if DEBUG } #endif var interpreterArgs = CurrentOptions.InterpreterArguments; if (!String.IsNullOrWhiteSpace(interpreterArgs)) { args.Add(interpreterArgs); } var analyzer = CurrentOptions.ProjectAnalyzer; if (analyzer != null && analyzer.InterpreterFactory == _interpreter) { if (_replAnalyzer != null && _replAnalyzer != analyzer) { analyzer.SwitchAnalyzers(_replAnalyzer); } _replAnalyzer = analyzer; _ownsAnalyzer = false; } args.Add(ProcessOutput.QuoteSingleArgument(PythonToolsInstallPath.GetFile("visualstudio_py_repl.py"))); args.Add("--port"); args.Add(portNum.ToString()); if (!String.IsNullOrWhiteSpace(CurrentOptions.StartupScript)) { args.Add("--launch_file"); args.Add(ProcessOutput.QuoteSingleArgument(CurrentOptions.StartupScript)); } _enableAttach = CurrentOptions.EnableAttach; if (CurrentOptions.EnableAttach) { args.Add("--enable-attach"); } bool multipleScopes = true; if (!String.IsNullOrWhiteSpace(CurrentOptions.ExecutionMode)) { // change ID to module name if we have a registered mode var modes = Microsoft.PythonTools.Options.ExecutionMode.GetRegisteredModes(_serviceProvider); string modeValue = CurrentOptions.ExecutionMode; foreach (var mode in modes) { if (mode.Id == CurrentOptions.ExecutionMode) { modeValue = mode.Type; multipleScopes = mode.SupportsMultipleScopes; _supportsMultipleCompleteStatementInputs = mode.SupportsMultipleCompleteStatementInputs; break; } } args.Add("--execution_mode"); args.Add(modeValue); } SetMultipleScopes(multipleScopes); processInfo.Arguments = String.Join(" ", args); var process = new Process(); process.StartInfo = processInfo; try { if (!File.Exists(processInfo.FileName)) { throw new Win32Exception(Microsoft.VisualStudioTools.Project.NativeMethods.ERROR_FILE_NOT_FOUND); } process.Start(); } catch (Exception e) { if (e.IsCriticalException()) { throw; } Win32Exception wex = e as Win32Exception; if (wex != null && wex.NativeErrorCode == Microsoft.VisualStudioTools.Project.NativeMethods.ERROR_FILE_NOT_FOUND) { Window.WriteError(SR.GetString(SR.ReplEvaluatorInterpreterNotFound)); } else { Window.WriteError(SR.GetString(SR.ErrorStartingInteractiveProcess, e.ToString())); } return; } CreateCommandProcessor(conn, processInfo.RedirectStandardOutput, process); } const int ERROR_FILE_NOT_FOUND = 2; } [InteractiveWindowRole("DontPersist")] class PythonReplEvaluatorDontPersist : PythonReplEvaluator { public PythonReplEvaluatorDontPersist(IPythonInterpreterFactory interpreter, IServiceProvider serviceProvider, PythonReplEvaluatorOptions options, IInterpreterOptionsService interpreterService) : base(interpreter, serviceProvider, options, interpreterService) { } } /// <summary> /// Base class used for providing REPL options /// </summary> abstract class PythonReplEvaluatorOptions { public abstract string InterpreterOptions { get; } public abstract string WorkingDirectory { get; } public abstract IDictionary<string, string> EnvironmentVariables { get; } public abstract string StartupScript { get; } public abstract string SearchPaths { get; } public abstract string InterpreterArguments { get; } public abstract VsProjectAnalyzer ProjectAnalyzer { get; } public abstract bool UseInterpreterPrompts { get; } public abstract string ExecutionMode { get; } public abstract bool EnableAttach { get; } public abstract bool ReplSmartHistory { get; } public abstract bool LiveCompletionsOnly { get; } public abstract string PrimaryPrompt { get; } public abstract string SecondaryPrompt { get; } } class ConfigurablePythonReplOptions : PythonReplEvaluatorOptions { private IPythonInterpreterFactory _factory; private PythonProjectNode _project; internal string _interpreterOptions; internal string _workingDir; internal IDictionary<string, string> _envVars; internal string _startupScript; internal string _searchPaths; internal string _interpreterArguments; internal VsProjectAnalyzer _projectAnalyzer; internal bool _useInterpreterPrompts; internal string _executionMode; internal bool _liveCompletionsOnly; internal bool _replSmartHistory; internal bool _enableAttach; internal string _primaryPrompt; internal string _secondaryPrompt; public ConfigurablePythonReplOptions() { _replSmartHistory = true; _primaryPrompt = ">>> "; _secondaryPrompt = "... "; } internal ConfigurablePythonReplOptions Clone() { var newOptions = (ConfigurablePythonReplOptions)MemberwiseClone(); if (_envVars != null) { newOptions._envVars = new Dictionary<string, string>(); foreach (var kv in _envVars) { newOptions._envVars[kv.Key] = kv.Value; } } return newOptions; } public IPythonInterpreterFactory InterpreterFactory { get { return _factory; } set { _factory = value; } } public PythonProjectNode Project { get { return _project; } set { _project = value; } } public override string InterpreterOptions { get { return _interpreterOptions ?? ""; } } public override string WorkingDirectory { get { if (_project != null && string.IsNullOrEmpty(_workingDir)) { return _project.GetWorkingDirectory(); } return _workingDir ?? ""; } } public override IDictionary<string, string> EnvironmentVariables { get { return _envVars; } } public override string StartupScript { get { return _startupScript ?? ""; } } public override string SearchPaths { get { if (_project != null && string.IsNullOrEmpty(_searchPaths)) { return string.Join(new string(Path.PathSeparator, 1), _project.GetSearchPaths()); } return _searchPaths ?? ""; } } public override string InterpreterArguments { get { return _interpreterArguments ?? ""; } } public override VsProjectAnalyzer ProjectAnalyzer { get { return _projectAnalyzer; } } public override bool UseInterpreterPrompts { get { return _useInterpreterPrompts; } } public override string ExecutionMode { get { return _executionMode; } } public override bool EnableAttach { get { return _enableAttach; } } public override bool ReplSmartHistory { get { return _replSmartHistory; } } public override bool LiveCompletionsOnly { get { return _liveCompletionsOnly; } } public override string PrimaryPrompt { get { return _primaryPrompt; } } public override string SecondaryPrompt { get { return _secondaryPrompt; } } } /// <summary> /// Provides REPL options based upon options stored in our UI. /// </summary> class DefaultPythonReplEvaluatorOptions : PythonReplEvaluatorOptions { private readonly Func<PythonInteractiveCommonOptions> _options; private readonly IServiceProvider _serviceProvider; public DefaultPythonReplEvaluatorOptions(IServiceProvider serviceProvider, Func<PythonInteractiveCommonOptions> options) { _serviceProvider = serviceProvider; _options = options; } public override string InterpreterOptions { get { return ((PythonInteractiveOptions)_options()).InterpreterOptions; } } public override bool EnableAttach { get { return ((PythonInteractiveOptions)_options()).EnableAttach; } } public override string StartupScript { get { return ((PythonInteractiveOptions)_options()).StartupScript; } } public override string ExecutionMode { get { return ((PythonInteractiveOptions)_options()).ExecutionMode; } } public override string WorkingDirectory { get { var startupProj = PythonToolsPackage.GetStartupProject(_serviceProvider); if (startupProj != null) { return startupProj.GetWorkingDirectory(); } var textView = CommonPackage.GetActiveTextView(_serviceProvider); if (textView != null) { return Path.GetDirectoryName(textView.GetFilePath()); } return null; } } public override IDictionary<string, string> EnvironmentVariables { get { return null; } } public override string SearchPaths { get { var startupProj = PythonToolsPackage.GetStartupProject(_serviceProvider) as IPythonProject; if (startupProj != null) { return string.Join(";", startupProj.GetSearchPaths()); } return null; } } public override string InterpreterArguments { get { var startupProj = PythonToolsPackage.GetStartupProject(_serviceProvider); if (startupProj != null) { return startupProj.GetProjectProperty(PythonConstants.InterpreterArgumentsSetting, true); } return null; } } public override VsProjectAnalyzer ProjectAnalyzer { get { var startupProj = PythonToolsPackage.GetStartupProject(_serviceProvider); if (startupProj != null) { return ((PythonProjectNode)startupProj).GetAnalyzer(); } return null; } } public override bool UseInterpreterPrompts { get { return _options().UseInterpreterPrompts; } } public override bool ReplSmartHistory { get { return _options().ReplSmartHistory; } } public override bool LiveCompletionsOnly { get { return _options().LiveCompletionsOnly; } } public override string PrimaryPrompt { get { return _options().PrimaryPrompt; } } public override string SecondaryPrompt { get { return _options().SecondaryPrompt; } } } }
using System; using System.Globalization; using System.Web; using System.Web.Routing; using MbUnit.Framework; using Moq; using Subtext.Extensibility; using Subtext.Framework; using Subtext.Framework.Components; using Subtext.Framework.Routing; namespace UnitTests.Subtext.Framework.Routing { [TestFixture] public class UrlHelperTests { [Test] public void EntryUrl_WithSubfolderAndEntryHavingEntryName_RendersVirtualPathToEntryWithDateAndSlugInUrl() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "subfolder"); UrlHelper helper = SetupUrlHelper("/", routeData); DateTime dateCreated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var entry = new Entry(PostType.BlogPost) { Id = 123, DateCreated = dateCreated, DateSyndicated = dateCreated, EntryName = "post-slug" }; //act string url = helper.EntryUrl(entry); //assert Assert.AreEqual("/subfolder/archive/2008/01/23/post-slug.aspx", url); } [Test] public void EntryUrl_WithEntryHavingEntryName_RendersVirtualPathToEntryWithDateAndSlugInUrl() { //arrange UrlHelper helper = SetupUrlHelper("/"); DateTime dateCreated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var entry = new Entry(PostType.BlogPost) { Id = 123, DateSyndicated = dateCreated, DateCreated = dateCreated, EntryName = "post-slug" }; //act string url = helper.EntryUrl(entry); //assert Assert.AreEqual("/archive/2008/01/23/post-slug.aspx", url); } [Test] public void EntryUrl_WithEntryHavingEntryNameAndPublishedInTheFuture_RendersVirtualPathToEntryWithDateAndSlugInUrl() { //arrange UrlHelper helper = SetupUrlHelper("/"); DateTime dateCreated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); DateTime dateSyndicated = DateTime.ParseExact("2008/02/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var entry = new Entry(PostType.BlogPost) { Id = 123, DateCreated = dateCreated, DateSyndicated = dateSyndicated, EntryName = "post-slug" }; //act string url = helper.EntryUrl(entry); //assert Assert.AreEqual("/archive/2008/02/23/post-slug.aspx", url); } [Test] public void EntryUrl_WithEntryWhichIsReallyAnArticle_ReturnsArticleLink() { //arrange UrlHelper helper = SetupUrlHelper("/"); DateTime dateCreated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var entry = new Entry(PostType.BlogPost) { Id = 123, DateCreated = dateCreated, DateSyndicated = dateCreated, EntryName = "post-slug", PostType = PostType.Story }; //act string url = helper.EntryUrl(entry); //assert Assert.AreEqual("/articles/post-slug.aspx", url); } [Test] public void EntryUrl_WithEntryNotHavingEntryName_RendersVirtualPathWithId() { //arrange UrlHelper helper = SetupUrlHelper("/"); DateTime dateCreated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var entry = new Entry(PostType.BlogPost) { DateCreated = dateCreated, DateSyndicated = dateCreated, EntryName = string.Empty, Id = 123 }; //act string url = helper.EntryUrl(entry); //assert Assert.AreEqual("/archive/2008/01/23/123.aspx", url); } [Test] public void EntryUrlWithAppPath_WithEntryHavingEntryName_RendersVirtualPathToEntryWithDateAndSlugInUrl() { //arrange UrlHelper helper = SetupUrlHelper("/App"); DateTime dateCreated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var entry = new Entry(PostType.BlogPost) { Id = 123, DateCreated = dateCreated, DateSyndicated = dateCreated, EntryName = "post-slug" }; //act string url = helper.EntryUrl(entry); //assert Assert.AreEqual("/App/archive/2008/01/23/post-slug.aspx", url); } [Test] public void EntryUrl_WithNullEntry_ThrowsArgumentNullException() { //arrange var httpContext = new Mock<HttpContextBase>(); var requestContext = new RequestContext(httpContext.Object, new RouteData()); var helper = new UrlHelper(requestContext, new RouteCollection()); //act, assert UnitTestHelper.AssertThrowsArgumentNullException(() => helper.EntryUrl(null)); } [Test] public void EntryUrl_WithEntryHavingPostTypeOfNone_ThrowsArgumentException() { //arrange var httpContext = new Mock<HttpContextBase>(); var requestContext = new RequestContext(httpContext.Object, new RouteData()); var helper = new UrlHelper(requestContext, new RouteCollection()); //act UnitTestHelper.AssertThrows<ArgumentException>(() => helper.EntryUrl(new Entry(PostType.None))); } [Test] public void FeedbackUrl_WithEntryHavingEntryName_RendersVirtualPathWithFeedbackIdInFragment() { //arrange UrlHelper helper = SetupUrlHelper("/"); DateTime dateCreated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var comment = new FeedbackItem(FeedbackType.Comment) { Id = 321, Entry = new Entry(PostType.BlogPost) { Id = 123, DateCreated = dateCreated, DateSyndicated = dateCreated, EntryName = "post-slug" } }; //act string url = helper.FeedbackUrl(comment); //assert Assert.AreEqual("/archive/2008/01/23/post-slug.aspx#321", url); } [Test] public void FeedbackUrl_WithEntryHavingNoEntryName_RendersVirtualPathWithFeedbackIdInFragment() { //arrange UrlHelper helper = SetupUrlHelper("/"); DateTime dateSyndicated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var comment = new FeedbackItem(FeedbackType.Comment) { Id = 321, EntryId = 1234, ParentDateSyndicated = dateSyndicated }; //act string url = helper.FeedbackUrl(comment); //assert Assert.AreEqual("/archive/2008/01/23/1234.aspx#321", url); } [Test] public void FeedbackUrl_WithContactPageFeedback_ReturnsNullUrl() { //arrange UrlHelper helper = SetupUrlHelper("/"); var comment = new FeedbackItem(FeedbackType.ContactPage) { Id = 321, Entry = new Entry(PostType.BlogPost) }; //act string url = helper.FeedbackUrl(comment); //assert Assert.IsNull(url); } [Test] public void FeedbackUrl_WithNullEntry_ReturnsNullUrl() { //arrange UrlHelper helper = SetupUrlHelper("/"); var comment = new FeedbackItem(FeedbackType.ContactPage) { Id = 321, Entry = null }; //act string url = helper.FeedbackUrl(comment); //assert Assert.IsNull(url); } [Test] public void FeedbackUrl_WithEntryIdEqualToIntMinValue_ReturnsNull() { //arrange UrlHelper helper = SetupUrlHelper("/"); DateTime dateCreated = DateTime.ParseExact("2008/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); var comment = new FeedbackItem(FeedbackType.Comment) { Id = 123, Entry = new Entry(PostType.BlogPost) { Id = NullValue.NullInt32, DateCreated = dateCreated, EntryName = "post-slug" } }; //act string url = helper.FeedbackUrl(comment); //assert Assert.IsNull(url); } [Test] public void FeedbackUrl_WithNullFeedback_ThrowsArgumentNullException() { //arrange UrlHelper helper = SetupUrlHelper("/App"); //act, assert UnitTestHelper.AssertThrowsArgumentNullException(() => helper.FeedbackUrl(null)); } [Test] public void IdenticonUrl_WithAppPathWithoutSubfolder_ReturnsRootedUrl() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); //act string url = helper.IdenticonUrl(123); //assert Assert.AreEqual("/Subtext.Web/images/services/IdenticonHandler.ashx?code=123", url); } [Test] public void IdenticonUrl_WithEmptyAppPathWithoutSubfolder_ReturnsRootedUrl() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.IdenticonUrl(123); //assert Assert.AreEqual("/images/services/IdenticonHandler.ashx?code=123", url); } [Test] public void IdenticonUrl_WithEmptyPathWithSubfolder_IgnoresSubfolderInUrl() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "foobar"); UrlHelper helper = SetupUrlHelper("/", routeData); //act string url = helper.IdenticonUrl(123); //assert Assert.AreEqual("/images/services/IdenticonHandler.ashx?code=123", url); } [Test] public void ImageUrl_WithoutBlogWithAppPathWithoutSubfolderAndImage_ReturnsRootedImageUrl() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); //act string url = helper.ImageUrl("random.gif"); //assert Assert.AreEqual("/Subtext.Web/images/random.gif", url); } [Test] public void ImageUrl_WithoutBlogWithEmptyAppPathWithoutSubfolderAndImage_ReturnsRootedImageUrl() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.ImageUrl("random.gif"); //assert Assert.AreEqual("/images/random.gif", url); } [Test] public void ImageUrl_WithoutBlogWithSubfolderAndImage_IgnoresSubfolderInUrl() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "foobar"); UrlHelper helper = SetupUrlHelper("/", routeData); //act string url = helper.ImageUrl("random.gif"); //assert Assert.AreEqual("/images/random.gif", url); } [Test] public void ImageUrl_WithBlogWithAppPathWithoutSubfolderAndImage_ReturnsUrlForImageUploadDirectory() { //arrange var blog = new Blog {Host = "localhost", Subfolder = "sub"}; UrlHelper helper = SetupUrlHelper("/Subtext.Web"); //act string url = helper.ImageUrl(blog, "random.gif"); //assert Assert.AreEqual("/Subtext.Web/images/localhost/Subtext_Web/sub/random.gif", url); } [Test] public void ImageUrl_WithBlogWithEmptyAppPathWithoutSubfolderAndImage_ReturnsUrlForImageUploadDirectory() { //arrange var blog = new Blog { Host = "localhost", Subfolder = "" }; UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.ImageUrl(blog, "random.gif"); //assert Assert.AreEqual("/images/localhost/random.gif", url); } [Test] public void ImageUrl_WithBlogWithSubfolderAndImage_IgnoresSubfolderInUrl() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "foobar"); UrlHelper helper = SetupUrlHelper("/", routeData); //act string url = helper.ImageUrl("random.gif"); //assert Assert.AreEqual("/images/random.gif", url); } [Test] public void GalleryUrl_WithId_ReturnsGalleryUrlWithId() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.GalleryUrl(1234); //assert Assert.AreEqual("/gallery/1234.aspx", url); } [Test] public void GalleryUrl_WithImageAndBlogWithSubfolder_ReturnsGalleryUrlWithSubfolder() { //arrange UrlHelper helper = SetupUrlHelper("/"); var image = new Image {CategoryID = 1234, Blog = new Blog {Subfolder = "subfolder"}}; //act string url = helper.GalleryUrl(image); //assert Assert.AreEqual("/subfolder/gallery/1234.aspx", url); } [Test] public void GalleryImageUrl_WithNullImage_ThrowsArgumentNullException() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act, assert UnitTestHelper.AssertThrowsArgumentNullException(() => helper.GalleryImagePageUrl(null)); } [Test] public void GalleryImageUrl_WithId_ReturnsGalleryUrlWithId() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.GalleryImagePageUrl(new Image {ImageID = 1234, Blog = new Blog()}); //assert Assert.AreEqual("/gallery/image/1234.aspx", url); } [Test] public void GalleryImageUrl_WithImageInBlogWithSubfolder_ReturnsGalleryUrlWithId() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.GalleryImagePageUrl(new Image {ImageID = 1234, Blog = new Blog {Subfolder = "subfolder"}}); //assert Assert.AreEqual("/subfolder/gallery/image/1234.aspx", url); } [Test] public void GalleryImageUrl_WithImageHavingUrlAndFileName_ReturnsUrlToImage() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); var image = new Image {Url = "~/images/localhost/blog1/1234/", FileName = "close.gif"}; //act string url = helper.GalleryImageUrl(image, image.OriginalFile); //assert Assert.AreEqual("/Subtext.Web/images/localhost/blog1/1234/o_close.gif", url); } [Test] public void GalleryImageUrl_WithBlogHavingSubfolderAndVirtualPathAndImageHavingNullUrlAndFileName_ReturnsUrlToImage() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); var blog = new Blog {Host = "localhost", Subfolder = "blog1"}; var image = new Image {Blog = blog, Url = null, FileName = "open.gif", CategoryID = 1234}; //act string url = helper.GalleryImageUrl(image, image.OriginalFile); //assert Assert.AreEqual("/Subtext.Web/images/localhost/Subtext_Web/blog1/1234/o_open.gif", url); } [Test] public void GalleryImageUrl_WithBlogHavingSubfolderAndImageHavingNullUrlAndFileName_ReturnsUrlToImage() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "localhost", Subfolder = "blog1"}; var image = new Image {Blog = blog, Url = null, FileName = "open.gif", CategoryID = 1234}; //act string url = helper.GalleryImageUrl(image, image.OriginalFile); //assert Assert.AreEqual("/images/localhost/blog1/1234/o_open.gif", url); } [Test] public void GalleryImageUrl_WithBlogHavingNoSubfolderAndImageHavingNullUrlAndFileName_ReturnsUrlToImage() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "localhost", Subfolder = ""}; var image = new Image {Blog = blog, Url = null, FileName = "open.gif", CategoryID = 1234}; //act string url = helper.GalleryImageUrl(image, image.OriginalFile); //assert Assert.AreEqual("/images/localhost/1234/o_open.gif", url); } [Test] public void GalleryImageUrl_WithAppPathWithSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); var blog = new Blog {Host = "localhost", Subfolder = "blog1"}; var image = new Image {CategoryID = 1234, FileName = "close.gif", Blog = blog}; //act string url = helper.GalleryImageUrl(image); //assert Assert.AreEqual("/Subtext.Web/images/localhost/Subtext_Web/blog1/1234/o_close.gif", url); } [Test] public void GalleryImageUrl_WithoutAppPathWithSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "localhost", Subfolder = "blog1"}; var image = new Image {CategoryID = 1234, FileName = "close.gif", Blog = blog}; //act string url = helper.GalleryImageUrl(image); //assert Assert.AreEqual("/images/localhost/blog1/1234/o_close.gif", url); } [Test] public void GalleryImageUrl_WithAppPathWithoutSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); var blog = new Blog {Host = "localhost", Subfolder = ""}; var image = new Image {CategoryID = 1234, FileName = "close.gif", Blog = blog}; //act string url = helper.GalleryImageUrl(image); //assert Assert.AreEqual("/Subtext.Web/images/localhost/Subtext_Web/1234/o_close.gif", url); } [Test] public void GalleryImageUrl_WithoutAppPathWithoutSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "localhost", Subfolder = ""}; var image = new Image {CategoryID = 1234, FileName = "close.gif", Blog = blog}; //act string url = helper.GalleryImageUrl(image); //assert Assert.AreEqual("/images/localhost/1234/o_close.gif", url); } [Test] public void ImageGalleryDirectoryUrl_WithAppPathWithSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); var blog = new Blog {Host = "localhost", Subfolder = "blog1"}; //act string url = helper.ImageGalleryDirectoryUrl(blog, 1234); //assert Assert.AreEqual("/Subtext.Web/images/localhost/Subtext_Web/blog1/1234/", url); } [Test] public void ImageGalleryDirectoryUrl_WithoutAppPathWithSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "localhost", Subfolder = "blog1"}; //act string url = helper.ImageGalleryDirectoryUrl(blog, 1234); //assert Assert.AreEqual("/images/localhost/blog1/1234/", url); } [Test] public void ImageGalleryDirectoryUrl_WithAppPathWithoutSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); var blog = new Blog {Host = "localhost", Subfolder = ""}; //act string url = helper.ImageGalleryDirectoryUrl(blog, 1234); //assert Assert.AreEqual("/Subtext.Web/images/localhost/Subtext_Web/1234/", url); } [Test] public void ImageGalleryDirectoryUrl_WithoutAppPathWithoutSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "localhost", Subfolder = ""}; //act string url = helper.ImageGalleryDirectoryUrl(blog, 1234); //assert Assert.AreEqual("/images/localhost/1234/", url); } [Test] public void ImageDirectoryUrl_WithAppPathWithSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); var blog = new Blog {Host = "localhost", Subfolder = "blog1"}; //act string url = helper.ImageDirectoryUrl(blog); //assert Assert.AreEqual("/Subtext.Web/images/localhost/Subtext_Web/blog1/", url); } [Test] public void ImageDirectoryUrl_WithoutAppPathWithSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "localhost", Subfolder = "blog1"}; //act string url = helper.ImageDirectoryUrl(blog); //assert Assert.AreEqual("/images/localhost/blog1/", url); } [Test] public void ImageDirectoryUrl_WithAppPathWithoutSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); var blog = new Blog {Host = "localhost", Subfolder = ""}; //act string url = helper.ImageDirectoryUrl(blog); //assert Assert.AreEqual("/Subtext.Web/images/localhost/Subtext_Web/", url); } [Test] public void ImageDirectoryUrl_WithoutAppPathWithoutSubfolderAndImage_ReturnsUrlToImageFile() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "localhost", Subfolder = ""}; //act string url = helper.ImageDirectoryUrl(blog); //assert Assert.AreEqual("/images/localhost/", url); } [Test] public void AggBugUrl_WithId_ReturnsAggBugUrlWithId() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.AggBugUrl(1234); //assert Assert.AreEqual("/aggbug/1234.aspx", url); } [Test] public void BlogUrl_WithoutSubfolder_ReturnsVirtualPathToBlog() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.BlogUrl(); //assert Assert.AreEqual("/default.aspx", url); } [Test] public void BlogUrl_WithSubfolder_ReturnsVirtualPathToBlogWithSubfolder() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "subfolder"); UrlHelper helper = SetupUrlHelper("/", routeData); //act string url = helper.BlogUrl(); //assert Assert.AreEqual("/subfolder/default.aspx", url); } [Test] public void BlogUrlWithExplicitBlogNotHavingSubfolderAndVirtualPath_WithoutSubfolderInRouteData_ReturnsSubfolder() { //arrange var routeData = new RouteData(); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.BlogUrl(new Blog { Subfolder = null }); //assert Assert.AreEqual("/Subtext.Web/default.aspx", url); } [Test] public void BlogUrlWithExplicitBlogHavingSubfolderAndVirtualPath_WithoutSubfolderInRouteData_ReturnsSubfolder() { //arrange var routeData = new RouteData(); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.BlogUrl(new Blog { Subfolder = "subfolder" }); //assert Assert.AreEqual("/Subtext.Web/subfolder/default.aspx", url); } [Test] public void BlogUrlWithExplicitBlogHavingSubfolder_WithoutSubfolderInRouteData_ReturnsSubfolder() { //arrange var routeData = new RouteData(); UrlHelper helper = SetupUrlHelper("/", routeData); //act string url = helper.BlogUrl(new Blog {Subfolder = "subfolder"}); //assert Assert.AreEqual("/subfolder/default.aspx", url); } [Test] public void BlogUrl_WithSubfolderAndAppPath_ReturnsSubfolder() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "subfolder"); UrlHelper helper = SetupUrlHelper("/App", routeData); //act string url = helper.BlogUrl(); //assert Assert.AreEqual("/App/subfolder/default.aspx", url); } [Test] public void CategoryUrl_ReturnsURlWithCategoryId() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.CategoryUrl(new LinkCategory {Id = 1234}); //assert Assert.AreEqual("/category/1234.aspx", url); } [Test] public void CategoryRssUrl_ReturnsURlWithCategoryIdInQueryString() { UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.CategoryRssUrl(new LinkCategory {Id = 1234}); //assert Assert.AreEqual("/rss.aspx?catId=1234", url); } [Test] public void AdminUrl_WithoutSubfolder_ReturnsCorrectUrl() { UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.AdminUrl("Feedback.aspx", new {status = 2}); //assert Assert.AreEqual("/admin/Feedback.aspx?status=2", url); } [Test] public void AdminUrl_WithSubfolderAndApplicationPath_ReturnsCorrectUrl() { var routeData = new RouteData(); routeData.Values.Add("subfolder", "subfolder"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.AdminUrl("Feedback.aspx", new {status = 2}); //assert Assert.AreEqual("/Subtext.Web/subfolder/admin/Feedback.aspx?status=2", url); } [Test] public void DayUrl_WithDate_ReturnsUrlWithDateInIt() { //arrange UrlHelper helper = SetupUrlHelper("/"); //Make sure date isn't midnight. DateTime dateTime = DateTime.ParseExact("2009/01/23", "yyyy/MM/dd", CultureInfo.InvariantCulture); dateTime.AddMinutes(231); //act string url = helper.DayUrl(dateTime); //assert Assert.AreEqual("/archive/2009/01/23.aspx", url); } [Test] public void RssProxyUrl_WithBlogHavingFeedBurnerName_ReturnsFeedburnerUrl() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {RssProxyUrl = "test"}; //act Uri url = helper.RssProxyUrl(blog); //assert Assert.AreEqual("http://feedproxy.google.com/test", url.ToString()); } [Test] public void RssProxyUrl_WithBlogHavingSyndicationProviderUrl_ReturnsFullUrl() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {RssProxyUrl = "http://feeds.example.com/"}; //act Uri url = helper.RssProxyUrl(blog); //assert Assert.AreEqual("http://feeds.example.com/", url.ToString()); } [Test] public void RssUrl_WithoutRssProxy_ReturnsRssUri() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "example.com"}; //act Uri url = helper.RssUrl(blog); //assert Assert.AreEqual("http://example.com/rss.aspx", url.ToString()); } [Test] public void RssUrl_ForBlogWithSubfolderWithoutRssProxy_ReturnsRssUri() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); var blog = new Blog { Host = "example.com", Subfolder = "blog"}; //act Uri url = helper.RssUrl(blog); //assert Assert.AreEqual("http://example.com/Subtext.Web/blog/rss.aspx", url.ToString()); } [Test] public void RssUrl_WithRssProxy_ReturnsProxyUrl() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "example.com", RssProxyUrl = "http://feeds.example.com/feed"}; //act Uri url = helper.RssUrl(blog); //assert Assert.AreEqual("http://feeds.example.com/feed", url.ToString()); } [Test] public void AtomUrl_WithoutRssProxy_ReturnsRssUri() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "example.com"}; //act Uri url = helper.AtomUrl(blog); //assert Assert.AreEqual("http://example.com/atom.aspx", url.ToString()); } [Test] public void AtomUrl_WithRssProxy_ReturnsRssUri() { //arrange UrlHelper helper = SetupUrlHelper("/"); var blog = new Blog {Host = "example.com", RssProxyUrl = "http://atom.example.com/atom"}; //act Uri url = helper.AtomUrl(blog); //assert Assert.AreEqual("http://atom.example.com/atom", url.ToString()); } [Test] public void AdminUrl_WithPage_RendersAdminUrlToPage() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act string url = helper.AdminUrl("log.aspx"); //assert Assert.AreEqual("/admin/log.aspx", url); } [Test] public void AdminUrl_WithBlogHavingSubfolder_RendersAdminUrlToPage() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/", routeData); //act string url = helper.AdminUrl("log.aspx"); //assert Assert.AreEqual("/sub/admin/log.aspx", url); } [Test] public void AdminUrl_WithBlogHavingSubfolderAndVirtualPath_RendersAdminUrlToPage() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.AdminUrl("log.aspx"); //assert Assert.AreEqual("/Subtext.Web/sub/admin/log.aspx", url); } [Test] public void AdminRssUrl_WithFeednameAndSubfolderAndApp_ReturnsAdminRssUrl() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act VirtualPath url = helper.AdminRssUrl("Referrers"); //assert Assert.AreEqual("/Subtext.Web/sub/admin/ReferrersRss.axd", url.ToString()); } [Test] public void LoginUrl_WithSubfolderAndApp_ReturnsLoginUrlInSubfolder() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.LoginUrl(); //assert Assert.AreEqual("/Subtext.Web/sub/login.aspx", url); } [Test] public void LoginUrl_WithSubfolderAndAppAndReturnUrl_ReturnsLoginUrlWithReturnUrlInQueryString() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.LoginUrl("/Subtext.Web/AdminPage.aspx").ToString().ToLowerInvariant(); //assert Assert.AreEqual(("/Subtext.Web/sub/login.aspx?ReturnUrl=" + HttpUtility.UrlEncode("/Subtext.Web/AdminPage.aspx")).ToLowerInvariant(), url); } [Test] public void LogoutUrl_WithSubfolderAndApp_ReturnsLoginUrlInSubfolder() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.LogoutUrl(); //assert Assert.AreEqual("/Subtext.Web/sub/account/logout.ashx", url); } [Test] public void LogoutUrl_WithoutSubfolderAndApp_ReturnsLoginUrlInSubfolder() { //arrange var routeData = new RouteData(); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.LogoutUrl(); //assert Assert.AreEqual("/Subtext.Web/account/logout.ashx", url); } [Test] public void ArchivesUrl_WithSubfolderAndApp_ReturnsUrlWithAppAndSubfolder() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.ArchivesUrl(); //assert Assert.AreEqual("/Subtext.Web/sub/archives.aspx", url); } [Test] public void ContactFormUrl_WithSubfolderAndApp_ReturnsUrlWithAppAndSubfolder() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.ContactFormUrl(); //assert Assert.AreEqual("/Subtext.Web/sub/contact.aspx", url); } [Test] public void WlwManifestUrl_WithoutSubfolderWithoutApp_ReturnsPerBlogManifestUrl() { //arrange UrlHelper helper = SetupUrlHelper("/"); //act string manifestUrl = helper.WlwManifestUrl(); //assert Assert.AreEqual("/wlwmanifest.xml.ashx", manifestUrl); } [Test] public void WlwManifestUrl_WithoutSubfolderAndApp_ReturnsPerBlogManifestUrl() { //arrange UrlHelper helper = SetupUrlHelper("/Subtext.Web"); //act string manifestUrl = helper.WlwManifestUrl(); //assert Assert.AreEqual("/Subtext.Web/wlwmanifest.xml.ashx", manifestUrl); } [Test] public void WlwManifestUrl_WithSubfolderAndApp_ReturnsPerBlogManifestUrl() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string manifestUrl = helper.WlwManifestUrl(); //assert Assert.AreEqual("/Subtext.Web/sub/wlwmanifest.xml.ashx", manifestUrl); } [Test] public void MetaWeblogApiUrl_WithSubfolderAndApp_ReturnsFullyQualifiedUrl() { //arrange var blog = new Blog {Host = "example.com", Subfolder = "sub"}; var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act Uri url = helper.MetaWeblogApiUrl(blog); //assert Assert.AreEqual("http://example.com/Subtext.Web/sub/services/metablogapi.aspx", url.ToString()); } [Test] public void RsdUrl_WithSubfolderAndApp_ReturnsFullyQualifiedUrl() { //arrange var blog = new Blog {Host = "example.com", Subfolder = "sub"}; var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act Uri url = helper.RsdUrl(blog); //assert Assert.AreEqual("http://example.com/Subtext.Web/sub/rsd.xml.ashx", url.ToString()); } [Test] public void CustomCssUrl_WithSubfolderAndApp_ReturnsFullyQualifiedUrl() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act VirtualPath url = helper.CustomCssUrl(); //assert Assert.AreEqual("/Subtext.Web/sub/customcss.aspx", url.ToString()); } [Test] public void TagUrl_WithSubfolderAndApp_ReturnsTagUrl() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act VirtualPath url = helper.TagUrl("tagName"); //assert Assert.AreEqual("/Subtext.Web/sub/tags/tagName/default.aspx", url.ToString()); } [Test] public void TagUrl_CorrectlyEncodesPoundCharacter() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act VirtualPath url = helper.TagUrl("C#"); //assert Assert.AreEqual("/Subtext.Web/sub/tags/C%23/default.aspx", url.ToString()); } [Test] public void TagCloudUrl_WithSubfolderAndApp_ReturnsTagCloudUrl() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act VirtualPath url = helper.TagCloudUrl(); //assert Assert.AreEqual("/Subtext.Web/sub/tags/default.aspx", url.ToString()); } [Test] public void AppRootUrl_WithSubfolder_ReturnsAppRootAndIgnoresSubfolder() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/", routeData); //act VirtualPath url = helper.AppRoot(); //assert Assert.AreEqual("/", url.ToString()); } [Test] public void AppRootUrl_WithSubfolderAndApp_ReturnsAppRootAndIgnoresSubfolder() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act VirtualPath url = helper.AppRoot(); //assert Assert.AreEqual("/Subtext.Web/", url.ToString()); } [Test] public void EditIcon_WithSubfolderAndApp_ReturnsAppRootAndIgnoresSubfolder() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act VirtualPath url = helper.EditIconUrl(); //assert Assert.AreEqual("/Subtext.Web/images/icons/edit.gif", url.ToString()); } [Test] public void HostAdminUrl_WithBlogHavingSubfolder_RendersUrlToHostAdmin() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/", routeData); //act string url = helper.HostAdminUrl("default.aspx"); //assert Assert.AreEqual("/hostadmin/default.aspx", url); } [Test] public void HostAdminUrl_WithAppPathAndBlogHavingSubfolder_RendersUrlToHostAdmin() { //arrange var routeData = new RouteData(); routeData.Values.Add("subfolder", "sub"); UrlHelper helper = SetupUrlHelper("/Subtext.Web", routeData); //act string url = helper.HostAdminUrl("default.aspx"); //assert Assert.AreEqual("/Subtext.Web/hostadmin/default.aspx", url); } private static UrlHelper SetupUrlHelper(string appPath) { return SetupUrlHelper(appPath, new RouteData()); } private static UrlHelper SetupUrlHelper(string appPath, RouteData routeData) { return UnitTestHelper.SetupUrlHelper(appPath, routeData); } [RowTest] [Row("http://www.google.com/search?q=asp.net+mvc&ie=utf-8&oe=utf-8&aq=t&rls=org.mozilla:en-US:official&client=firefox-a", "asp.net mvc")] [Row("http://it.search.yahoo.com/search;_ylt=A03uv8bsRjNLZ0ABugAbDQx.?p=asp.net+mvc&fr2=sb-top&fr=yfp-t-709&rd=r1&sao=1", "asp.net mvc")] [Row("http://www.google.com/#hl=en&source=hp&q=asp.net+mvc&btnG=Google+Search&aq=0p&aqi=g-p3g7&oq=as&fp=cbc2f75bf9d43a8f", "asp.net mvc")] [Row("http://www.bing.com/search?q=asp.net+mvc&go=&form=QBLH&filt=all", "asp.net mvc")] [Row("http://www.google.com/search?hl=en&safe=off&client=firefox-a&rls=org.mozilla%3Aen-US%3Aofficial&hs=MUl&q=%22asp.net+mvc%22&aq=f&oq=&aqi=g-p3g7", "\"asp.net mvc\"")] [Row("http://codeclimber.net.nz/search.aspx?q=%22asp.net%20mvc%22", "")] [Row("http://www.google.it/search?rlz=1C1GGLS_enIT354IT354&sourceid=chrome&ie=UTF-8&q=site:http://haacked.com/+water+birth", "water birth")] [Row("http://www.google.it/search?rlz=1C1GGLS_enIT354IT354&sourceid=chrome&ie=UTF-8&q=site:https://haacked.com/+water+birth", "water birth")] [Row("http://www.google.it/search?rlz=1C1GGLS_enIT354IT354&sourceid=chrome&ie=UTF-8&q=water+birth+site:https://haacked.com/", "water birth")] public void UrlHelper_ExtractKeywordsFromReferrer_ParsesCorrectly(string referralUrl, string expectedResult) { Uri referrer = new Uri(referralUrl); Uri currentPath = new Uri("http://codeclimber.net.nz/archive/2009/05/20/book-review-asp.net-mvc-1.0-quickly.aspx"); string query = UrlHelper.ExtractKeywordsFromReferrer(referrer, currentPath); Assert.AreEqual(expectedResult, query); } } }
using Lucene.Net.Analysis.Tokenattributes; using System; using System.Collections.Generic; using System.Text; using Lucene.Net.Documents; namespace Lucene.Net.Search { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using Lucene.Net.Analysis; using NUnit.Framework; using System.IO; using AtomicReader = Lucene.Net.Index.AtomicReader; using BytesRef = Lucene.Net.Util.BytesRef; using Directory = Lucene.Net.Store.Directory; using DocsAndPositionsEnum = Lucene.Net.Index.DocsAndPositionsEnum; using Document = Documents.Document; using Field = Field; using IndexReader = Lucene.Net.Index.IndexReader; using LuceneTestCase = Lucene.Net.Util.LuceneTestCase; using MultiFields = Lucene.Net.Index.MultiFields; using MultiSpansWrapper = Lucene.Net.Search.Spans.MultiSpansWrapper; using PayloadSpanUtil = Lucene.Net.Search.Payloads.PayloadSpanUtil; using RandomIndexWriter = Lucene.Net.Index.RandomIndexWriter; using SlowCompositeReaderWrapper = Lucene.Net.Index.SlowCompositeReaderWrapper; using SpanNearQuery = Lucene.Net.Search.Spans.SpanNearQuery; using SpanQuery = Lucene.Net.Search.Spans.SpanQuery; using SpanTermQuery = Lucene.Net.Search.Spans.SpanTermQuery; using Term = Lucene.Net.Index.Term; using TextField = TextField; /// <summary> /// Term position unit test. /// /// /// </summary> [TestFixture] public class TestPositionIncrement : LuceneTestCase { internal const bool VERBOSE = false; [Test] public virtual void TestSetPosition() { Analyzer analyzer = new AnalyzerAnonymousInnerClassHelper(this); Directory store = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), store, analyzer); Document d = new Document(); d.Add(NewTextField("field", "bogus", Field.Store.YES)); writer.AddDocument(d); IndexReader reader = writer.Reader; writer.Dispose(); IndexSearcher searcher = NewSearcher(reader); DocsAndPositionsEnum pos = MultiFields.GetTermPositionsEnum(searcher.IndexReader, MultiFields.GetLiveDocs(searcher.IndexReader), "field", new BytesRef("1")); pos.NextDoc(); // first token should be at position 0 Assert.AreEqual(0, pos.NextPosition()); pos = MultiFields.GetTermPositionsEnum(searcher.IndexReader, MultiFields.GetLiveDocs(searcher.IndexReader), "field", new BytesRef("2")); pos.NextDoc(); // second token should be at position 2 Assert.AreEqual(2, pos.NextPosition()); PhraseQuery q; ScoreDoc[] hits; q = new PhraseQuery(); q.Add(new Term("field", "1")); q.Add(new Term("field", "2")); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // same as previous, just specify positions explicitely. q = new PhraseQuery(); q.Add(new Term("field", "1"), 0); q.Add(new Term("field", "2"), 1); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // specifying correct positions should find the phrase. q = new PhraseQuery(); q.Add(new Term("field", "1"), 0); q.Add(new Term("field", "2"), 2); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); q = new PhraseQuery(); q.Add(new Term("field", "2")); q.Add(new Term("field", "3")); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); q = new PhraseQuery(); q.Add(new Term("field", "3")); q.Add(new Term("field", "4")); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // phrase query would find it when correct positions are specified. q = new PhraseQuery(); q.Add(new Term("field", "3"), 0); q.Add(new Term("field", "4"), 0); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); // phrase query should fail for non existing searched term // even if there exist another searched terms in the same searched position. q = new PhraseQuery(); q.Add(new Term("field", "3"), 0); q.Add(new Term("field", "9"), 0); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); // multi-phrase query should succed for non existing searched term // because there exist another searched terms in the same searched position. MultiPhraseQuery mq = new MultiPhraseQuery(); mq.Add(new Term[] { new Term("field", "3"), new Term("field", "9") }, 0); hits = searcher.Search(mq, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); q = new PhraseQuery(); q.Add(new Term("field", "2")); q.Add(new Term("field", "4")); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); q = new PhraseQuery(); q.Add(new Term("field", "3")); q.Add(new Term("field", "5")); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); q = new PhraseQuery(); q.Add(new Term("field", "4")); q.Add(new Term("field", "5")); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(1, hits.Length); q = new PhraseQuery(); q.Add(new Term("field", "2")); q.Add(new Term("field", "5")); hits = searcher.Search(q, null, 1000).ScoreDocs; Assert.AreEqual(0, hits.Length); reader.Dispose(); store.Dispose(); } private class AnalyzerAnonymousInnerClassHelper : Analyzer { private readonly TestPositionIncrement OuterInstance; public AnalyzerAnonymousInnerClassHelper(TestPositionIncrement outerInstance) { this.OuterInstance = outerInstance; } public override TokenStreamComponents CreateComponents(string fieldName, TextReader reader) { return new TokenStreamComponents(new TokenizerAnonymousInnerClassHelper(this, reader)); } private class TokenizerAnonymousInnerClassHelper : Tokenizer { private readonly AnalyzerAnonymousInnerClassHelper OuterInstance; public TokenizerAnonymousInnerClassHelper(AnalyzerAnonymousInnerClassHelper outerInstance, TextReader reader) : base(reader) { this.OuterInstance = outerInstance; TOKENS = new string[] { "1", "2", "3", "4", "5" }; INCREMENTS = new int[] { 1, 2, 1, 0, 1 }; i = 0; posIncrAtt = AddAttribute<IPositionIncrementAttribute>(); termAtt = AddAttribute<ICharTermAttribute>(); offsetAtt = AddAttribute<IOffsetAttribute>(); } // TODO: use CannedTokenStream private readonly string[] TOKENS; private readonly int[] INCREMENTS; private int i; internal IPositionIncrementAttribute posIncrAtt; internal ICharTermAttribute termAtt; internal IOffsetAttribute offsetAtt; public override sealed bool IncrementToken() { if (i == TOKENS.Length) { return false; } ClearAttributes(); termAtt.Append(TOKENS[i]); offsetAtt.SetOffset(i, i); posIncrAtt.PositionIncrement = INCREMENTS[i]; i++; return true; } public override void Reset() { base.Reset(); this.i = 0; } } } [Test] public virtual void TestPayloadsPos0() { Directory dir = NewDirectory(); RandomIndexWriter writer = new RandomIndexWriter(Random(), dir, new MockPayloadAnalyzer()); Document doc = new Document(); doc.Add(new TextField("content", new StringReader("a a b c d e a f g h i j a b k k"))); writer.AddDocument(doc); IndexReader readerFromWriter = writer.Reader; AtomicReader r = SlowCompositeReaderWrapper.Wrap(readerFromWriter); DocsAndPositionsEnum tp = r.TermPositionsEnum(new Term("content", "a")); int count = 0; Assert.IsTrue(tp.NextDoc() != DocIdSetIterator.NO_MORE_DOCS); // "a" occurs 4 times Assert.AreEqual(4, tp.Freq()); Assert.AreEqual(0, tp.NextPosition()); Assert.AreEqual(1, tp.NextPosition()); Assert.AreEqual(3, tp.NextPosition()); Assert.AreEqual(6, tp.NextPosition()); // only one doc has "a" Assert.AreEqual(DocIdSetIterator.NO_MORE_DOCS, tp.NextDoc()); IndexSearcher @is = NewSearcher(readerFromWriter); SpanTermQuery stq1 = new SpanTermQuery(new Term("content", "a")); SpanTermQuery stq2 = new SpanTermQuery(new Term("content", "k")); SpanQuery[] sqs = new SpanQuery[] { stq1, stq2 }; SpanNearQuery snq = new SpanNearQuery(sqs, 30, false); count = 0; bool sawZero = false; if (VERBOSE) { Console.WriteLine("\ngetPayloadSpans test"); } Search.Spans.Spans pspans = MultiSpansWrapper.Wrap(@is.TopReaderContext, snq); while (pspans.Next()) { if (VERBOSE) { Console.WriteLine("doc " + pspans.Doc() + ": span " + pspans.Start() + " to " + pspans.End()); } var payloads = pspans.Payload; sawZero |= pspans.Start() == 0; foreach (var bytes in payloads) { count++; if (VERBOSE) { Console.WriteLine(" payload: " + Encoding.UTF8.GetString((byte[])(Array)bytes)); } } } Assert.IsTrue(sawZero); Assert.AreEqual(5, count); // System.out.println("\ngetSpans test"); Search.Spans.Spans spans = MultiSpansWrapper.Wrap(@is.TopReaderContext, snq); count = 0; sawZero = false; while (spans.Next()) { count++; sawZero |= spans.Start() == 0; // System.out.println(spans.Doc() + " - " + spans.Start() + " - " + // spans.End()); } Assert.AreEqual(4, count); Assert.IsTrue(sawZero); // System.out.println("\nPayloadSpanUtil test"); sawZero = false; PayloadSpanUtil psu = new PayloadSpanUtil(@is.TopReaderContext); var pls = psu.GetPayloadsForQuery(snq); count = pls.Count; foreach (var bytes in pls) { string s = Encoding.UTF8.GetString(bytes); //System.out.println(s); sawZero |= s.Equals("pos: 0"); } Assert.AreEqual(5, count); Assert.IsTrue(sawZero); writer.Dispose(); @is.IndexReader.Dispose(); dir.Dispose(); } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using ContosoUniversity.Models.SchoolViewModels; using ContosoUniversity.Data.Entities; using ContosoUniversity.Common.Interfaces; using ContosoUniversity.Common; using ContosoUniversity.Data.DbContexts; using Microsoft.AspNetCore.Authorization; namespace ContosoUniversity.Web.Controllers { public class InstructorsController : Controller { private readonly IRepository<Department> _departmentRepo; private readonly IRepository<Instructor> _instructorRepo; private readonly IRepository<Course> _courseRepo; private readonly IRepository<CourseAssignment> _courseAssignmentRepo; private readonly IModelBindingHelperAdaptor _modelBindingHelperAdaptor; public InstructorsController(UnitOfWork<ApplicationContext> unitOfWork, IModelBindingHelperAdaptor modelBindingHelperAdaptor) { _instructorRepo = unitOfWork.InstructorRepository; _departmentRepo = unitOfWork.DepartmentRepository; _courseRepo = unitOfWork.CourseRepository; _courseAssignmentRepo = unitOfWork.CourseAssignmentRepository; _modelBindingHelperAdaptor = modelBindingHelperAdaptor; } public async Task<IActionResult> Index(int? id, int? courseID) { var viewModel = new InstructorIndexData() { }; viewModel.Instructors = await _instructorRepo.GetAll() .Include(i => i.OfficeAssignment) .Include(i => i.CourseAssignments) .ThenInclude(i => i.Course) .ThenInclude(i => i.Enrollments) .ThenInclude(i => i.Student) .Include(i => i.CourseAssignments) .ThenInclude(i => i.Course) .ThenInclude(i => i.Department) .AsGatedNoTracking() .OrderBy(i => i.LastName) .ToListAsync(); if (id != null) { ViewData["InstructorID"] = id.Value; Instructor instructor = viewModel.Instructors.Where(i => i.ID == id.Value).Single(); viewModel.Courses = instructor.CourseAssignments.Select(s => s.Course); } if (courseID != null) { ViewData["CourseID"] = courseID.Value; viewModel.Enrollments = viewModel.Courses.Where(x => x.ID == courseID).Single().Enrollments; } return View(viewModel); } public async Task<IActionResult> Details(int? id) { if (id == null) { return NotFound(); } var instructor = await _instructorRepo.Get(id.Value).SingleOrDefaultAsync(); if (instructor == null) { return NotFound(); } return View(instructor); } public IActionResult Create() { var instructor = new Instructor() { }; instructor.CourseAssignments = new List<CourseAssignment>(); PopulateAssignedCourseData(instructor); return View(); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("FirstMidName,HireDate,LastName,OfficeAssignment")] Instructor instructor, string[] selectedCourses) { if (selectedCourses != null) { instructor.CourseAssignments = new List<CourseAssignment>(); foreach (var course in selectedCourses) { var courseToAdd = new CourseAssignment { InstructorID = instructor.ID, CourseID = int.Parse(course) }; instructor.CourseAssignments.Add(courseToAdd); } } if (ModelState.IsValid) { await _instructorRepo.AddAsync(instructor); await _instructorRepo.SaveChangesAsync(); return RedirectToAction("Index"); } PopulateAssignedCourseData(instructor); return View(instructor); } public async Task<IActionResult> Edit(int? id) { if (id == null) { return NotFound(); } var instructor = await _instructorRepo.Get(id.Value) .Include(i => i.OfficeAssignment) .Include(i => i.CourseAssignments).ThenInclude(i => i.Course) .AsGatedNoTracking() .SingleOrDefaultAsync(); if (instructor == null) { return NotFound(); } PopulateAssignedCourseData(instructor); return View(instructor); } [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Edit(int? id, string[] selectedCourses) { if (id == null) { return NotFound(); } var instructorToUpdate = await _instructorRepo.GetAll() .Include(i => i.OfficeAssignment) .Include(i => i.CourseAssignments).ThenInclude(i => i.Course) .SingleOrDefaultAsync(s => s.ID == id); if (await _modelBindingHelperAdaptor.TryUpdateModelAsync<Instructor>(this, instructorToUpdate, "", i => i.FirstMidName, i => i.LastName, i => i.HireDate, i => i.OfficeAssignment)) { if (String.IsNullOrWhiteSpace(instructorToUpdate.OfficeAssignment?.Location)) { instructorToUpdate.OfficeAssignment = null; } UpdateInstructorCourses(selectedCourses, instructorToUpdate); try { instructorToUpdate.ModifiedDate = DateTime.UtcNow; await _instructorRepo.SaveChangesAsync(); return RedirectToAction("Index"); } catch (DbUpdateException) { ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists, see your system administrator."); } } UpdateInstructorCourses(selectedCourses, instructorToUpdate); PopulateAssignedCourseData(instructorToUpdate); return View(instructorToUpdate); } [Authorize(Roles = "Administrator")] public async Task<IActionResult> Delete(int? id) { if (id == null) { return NotFound(); } var instructor = await _instructorRepo.Get(id.Value).SingleOrDefaultAsync(); if (instructor == null) { return NotFound(); } return View(instructor); } [Authorize(Roles = "Administrator")] [HttpPost, ActionName("Delete")] [ValidateAntiForgeryToken] public async Task<IActionResult> DeleteConfirmed(int id) { Instructor instructor = await _instructorRepo.GetAll() .Include(i => i.CourseAssignments) .SingleAsync(m => m.ID == id); var departments = await _departmentRepo.GetAll().Where(d => d.InstructorID == id).ToListAsync(); departments.ForEach(d => d.InstructorID = null); _instructorRepo.Delete(instructor); await _instructorRepo.SaveChangesAsync(); return RedirectToAction("Index"); } private void UpdateInstructorCourses(string[] selectedCourses, Instructor instructorToUpdate) { if (selectedCourses == null) { instructorToUpdate.CourseAssignments = new List<CourseAssignment>(); return; } var selectedCoursesHS = new HashSet<string>(selectedCourses); var instructorCourses = new HashSet<int>(instructorToUpdate.CourseAssignments.Select(c => c.Course.ID)); foreach (var course in _courseRepo.GetAll()) { if (selectedCoursesHS.Contains(course.ID.ToString())) { if (!instructorCourses.Contains(course.ID)) { instructorToUpdate.CourseAssignments.Add(new CourseAssignment { InstructorID = instructorToUpdate.ID, CourseID = course.ID }); } } else { if (instructorCourses.Contains(course.ID)) { CourseAssignment courseToRemove = instructorToUpdate.CourseAssignments.SingleOrDefault(i => i.CourseID == course.ID); _courseAssignmentRepo.Delete(courseToRemove); } } } } private void PopulateAssignedCourseData(Instructor instructor) { var allCourses = _courseRepo.GetAll(); var instructorCourses = new HashSet<int>(instructor.CourseAssignments.Select(c => c.CourseID)); var viewModel = new List<AssignedCourseData>(); foreach (var course in allCourses) { viewModel.Add(new AssignedCourseData { CourseID = course.ID, Title = course.Title, Assigned = instructorCourses.Contains(course.ID) }); } ViewData["Courses"] = viewModel; } private bool InstructorExists(int id) { return _instructorRepo.GetAll().Any(e => e.ID == id); } } }
namespace ZetaResourceEditor.UI.Translation; using DevExpress.XtraEditors; using DevExpress.XtraEditors.Controls; using ExtendedControlsLibrary; using Helper.Base; using RuntimeBusinessLogic.Helpers; using RuntimeBusinessLogic.Projects; using RuntimeBusinessLogic.Translation; using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Windows.Forms; using Zeta.VoyagerLibrary.Common; using Zeta.VoyagerLibrary.WinForms.Persistance; public partial class TranslateOptionsForm : FormBase { private Project _project; private int _initialIndex; private int _beforeIndex = -1; public TranslateOptionsForm() { InitializeComponent(); if (!DesignModeHelper.IsDesignMode) { // Positioning the multi-line text box. var delta = appIDMemoEdit.Top - appIDTextEdit.Top; appIDMemoEdit.Top = appIDTextEdit.Top; appIDMemoEdit.Height += delta; } } private class EngineHelper { public ITranslationEngine Engine { get; } public EngineHelper( ITranslationEngine engine) { Engine = engine; } public override string ToString() { return Engine.UserReadableName; } } public bool TranslationProviderChanged => engineComboBox.SelectedIndex != _initialIndex || appIDTextEdit.Text.Trim() != _initialAppID; protected override void InitiallyFillLists() { base.InitiallyFillLists(); foreach (var engine in TranslationHelper.Engines) { engineComboBox.Properties.Items.Add(new EngineHelper(engine)); } } protected override void FillItemToControls() { base.FillItemToControls(); translationDelayTextEdit.Text = _project.TranslationDelayMilliseconds.ToString(CultureInfo.InvariantCulture); checkEditContinueOnErrors.Checked = _project.TranslationContinueOnErrors; wordsToProtectMemoEdit.Text = string.Join(Environment.NewLine, _project.TranslationWordsToProtect); wordsToRemoveMemoEdit.Text = string.Join(Environment.NewLine, _project.TranslationWordsToRemove); selectEngine(_project.TranslationEngineUniqueInternalName); _initialIndex = engineComboBox.SelectedIndex; _localDic = _project.TranslationAppIDs; loadAppID(engineComboBox.SelectedIndex); _initialAppID = appIDTextEdit.Text.Trim(); } private void selectEngine(string un) { foreach (EngineHelper eh in engineComboBox.Properties.Items) { if (string.Compare(eh.Engine.UniqueInternalName, un, StringComparison.OrdinalIgnoreCase) == 0) { engineComboBox.SelectedItem = eh; return; } } // Not found, select default. foreach (EngineHelper eh in engineComboBox.Properties.Items) { if (eh.Engine.IsDefault) { engineComboBox.SelectedItem = eh; return; } } } protected override void FillControlsToItem() { base.FillControlsToItem(); _project.TranslationDelayMilliseconds = ConvertHelper.ToInt32(translationDelayTextEdit.Text.Trim()); _project.TranslationContinueOnErrors = checkEditContinueOnErrors.Checked; _project.TranslationEngineUniqueInternalName = ((EngineHelper)engineComboBox.SelectedItem).Engine.UniqueInternalName; _project.TranslationWordsToProtect = wordsToProtectMemoEdit.Text.Trim().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); _project.TranslationWordsToRemove = wordsToRemoveMemoEdit.Text.Trim().Split(new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries); saveAppID(engineComboBox.SelectedIndex); _project.TranslationAppIDs = _localDic; TranslationHelper.ResetSelectedEngine(); } public override void UpdateUI() { base.UpdateUI(); buttonOK.Enabled = ConvertHelper.IsInt32(translationDelayTextEdit.Text.Trim()) && ConvertHelper.ToInt32(translationDelayTextEdit.Text.Trim()) > 0 && ConvertHelper.ToInt32(translationDelayTextEdit.Text.Trim()) < 50000; } private void AutoTranslateOptionsForm_Load( object sender, EventArgs e) { _appIDLabelText = appIDLabel.Text; WinFormsPersistanceHelper.RestoreState(this); CenterToParent(); InitiallyFillLists(); FillItemToControls(); engineComboBox_SelectedIndexChanged(null, null); UpdateUI(); } private void AutoTranslateOptionsForm_FormClosing( object sender, FormClosingEventArgs e) { WinFormsPersistanceHelper.SaveState(this); } private void translationDelayTextEdit_EditValueChanged(object sender, EventArgs e) { UpdateUI(); } private void buttonOK_Click(object sender, EventArgs e) { FillControlsToItem(); } public void Initialize(Project project) { // The translation stuff is streamed through the project but // actually stored in the global settings. _project = project ?? Project.Empty; } private void buttonAddDefaultWordsToKeep_Click(object sender, EventArgs e) { var current = new List<string>( wordsToProtectMemoEdit.Text.Trim().Split( new[] { Environment.NewLine }, StringSplitOptions.RemoveEmptyEntries)); for (var i = 0; i < current.Count; i++) { current[i] = current[i].Trim(); } current.RemoveAll(string.IsNullOrEmpty); // -- foreach (var wtp in Project.DefaultWordsToProtect) { if (!current.Contains(wtp)) { current.Add(wtp); } } wordsToProtectMemoEdit.Text = string.Join(Environment.NewLine, current.ToArray()); } private void engineComboBox_SelectedIndexChanged(object sender, EventArgs e) { saveAppID(_beforeIndex); _beforeIndex = engineComboBox.SelectedIndex; loadAppID(engineComboBox.SelectedIndex); updateAppIDLink(); } private void updateAppIDLink() { if (engineComboBox.SelectedIndex >= 0 && engineComboBox.SelectedIndex < engineComboBox.Properties.Items.Count) { appIDLinkControl.Visible = true; } else { appIDLinkControl.Visible = false; } } private void loadAppID(int engineComboBoxIndex) { if (engineComboBoxIndex >= 0 && engineComboBoxIndex < engineComboBox.Properties.Items.Count) { var dic = _localDic; if (dic is { Count: > 0 }) { var eh = (EngineHelper)engineComboBox.Properties.Items[engineComboBoxIndex]; appIDTextEdit.Text = dic.TryGetValue(eh.Engine.UniqueInternalName, out var appID) ? appID : string.Empty; appIDMemoEdit.Text = dic.TryGetValue(eh.Engine.UniqueInternalName, out appID) ? appID : string.Empty; appIDLabel.Text = string.Format(_appIDLabelText, eh.Engine.AppID1Name); appIDTextEdit.Visible = !eh.Engine.IsAppIDMultiLine; appIDMemoEdit.Visible = eh.Engine.IsAppIDMultiLine; myHyperLinkEdit1.Visible = eh.Engine.IsJson; } } else { appIDTextEdit.Text = string.Empty; } } private void saveAppID(int engineComboBoxIndex) { if (engineComboBoxIndex >= 0 && engineComboBoxIndex < engineComboBox.Properties.Items.Count) { var eh = (EngineHelper)engineComboBox.Properties.Items[engineComboBoxIndex]; var key = eh.Engine.UniqueInternalName; var dic = _localDic; dic[key] = eh.Engine.IsAppIDMultiLine ? appIDMemoEdit.Text.Trim() : appIDTextEdit.Text.Trim(); _localDic = dic; if (eh.Engine.IsJson && !string.IsNullOrWhiteSpace(appIDMemoEdit.Text.Trim()) && !JsonHelper.IsValidJson(appIDMemoEdit.Text.Trim())) { XtraMessageBox.Show( ActiveForm, "Your entered JSON seems to be invalid. Please ensure that you enter a valid JSON document.", @"Zeta Resource Editor", MessageBoxButtons.OK, MessageBoxIcon.Warning); } } } private Dictionary<string, string> _localDic; private string _appIDLabelText; private string _initialAppID; private void appIDLinkControl_OpenLink(object sender, OpenLinkEventArgs e) { e.Handled = true; if (engineComboBox.SelectedIndex >= 0 && engineComboBox.SelectedIndex < engineComboBox.Properties.Items.Count) { var eh = (EngineHelper)engineComboBox.Properties.Items[engineComboBox.SelectedIndex]; Process.Start(eh.Engine.AppIDLink); } } private void TranslateOptionsForm_Shown(object sender, EventArgs e) { AutoTranslateForm.CheckShowNewTranslationInfos(); } private void myHyperLinkEdit1_OpenLink(object sender, OpenLinkEventArgs e) { e.Handled = true; Process.Start(@"http://zeta.li/json-validator"); } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.Win32.SafeHandles; using System.Diagnostics; using System.Runtime.InteropServices; using System.Security; using System.Threading; namespace System.IO.MemoryMappedFiles { public partial class MemoryMappedFile { /// <summary> /// Used by the 2 Create factory method groups. A null fileHandle specifies that the /// memory mapped file should not be associated with an exsiting file on disk (ie start /// out empty). /// </summary> private static readonly IntPtr INVALID_HANDLE_VALUE = new IntPtr(-1); [SecurityCritical] private static SafeMemoryMappedFileHandle CreateCore( FileStream fileStream, string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { SafeFileHandle fileHandle = fileStream != null ? fileStream.SafeFileHandle : null; Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); // split the long into two ints int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL)); int capacityHigh = unchecked((int)(capacity >> 32)); SafeMemoryMappedFileHandle handle = fileHandle != null ? Interop.mincore.CreateFileMapping(fileHandle, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName) : Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); int errorCode = Marshal.GetLastWin32Error(); if (!handle.IsInvalid) { if (errorCode == Interop.mincore.Errors.ERROR_ALREADY_EXISTS) { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } } else // handle.IsInvalid { handle.Dispose(); throw Win32Marshal.GetExceptionForWin32Error(errorCode); } return handle; } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, bool createOrOpen) { return OpenCore(mapName, inheritability, GetFileMapAccess(access), createOrOpen); } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileRights rights, bool createOrOpen) { return OpenCore(mapName, inheritability, GetFileMapAccess(rights), createOrOpen); } /// <summary> /// Used by the CreateOrOpen factory method groups. /// </summary> [SecurityCritical] private static SafeMemoryMappedFileHandle CreateOrOpenCore( string mapName, HandleInheritability inheritability, MemoryMappedFileAccess access, MemoryMappedFileOptions options, long capacity) { /// Try to open the file if it exists -- this requires a bit more work. Loop until we can /// either create or open a memory mapped file up to a timeout. CreateFileMapping may fail /// if the file exists and we have non-null security attributes, in which case we need to /// use OpenFileMapping. But, there exists a race condition because the memory mapped file /// may have closed inbetween the two calls -- hence the loop. /// /// The retry/timeout logic increases the wait time each pass through the loop and times /// out in approximately 1.4 minutes. If after retrying, a MMF handle still hasn't been opened, /// throw an InvalidOperationException. Debug.Assert(access != MemoryMappedFileAccess.Write, "Callers requesting write access shouldn't try to create a mmf"); SafeMemoryMappedFileHandle handle = null; Interop.mincore.SECURITY_ATTRIBUTES secAttrs = GetSecAttrs(inheritability); // split the long into two ints int capacityLow = unchecked((int)(capacity & 0x00000000FFFFFFFFL)); int capacityHigh = unchecked((int)(capacity >> 32)); int waitRetries = 14; //((2^13)-1)*10ms == approximately 1.4mins int waitSleep = 0; // keep looping until we've exhausted retries or break as soon we we get valid handle while (waitRetries > 0) { // try to create handle = Interop.mincore.CreateFileMapping(INVALID_HANDLE_VALUE, ref secAttrs, GetPageAccess(access) | (int)options, capacityHigh, capacityLow, mapName); if (!handle.IsInvalid) { break; } else { handle.Dispose(); int createErrorCode = Marshal.GetLastWin32Error(); if (createErrorCode != Interop.mincore.Errors.ERROR_ACCESS_DENIED) { throw Win32Marshal.GetExceptionForWin32Error(createErrorCode); } } // try to open handle = Interop.mincore.OpenFileMapping(GetFileMapAccess(access), (inheritability & HandleInheritability.Inheritable) != 0, mapName); // valid handle if (!handle.IsInvalid) { break; } // didn't get valid handle; have to retry else { handle.Dispose(); int openErrorCode = Marshal.GetLastWin32Error(); if (openErrorCode != Interop.mincore.Errors.ERROR_FILE_NOT_FOUND) { throw Win32Marshal.GetExceptionForWin32Error(openErrorCode); } // increase wait time --waitRetries; if (waitSleep == 0) { waitSleep = 10; } else { ThreadSleep(waitSleep); waitSleep *= 2; } } } // finished retrying but couldn't create or open if (handle == null || handle.IsInvalid) { throw new InvalidOperationException(SR.InvalidOperation_CantCreateFileMapping); } return handle; } // ----------------------------- // ---- PAL layer ends here ---- // ----------------------------- /// <summary> /// This converts a MemoryMappedFileRights to its corresponding native FILE_MAP_XXX value to be used when /// creating new views. /// </summary> private static int GetFileMapAccess(MemoryMappedFileRights rights) { return (int)rights; } /// <summary> /// This converts a MemoryMappedFileAccess to its corresponding native FILE_MAP_XXX value to be used when /// creating new views. /// </summary> internal static int GetFileMapAccess(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Read: return Interop.mincore.FileMapOptions.FILE_MAP_READ; case MemoryMappedFileAccess.Write: return Interop.mincore.FileMapOptions.FILE_MAP_WRITE; case MemoryMappedFileAccess.ReadWrite: return Interop.mincore.FileMapOptions.FILE_MAP_READ | Interop.mincore.FileMapOptions.FILE_MAP_WRITE; case MemoryMappedFileAccess.CopyOnWrite: return Interop.mincore.FileMapOptions.FILE_MAP_COPY; case MemoryMappedFileAccess.ReadExecute: return Interop.mincore.FileMapOptions.FILE_MAP_EXECUTE | Interop.mincore.FileMapOptions.FILE_MAP_READ; default: Debug.Assert(access == MemoryMappedFileAccess.ReadWriteExecute); return Interop.mincore.FileMapOptions.FILE_MAP_EXECUTE | Interop.mincore.FileMapOptions.FILE_MAP_READ | Interop.mincore.FileMapOptions.FILE_MAP_WRITE; } } /// <summary> /// This converts a MemoryMappedFileAccess to it's corresponding native PAGE_XXX value to be used by the /// factory methods that construct a new memory mapped file object. MemoryMappedFileAccess.Write is not /// valid here since there is no corresponding PAGE_XXX value. /// </summary> internal static int GetPageAccess(MemoryMappedFileAccess access) { switch (access) { case MemoryMappedFileAccess.Read: return Interop.mincore.PageOptions.PAGE_READONLY; case MemoryMappedFileAccess.ReadWrite: return Interop.mincore.PageOptions.PAGE_READWRITE; case MemoryMappedFileAccess.CopyOnWrite: return Interop.mincore.PageOptions.PAGE_WRITECOPY; case MemoryMappedFileAccess.ReadExecute: return Interop.mincore.PageOptions.PAGE_EXECUTE_READ; default: Debug.Assert(access == MemoryMappedFileAccess.ReadWriteExecute); return Interop.mincore.PageOptions.PAGE_EXECUTE_READWRITE; } } /// <summary> /// Used by the OpenExisting factory method group and by CreateOrOpen if access is write. /// We'll throw an ArgumentException if the file mapping object didn't exist and the /// caller used CreateOrOpen since Create isn't valid with Write access /// </summary> [SecurityCritical] private static SafeMemoryMappedFileHandle OpenCore( string mapName, HandleInheritability inheritability, int desiredAccessRights, bool createOrOpen) { SafeMemoryMappedFileHandle handle = Interop.mincore.OpenFileMapping( desiredAccessRights, (inheritability & HandleInheritability.Inheritable) != 0, mapName); int lastError = Marshal.GetLastWin32Error(); if (handle.IsInvalid) { handle.Dispose(); if (createOrOpen && (lastError == Interop.mincore.Errors.ERROR_FILE_NOT_FOUND)) { throw new ArgumentException(SR.Argument_NewMMFWriteAccessNotAllowed, "access"); } else { throw Win32Marshal.GetExceptionForWin32Error(lastError); } } return handle; } /// <summary> /// Helper method used to extract the native binary security descriptor from the MemoryMappedFileSecurity /// type. If pinningHandle is not null, caller must free it AFTER the call to CreateFile has returned. /// </summary> [SecurityCritical] private unsafe static Interop.mincore.SECURITY_ATTRIBUTES GetSecAttrs(HandleInheritability inheritability) { Interop.mincore.SECURITY_ATTRIBUTES secAttrs = default(Interop.mincore.SECURITY_ATTRIBUTES); if ((inheritability & HandleInheritability.Inheritable) != 0) { secAttrs = new Interop.mincore.SECURITY_ATTRIBUTES(); secAttrs.nLength = (uint)sizeof(Interop.mincore.SECURITY_ATTRIBUTES); secAttrs.bInheritHandle = Interop.BOOL.TRUE; } return secAttrs; } /// <summary> /// Replacement for Thread.Sleep(milliseconds), which isn't available. /// </summary> internal static void ThreadSleep(int milliseconds) { new ManualResetEventSlim(initialState: false).Wait(milliseconds); } } }
/************************************************************************************ Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Licensed under the Oculus SDK License Version 3.4.1 (the "License"); you may not use the Oculus SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at https://developer.oculus.com/licenses/sdk-3.4.1 Unless required by applicable law or agreed to in writing, the Oculus SDK 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 UNITY_EDITOR using UnityEngine; using UnityEditor; using System.Collections.Generic; using Assets.OVR.Scripts; /// <summary> ///Scans the project and warns about the following conditions: ///Audio sources > 16 ///Using MSAA levels other than recommended level ///Excessive pixel lights (>1 on Gear VR; >3 on Rift) ///Directional Lightmapping Modes (on Gear; use Non-Directional) ///Preload audio setting on individual audio clips ///Decompressing audio clips on load ///Disabling occlusion mesh ///Android target API level set to 21 or higher ///Unity skybox use (on by default, but if you can't see the skybox switching to Color is much faster on Gear) ///Lights marked as "baked" but that were not included in the last bake (and are therefore realtime). ///Lack of static batching and dynamic batching settings activated. ///Full screen image effects (Gear) ///Warn about large textures that are marked as uncompressed. ///32-bit depth buffer (use 16) ///Use of projectors (Gear; can be used carefully but slow enough to warrant a warning) ///Maybe in the future once quantified: Graphics jobs and IL2CPP on Gear. ///Real-time global illumination ///No texture compression, or non-ASTC texture compression as a global setting (Gear). ///Using deferred rendering ///Excessive texture resolution after LOD bias (>2k on Gear VR; >4k on Rift) ///Not using trilinear or aniso filtering and not generating mipmaps ///Excessive render scale (>1.2) ///Slow physics settings: Sleep Threshold < 0.005, Default Contact Offset < 0.01, Solver Iteration Count > 6 ///Shadows on when approaching the geometry or draw call limits ///Non-static objects with colliders that are missing rigidbodies on themselves or in the parent chain. ///No initialization of GPU/CPU throttling settings, or init to dangerous values (-1 or > 3) (Gear) ///Using inefficient effects: SSAO, motion blur, global fog, parallax mapping, etc. ///Too many Overlay layers ///Use of Standard shader or Standard Specular shader on Gear. More generally, excessive use of multipass shaders (legacy specular, etc). ///Multiple cameras with clears (on Gear, potential for excessive fill cost) ///Excessive shader passes (>2) ///Material pointers that have been instanced in the editor (esp. if we could determine that the instance has no deltas from the original) ///Excessive draw calls (>150 on Gear VR; >2000 on Rift) ///Excessive tris or verts (>100k on Gear VR; >1M on Rift) ///Large textures, lots of prefabs in startup scene (for bootstrap optimization) ///GPU skinning: testing Android-only, as most Rift devs are GPU-bound. /// </summary> public class OVRLint : EditorWindow { //TODO: The following require reflection or static analysis. ///Use of ONSP reflections (Gear) ///Use of LoadLevelAsync / LoadLevelAdditiveAsync (on Gear, this kills frame rate so dramatically it's probably better to just go to black and load synchronously) ///Use of Linq in non-editor assemblies (common cause of GCs). Minor: use of foreach. ///Use of Unity WWW (exceptionally high overhead for large file downloads, but acceptable for tiny gets). ///Declared but empty Awake/Start/Update/OnCollisionEnter/OnCollisionExit/OnCollisionStay. Also OnCollision* star methods that declare the Collision argument but do not reference it (omitting it short-circuits the collision contact calculation). private static List<FixRecord> mRecords = new List<FixRecord>(); private Vector2 mScrollPosition; [MenuItem("Tools/Oculus/OVR Performance Lint Tool")] static void Init() { // Get existing open window or if none, make a new one: EditorWindow.GetWindow(typeof(OVRLint)); OVRLint.RunCheck(); } void OnGUI() { GUILayout.Label("OVR Performance Lint Tool", EditorStyles.boldLabel); if (GUILayout.Button("Refresh", EditorStyles.toolbarButton, GUILayout.ExpandWidth(false))) { RunCheck(); } string lastCategory = ""; mScrollPosition = EditorGUILayout.BeginScrollView(mScrollPosition); for (int x = 0; x < mRecords.Count; x++) { FixRecord record = mRecords[x]; if (!record.category.Equals(lastCategory)) // new category { lastCategory = record.category; EditorGUILayout.Separator(); EditorGUILayout.BeginHorizontal(); GUILayout.Label(lastCategory, EditorStyles.label, GUILayout.Width(200)); bool moreThanOne = (x + 1 < mRecords.Count && mRecords[x + 1].category.Equals(lastCategory)); if (record.buttonNames != null && record.buttonNames.Length > 0) { if (moreThanOne) { GUILayout.Label("Apply to all:", EditorStyles.label, GUILayout.Width(75)); for (int y = 0; y < record.buttonNames.Length; y++) { if (GUILayout.Button(record.buttonNames[y], EditorStyles.toolbarButton, GUILayout.Width(200))) { List<FixRecord> recordsToProcess = new List<FixRecord>(); for (int z = x; z < mRecords.Count; z++) { FixRecord thisRecord = mRecords[z]; bool isLast = false; if (z + 1 >= mRecords.Count || !mRecords[z + 1].category.Equals(lastCategory)) { isLast = true; } if (!thisRecord.complete) { recordsToProcess.Add(thisRecord); } if (isLast) { break; } } UnityEngine.Object[] undoObjects = new UnityEngine.Object[recordsToProcess.Count]; for (int z = 0; z < recordsToProcess.Count; z++) { undoObjects[z] = recordsToProcess[z].targetObject; } Undo.RecordObjects(undoObjects, record.category + " (Multiple)"); for (int z = 0; z < recordsToProcess.Count; z++) { FixRecord thisRecord = recordsToProcess[z]; thisRecord.fixMethod(thisRecord.targetObject, (z + 1 == recordsToProcess.Count), y); thisRecord.complete = true; } } } } } EditorGUILayout.EndHorizontal(); if (moreThanOne || record.targetObject) { GUILayout.Label(record.message); } } EditorGUILayout.BeginHorizontal(); GUI.enabled = !record.complete; if (record.targetObject) { EditorGUILayout.ObjectField(record.targetObject, record.targetObject.GetType(), true); } else { GUILayout.Label(record.message); } if (record.buttonNames != null) { for (int y = 0; y < record.buttonNames.Length; y++) { if (GUILayout.Button(record.buttonNames[y], EditorStyles.toolbarButton, GUILayout.Width(200))) { if (record.targetObject != null) { Undo.RecordObject(record.targetObject, record.category); } record.fixMethod(record.targetObject, true, y); record.complete = true; } } } GUI.enabled = true; EditorGUILayout.EndHorizontal(); } EditorGUILayout.EndScrollView(); } static void RunCheck() { mRecords.Clear(); CheckStaticCommonIssues(); #if UNITY_ANDROID CheckStaticAndroidIssues(); #endif if (EditorApplication.isPlaying) { CheckRuntimeCommonIssues(); #if UNITY_ANDROID CheckRuntimeAndroidIssues(); #endif } mRecords.Sort(delegate (FixRecord record1, FixRecord record2) { return record1.category.CompareTo(record2.category); }); } static void AddFix(string category, string message, FixMethodDelegate method, UnityEngine.Object target, params string[] buttons) { mRecords.Add(new FixRecord(category, message, method, target, buttons)); } static void CheckStaticCommonIssues() { if (OVRManager.IsUnityAlphaOrBetaVersion()) { AddFix("General", OVRManager.UnityAlphaOrBetaVersionWarningMessage, null, null); } if (QualitySettings.anisotropicFiltering != AnisotropicFiltering.Enable && QualitySettings.anisotropicFiltering != AnisotropicFiltering.ForceEnable) { AddFix("Optimize Aniso", "Anisotropic filtering is recommended for optimal image sharpness and GPU performance.", delegate (UnityEngine.Object obj, bool last, int selected) { // Ideally this would be multi-option: offer Enable or ForceEnable. QualitySettings.anisotropicFiltering = AnisotropicFiltering.Enable; }, null, "Fix"); } #if UNITY_ANDROID int recommendedPixelLightCount = 1; #else int recommendedPixelLightCount = 3; #endif if (QualitySettings.pixelLightCount > recommendedPixelLightCount) { AddFix("Optimize Pixel Light Count", "For GPU performance set no more than " + recommendedPixelLightCount + " pixel lights in Quality Settings (currently " + QualitySettings.pixelLightCount + ").", delegate (UnityEngine.Object obj, bool last, int selected) { QualitySettings.pixelLightCount = recommendedPixelLightCount; }, null, "Fix"); } #if false // Should we recommend this? Seems to be mutually exclusive w/ dynamic batching. if (!PlayerSettings.graphicsJobs) { AddFix ("Optimize Graphics Jobs", "For CPU performance, please use graphics jobs.", delegate(UnityEngine.Object obj, bool last, int selected) { PlayerSettings.graphicsJobs = true; }, null, "Fix"); } #endif #if UNITY_2017_2_OR_NEWER if ((!PlayerSettings.MTRendering || !PlayerSettings.GetMobileMTRendering(BuildTargetGroup.Android))) #else if ((!PlayerSettings.MTRendering || !PlayerSettings.mobileMTRendering)) #endif { AddFix("Optimize MT Rendering", "For CPU performance, please enable multithreaded rendering.", delegate (UnityEngine.Object obj, bool last, int selected) { #if UNITY_2017_2_OR_NEWER PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Standalone, true); PlayerSettings.SetMobileMTRendering(BuildTargetGroup.Android, true); #else PlayerSettings.MTRendering = PlayerSettings.mobileMTRendering = true; #endif }, null, "Fix"); } #if UNITY_ANDROID if (!PlayerSettings.use32BitDisplayBuffer) { AddFix("Optimize Display Buffer Format", "We recommend to enable use32BitDisplayBuffer.", delegate (UnityEngine.Object obj, bool last, int selected) { PlayerSettings.use32BitDisplayBuffer = true; }, null, "Fix"); } #endif #if UNITY_2017_3_OR_NEWER && !UNITY_ANDROID if (!PlayerSettings.VROculus.dashSupport) { AddFix("Enable Dash Integration", "We recommend to enable Dash Integration for better user experience.", delegate (UnityEngine.Object obj, bool last, int selected) { PlayerSettings.VROculus.dashSupport = true; }, null, "Fix"); } if (!PlayerSettings.VROculus.sharedDepthBuffer) { AddFix("Enable Depth Buffer Sharing", "We recommend to enable Depth Buffer Sharing for better user experience on Oculus Dash.", delegate (UnityEngine.Object obj, bool last, int selected) { PlayerSettings.VROculus.sharedDepthBuffer = true; }, null, "Fix"); } #endif BuildTargetGroup target = EditorUserBuildSettings.selectedBuildTargetGroup; var tier = UnityEngine.Rendering.GraphicsTier.Tier1; var tierSettings = UnityEditor.Rendering.EditorGraphicsSettings.GetTierSettings(target, tier); if ((tierSettings.renderingPath == RenderingPath.DeferredShading || tierSettings.renderingPath == RenderingPath.DeferredLighting)) { AddFix("Optimize Rendering Path", "For CPU performance, please do not use deferred shading.", delegate (UnityEngine.Object obj, bool last, int selected) { tierSettings.renderingPath = RenderingPath.Forward; UnityEditor.Rendering.EditorGraphicsSettings.SetTierSettings(target, tier, tierSettings); }, null, "Use Forward"); } if (PlayerSettings.stereoRenderingPath == StereoRenderingPath.MultiPass) { AddFix("Optimize Stereo Rendering", "For CPU performance, please enable single-pass or instanced stereo rendering.", delegate (UnityEngine.Object obj, bool last, int selected) { PlayerSettings.stereoRenderingPath = StereoRenderingPath.Instancing; }, null, "Fix"); } if (LightmapSettings.lightmaps.Length > 0 && LightmapSettings.lightmapsMode != LightmapsMode.NonDirectional) { AddFix("Optimize Lightmap Directionality", "Switching from directional lightmaps to non-directional lightmaps can save a small amount of GPU time.", delegate (UnityEngine.Object obj, bool last, int selected) { LightmapSettings.lightmapsMode = LightmapsMode.NonDirectional; }, null, "Switch to non-directional lightmaps"); } if (Lightmapping.realtimeGI) { AddFix("Disable Realtime GI", "Disabling real-time global illumination can improve GPU performance.", delegate (UnityEngine.Object obj, bool last, int selected) { Lightmapping.realtimeGI = false; }, null, "Set Lightmapping.realtimeGI = false."); } var lights = GameObject.FindObjectsOfType<Light>(); for (int i = 0; i < lights.Length; ++i) { #if UNITY_2017_3_OR_NEWER if (lights [i].type != LightType.Directional && !lights [i].bakingOutput.isBaked && IsLightBaked(lights[i])) #else if (lights[i].type != LightType.Directional && !lights[i].isBaked && IsLightBaked(lights[i])) #endif { AddFix("Unbaked Lights", "The following lights in the scene are marked as Baked, but they don't have up to date lightmap data. Generate the lightmap data, or set it to auto-generate, in Window->Lighting->Settings.", null, lights[i], null); } if (lights[i].shadows != LightShadows.None && !IsLightBaked(lights[i])) { AddFix("Optimize Shadows", "For CPU performance, consider disabling shadows on realtime lights.", delegate (UnityEngine.Object obj, bool last, int selected) { Light thisLight = (Light)obj; thisLight.shadows = LightShadows.None; }, lights[i], "Set \"Shadow Type\" to \"No Shadows\""); } } var sources = GameObject.FindObjectsOfType<AudioSource>(); if (sources.Length > 16) { List<AudioSource> playingAudioSources = new List<AudioSource>(); foreach (var audioSource in sources) { if (audioSource.isPlaying) { playingAudioSources.Add(audioSource); } } if (playingAudioSources.Count > 16) { // Sort playing audio sources by priority playingAudioSources.Sort(delegate (AudioSource x, AudioSource y) { return x.priority.CompareTo(y.priority); }); for (int i = 16; i < playingAudioSources.Count; ++i) { AddFix("Optimize Audio Source Count", "For CPU performance, please disable all but the top 16 AudioSources.", delegate (UnityEngine.Object obj, bool last, int selected) { AudioSource audioSource = (AudioSource)obj; audioSource.enabled = false; }, playingAudioSources[i], "Disable"); } } } var clips = GameObject.FindObjectsOfType<AudioClip>(); for (int i = 0; i < clips.Length; ++i) { if (clips[i].loadType == AudioClipLoadType.DecompressOnLoad) { AddFix("Audio Loading", "For fast loading, please don't use decompress on load for audio clips", delegate (UnityEngine.Object obj, bool last, int selected) { AudioClip thisClip = (AudioClip)obj; if (selected == 0) { SetAudioLoadType(thisClip, AudioClipLoadType.CompressedInMemory, last); } else { SetAudioLoadType(thisClip, AudioClipLoadType.Streaming, last); } }, clips[i], "Change to Compressed in Memory", "Change to Streaming"); } if (clips[i].preloadAudioData) { AddFix("Audio Preload", "For fast loading, please don't preload data for audio clips.", delegate (UnityEngine.Object obj, bool last, int selected) { SetAudioPreload(clips[i], false, last); }, clips[i], "Fix"); } } if (Physics.defaultContactOffset < 0.01f) { AddFix("Optimize Contact Offset", "For CPU performance, please don't use default contact offset below 0.01.", delegate (UnityEngine.Object obj, bool last, int selected) { Physics.defaultContactOffset = 0.01f; }, null, "Fix"); } if (Physics.sleepThreshold < 0.005f) { AddFix("Optimize Sleep Threshold", "For CPU performance, please don't use sleep threshold below 0.005.", delegate (UnityEngine.Object obj, bool last, int selected) { Physics.sleepThreshold = 0.005f; }, null, "Fix"); } if (Physics.defaultSolverIterations > 8) { AddFix("Optimize Solver Iterations", "For CPU performance, please don't use excessive solver iteration counts.", delegate (UnityEngine.Object obj, bool last, int selected) { Physics.defaultSolverIterations = 8; }, null, "Fix"); } var materials = Resources.FindObjectsOfTypeAll<Material>(); for (int i = 0; i < materials.Length; ++i) { if (materials[i].shader.name.Contains("Parallax") || materials[i].IsKeywordEnabled("_PARALLAXMAP")) { AddFix("Optimize Shading", "For GPU performance, please don't use parallax-mapped materials.", delegate (UnityEngine.Object obj, bool last, int selected) { Material thisMaterial = (Material)obj; if (thisMaterial.IsKeywordEnabled("_PARALLAXMAP")) { thisMaterial.DisableKeyword("_PARALLAXMAP"); } if (thisMaterial.shader.name.Contains("Parallax")) { var newName = thisMaterial.shader.name.Replace("-ParallaxSpec", "-BumpSpec"); newName = newName.Replace("-Parallax", "-Bump"); var newShader = Shader.Find(newName); if (newShader) { thisMaterial.shader = newShader; } else { Debug.LogWarning("Unable to find a replacement for shader " + materials[i].shader.name); } } }, materials[i], "Fix"); } } var renderers = GameObject.FindObjectsOfType<Renderer>(); for (int i = 0; i < renderers.Length; ++i) { if (renderers[i].sharedMaterial == null) { AddFix("Instanced Materials", "Please avoid instanced materials on renderers.", null, renderers[i]); } } var overlays = GameObject.FindObjectsOfType<OVROverlay>(); if (overlays.Length > 4) { AddFix("Optimize VR Layer Count", "For GPU performance, please use 4 or fewer VR layers.", delegate (UnityEngine.Object obj, bool last, int selected) { for (int i = 4; i < OVROverlay.instances.Length; ++i) { OVROverlay.instances[i].enabled = false; } }, null, "Fix"); } var splashScreen = PlayerSettings.virtualRealitySplashScreen; if (splashScreen != null) { if (splashScreen.filterMode != FilterMode.Trilinear) { AddFix("Optimize VR Splash Filtering", "For visual quality, please use trilinear filtering on your VR splash screen.", delegate (UnityEngine.Object obj, bool last, int EditorSelectedRenderState) { var assetPath = AssetDatabase.GetAssetPath(splashScreen); var importer = (TextureImporter)TextureImporter.GetAtPath(assetPath); importer.filterMode = FilterMode.Trilinear; AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); }, null, "Fix"); } if (splashScreen.mipmapCount <= 1) { AddFix("Generate VR Splash Mipmaps", "For visual quality, please use mipmaps with your VR splash screen.", delegate (UnityEngine.Object obj, bool last, int EditorSelectedRenderState) { var assetPath = AssetDatabase.GetAssetPath(splashScreen); var importer = (TextureImporter)TextureImporter.GetAtPath(assetPath); importer.mipmapEnabled = true; AssetDatabase.ImportAsset(assetPath, ImportAssetOptions.ForceUpdate); }, null, "Fix"); } } } static void CheckRuntimeCommonIssues() { if (!OVRPlugin.occlusionMesh) { AddFix("Occlusion Mesh", "Enabling the occlusion mesh saves substantial GPU resources, generally with no visual impact. Enable unless you have an exceptional use case.", delegate (UnityEngine.Object obj, bool last, int selected) { OVRPlugin.occlusionMesh = true; }, null, "Set OVRPlugin.occlusionMesh = true"); } if (OVRManager.instance != null && !OVRManager.instance.useRecommendedMSAALevel) { AddFix("Optimize MSAA", "OVRManager can select the optimal antialiasing for the installed hardware at runtime. Recommend enabling this.", delegate (UnityEngine.Object obj, bool last, int selected) { OVRManager.instance.useRecommendedMSAALevel = true; }, null, "Set useRecommendedMSAALevel = true"); } #if UNITY_2017_2_OR_NEWER if (UnityEngine.XR.XRSettings.eyeTextureResolutionScale > 1.5) #else if (UnityEngine.VR.VRSettings.renderScale > 1.5) #endif { AddFix("Optimize Render Scale", "Render scale above 1.5 is extremely expensive on the GPU, with little if any positive visual benefit.", delegate (UnityEngine.Object obj, bool last, int selected) { #if UNITY_2017_2_OR_NEWER UnityEngine.XR.XRSettings.eyeTextureResolutionScale = 1.5f; #else UnityEngine.VR.VRSettings.renderScale = 1.5f; #endif }, null, "Fix"); } } static void CheckStaticAndroidIssues() { AndroidSdkVersions recommendedAndroidSdkVersion = AndroidSdkVersions.AndroidApiLevel21; if ((int)PlayerSettings.Android.minSdkVersion < (int)recommendedAndroidSdkVersion) { AddFix("Optimize Android API Level", "To avoid legacy workarounds, please require at least API level " + (int)recommendedAndroidSdkVersion, delegate (UnityEngine.Object obj, bool last, int selected) { PlayerSettings.Android.minSdkVersion = recommendedAndroidSdkVersion; }, null, "Fix"); } if (!PlayerSettings.gpuSkinning) { AddFix("Optimize GPU Skinning", "If you are CPU-bound, consider using GPU skinning.", delegate (UnityEngine.Object obj, bool last, int selected) { PlayerSettings.gpuSkinning = true; }, null, "Fix"); } if (RenderSettings.skybox) { AddFix("Optimize Clearing", "For GPU performance, please don't use Unity's built-in Skybox.", delegate (UnityEngine.Object obj, bool last, int selected) { RenderSettings.skybox = null; }, null, "Clear Skybox"); } var materials = Resources.FindObjectsOfTypeAll<Material>(); for (int i = 0; i < materials.Length; ++i) { if (materials[i].IsKeywordEnabled("_SPECGLOSSMAP") || materials[i].IsKeywordEnabled("_METALLICGLOSSMAP")) { AddFix("Optimize Specular Material", "For GPU performance, please don't use specular shader on materials.", delegate (UnityEngine.Object obj, bool last, int selected) { Material thisMaterial = (Material)obj; thisMaterial.DisableKeyword("_SPECGLOSSMAP"); thisMaterial.DisableKeyword("_METALLICGLOSSMAP"); }, materials[i], "Fix"); } if (materials[i].passCount > 1) { AddFix("Material Passes", "Please use 2 or fewer passes in materials.", null, materials[i]); } } ScriptingImplementation backend = PlayerSettings.GetScriptingBackend(UnityEditor.BuildTargetGroup.Android); if (backend != UnityEditor.ScriptingImplementation.IL2CPP) { AddFix("Optimize Scripting Backend", "For CPU performance, please use IL2CPP.", delegate (UnityEngine.Object obj, bool last, int selected) { PlayerSettings.SetScriptingBackend(UnityEditor.BuildTargetGroup.Android, UnityEditor.ScriptingImplementation.IL2CPP); }, null, "Fix"); } var monoBehaviours = GameObject.FindObjectsOfType<MonoBehaviour>(); System.Type effectBaseType = System.Type.GetType("UnityStandardAssets.ImageEffects.PostEffectsBase"); if (effectBaseType != null) { for (int i = 0; i < monoBehaviours.Length; ++i) { if (monoBehaviours[i].GetType().IsSubclassOf(effectBaseType)) { AddFix("Image Effects", "Please don't use image effects.", null, monoBehaviours[i]); } } } var textures = Resources.FindObjectsOfTypeAll<Texture2D>(); int maxTextureSize = 1024 * (1 << QualitySettings.masterTextureLimit); maxTextureSize = maxTextureSize * maxTextureSize; for (int i = 0; i < textures.Length; ++i) { if (textures[i].filterMode == FilterMode.Trilinear && textures[i].mipmapCount == 1) { AddFix("Optimize Texture Filtering", "For GPU performance, please generate mipmaps or disable trilinear filtering for textures.", delegate (UnityEngine.Object obj, bool last, int selected) { Texture2D thisTexture = (Texture2D)obj; if (selected == 0) { thisTexture.filterMode = FilterMode.Bilinear; } else { SetTextureUseMips(thisTexture, true, last); } }, textures[i], "Switch to Bilinear", "Generate Mipmaps"); } } var projectors = GameObject.FindObjectsOfType<Projector>(); if (projectors.Length > 0) { AddFix("Optimize Projectors", "For GPU performance, please don't use projectors.", delegate (UnityEngine.Object obj, bool last, int selected) { Projector[] thisProjectors = GameObject.FindObjectsOfType<Projector>(); for (int i = 0; i < thisProjectors.Length; ++i) { thisProjectors[i].enabled = false; } }, null, "Disable Projectors"); } if (EditorUserBuildSettings.androidBuildSubtarget != MobileTextureSubtarget.ASTC) { AddFix("Optimize Texture Compression", "For GPU performance, please use ASTC.", delegate (UnityEngine.Object obj, bool last, int selected) { EditorUserBuildSettings.androidBuildSubtarget = MobileTextureSubtarget.ASTC; }, null, "Fix"); } var cameras = GameObject.FindObjectsOfType<Camera>(); int clearCount = 0; for (int i = 0; i < cameras.Length; ++i) { if (cameras[i].clearFlags != CameraClearFlags.Nothing && cameras[i].clearFlags != CameraClearFlags.Depth) ++clearCount; } if (clearCount > 2) { AddFix("Camera Clears", "Please use 2 or fewer clears.", null, null); } } static void CheckRuntimeAndroidIssues() { if (UnityStats.usedTextureMemorySize + UnityStats.vboTotalBytes > 1000000) { AddFix("Graphics Memory", "Please use less than 1GB of vertex and texture memory.", null, null); } if (OVRManager.cpuLevel < 0 || OVRManager.cpuLevel > 3) { AddFix("Optimize CPU level", "For battery life, please use a safe CPU level.", delegate (UnityEngine.Object obj, bool last, int selected) { OVRManager.cpuLevel = 2; }, null, "Set to CPU2"); } if (OVRManager.gpuLevel < 0 || OVRManager.gpuLevel > 3) { AddFix("Optimize GPU level", "For battery life, please use a safe GPU level.", delegate (UnityEngine.Object obj, bool last, int selected) { OVRManager.gpuLevel = 2; }, null, "Set to GPU2"); } if (UnityStats.triangles > 100000 || UnityStats.vertices > 100000) { AddFix("Triangles and Verts", "Please use less than 100000 triangles or vertices.", null, null); } // Warn for 50 if in non-VR mode? if (UnityStats.drawCalls > 100) { AddFix("Draw Calls", "Please use less than 100 draw calls.", null, null); } } enum LightmapType { Realtime = 4, Baked = 2, Mixed = 1 }; static bool IsLightBaked(Light light) { return light.lightmapBakeType == LightmapBakeType.Baked; } static void SetAudioPreload(AudioClip clip, bool preload, bool refreshImmediately) { if (clip != null) { string assetPath = AssetDatabase.GetAssetPath(clip); AudioImporter importer = AssetImporter.GetAtPath(assetPath) as AudioImporter; if (importer != null) { if (preload != importer.preloadAudioData) { importer.preloadAudioData = preload; AssetDatabase.ImportAsset(assetPath); if (refreshImmediately) { AssetDatabase.Refresh(); } } } } } static void SetAudioLoadType(AudioClip clip, AudioClipLoadType loadType, bool refreshImmediately) { if (clip != null) { string assetPath = AssetDatabase.GetAssetPath(clip); AudioImporter importer = AssetImporter.GetAtPath(assetPath) as AudioImporter; if (importer != null) { if (loadType != importer.defaultSampleSettings.loadType) { AudioImporterSampleSettings settings = importer.defaultSampleSettings; settings.loadType = loadType; importer.defaultSampleSettings = settings; AssetDatabase.ImportAsset(assetPath); if (refreshImmediately) { AssetDatabase.Refresh(); } } } } } public static void SetTextureUseMips(Texture texture, bool useMips, bool refreshImmediately) { if (texture != null) { string assetPath = AssetDatabase.GetAssetPath(texture); TextureImporter tImporter = AssetImporter.GetAtPath(assetPath) as TextureImporter; if (tImporter != null && tImporter.mipmapEnabled != useMips) { tImporter.mipmapEnabled = useMips; AssetDatabase.ImportAsset(assetPath); if (refreshImmediately) { AssetDatabase.Refresh(); } } } } static T FindComponentInParents<T>(GameObject obj) where T : Component { T component = null; if (obj != null) { Transform parent = obj.transform.parent; if (parent != null) { do { component = parent.GetComponent(typeof(T)) as T; parent = parent.parent; } while (parent != null && component == null); } } return component; } } #endif
// Copyright 2018 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using gaxres = Google.Api.Gax.ResourceNames; using sys = System; using linq = System.Linq; namespace Google.Cloud.Dialogflow.V2 { /// <summary> /// Resource name for the 'session' resource. /// </summary> public sealed partial class SessionName : gax::IResourceName, sys::IEquatable<SessionName> { private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/agent/sessions/{session}"); /// <summary> /// Parses the given session resource name in string form into a new /// <see cref="SessionName"/> instance. /// </summary> /// <param name="sessionName">The session resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SessionName"/> if successful.</returns> public static SessionName Parse(string sessionName) { gax::GaxPreconditions.CheckNotNull(sessionName, nameof(sessionName)); gax::TemplatedResourceName resourceName = s_template.ParseName(sessionName); return new SessionName(resourceName[0], resourceName[1]); } /// <summary> /// Tries to parse the given session resource name in string form into a new /// <see cref="SessionName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="sessionName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="sessionName">The session resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="SessionName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string sessionName, out SessionName result) { gax::GaxPreconditions.CheckNotNull(sessionName, nameof(sessionName)); gax::TemplatedResourceName resourceName; if (s_template.TryParseName(sessionName, out resourceName)) { result = new SessionName(resourceName[0], resourceName[1]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="SessionName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="sessionId">The session ID. Must not be <c>null</c>.</param> public SessionName(string projectId, string sessionId) { ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); SessionId = gax::GaxPreconditions.CheckNotNull(sessionId, nameof(sessionId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The session ID. Never <c>null</c>. /// </summary> public string SessionId { get; } /// <inheritdoc /> public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, SessionId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as SessionName); /// <inheritdoc /> public bool Equals(SessionName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(SessionName a, SessionName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(SessionName a, SessionName b) => !(a == b); } /// <summary> /// Resource name for the 'context' resource. /// </summary> public sealed partial class ContextName : gax::IResourceName, sys::IEquatable<ContextName> { private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/agent/sessions/{session}/contexts/{context}"); /// <summary> /// Parses the given context resource name in string form into a new /// <see cref="ContextName"/> instance. /// </summary> /// <param name="contextName">The context resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ContextName"/> if successful.</returns> public static ContextName Parse(string contextName) { gax::GaxPreconditions.CheckNotNull(contextName, nameof(contextName)); gax::TemplatedResourceName resourceName = s_template.ParseName(contextName); return new ContextName(resourceName[0], resourceName[1], resourceName[2]); } /// <summary> /// Tries to parse the given context resource name in string form into a new /// <see cref="ContextName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="contextName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="contextName">The context resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="ContextName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string contextName, out ContextName result) { gax::GaxPreconditions.CheckNotNull(contextName, nameof(contextName)); gax::TemplatedResourceName resourceName; if (s_template.TryParseName(contextName, out resourceName)) { result = new ContextName(resourceName[0], resourceName[1], resourceName[2]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="ContextName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="sessionId">The session ID. Must not be <c>null</c>.</param> /// <param name="contextId">The context ID. Must not be <c>null</c>.</param> public ContextName(string projectId, string sessionId, string contextId) { ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); SessionId = gax::GaxPreconditions.CheckNotNull(sessionId, nameof(sessionId)); ContextId = gax::GaxPreconditions.CheckNotNull(contextId, nameof(contextId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The session ID. Never <c>null</c>. /// </summary> public string SessionId { get; } /// <summary> /// The context ID. Never <c>null</c>. /// </summary> public string ContextId { get; } /// <inheritdoc /> public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, SessionId, ContextId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as ContextName); /// <inheritdoc /> public bool Equals(ContextName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(ContextName a, ContextName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(ContextName a, ContextName b) => !(a == b); } /// <summary> /// Resource name for the 'project_agent' resource. /// </summary> public sealed partial class ProjectAgentName : gax::IResourceName, sys::IEquatable<ProjectAgentName> { private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/agent"); /// <summary> /// Parses the given project_agent resource name in string form into a new /// <see cref="ProjectAgentName"/> instance. /// </summary> /// <param name="projectAgentName">The project_agent resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="ProjectAgentName"/> if successful.</returns> public static ProjectAgentName Parse(string projectAgentName) { gax::GaxPreconditions.CheckNotNull(projectAgentName, nameof(projectAgentName)); gax::TemplatedResourceName resourceName = s_template.ParseName(projectAgentName); return new ProjectAgentName(resourceName[0]); } /// <summary> /// Tries to parse the given project_agent resource name in string form into a new /// <see cref="ProjectAgentName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="projectAgentName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="projectAgentName">The project_agent resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="ProjectAgentName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string projectAgentName, out ProjectAgentName result) { gax::GaxPreconditions.CheckNotNull(projectAgentName, nameof(projectAgentName)); gax::TemplatedResourceName resourceName; if (s_template.TryParseName(projectAgentName, out resourceName)) { result = new ProjectAgentName(resourceName[0]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="ProjectAgentName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> public ProjectAgentName(string projectId) { ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <inheritdoc /> public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as ProjectAgentName); /// <inheritdoc /> public bool Equals(ProjectAgentName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(ProjectAgentName a, ProjectAgentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(ProjectAgentName a, ProjectAgentName b) => !(a == b); } /// <summary> /// Resource name for the 'entity_type' resource. /// </summary> public sealed partial class EntityTypeName : gax::IResourceName, sys::IEquatable<EntityTypeName> { private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/agent/entityTypes/{entity_type}"); /// <summary> /// Parses the given entity_type resource name in string form into a new /// <see cref="EntityTypeName"/> instance. /// </summary> /// <param name="entityTypeName">The entity_type resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="EntityTypeName"/> if successful.</returns> public static EntityTypeName Parse(string entityTypeName) { gax::GaxPreconditions.CheckNotNull(entityTypeName, nameof(entityTypeName)); gax::TemplatedResourceName resourceName = s_template.ParseName(entityTypeName); return new EntityTypeName(resourceName[0], resourceName[1]); } /// <summary> /// Tries to parse the given entity_type resource name in string form into a new /// <see cref="EntityTypeName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="entityTypeName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="entityTypeName">The entity_type resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="EntityTypeName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string entityTypeName, out EntityTypeName result) { gax::GaxPreconditions.CheckNotNull(entityTypeName, nameof(entityTypeName)); gax::TemplatedResourceName resourceName; if (s_template.TryParseName(entityTypeName, out resourceName)) { result = new EntityTypeName(resourceName[0], resourceName[1]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="EntityTypeName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="entityTypeId">The entityType ID. Must not be <c>null</c>.</param> public EntityTypeName(string projectId, string entityTypeId) { ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); EntityTypeId = gax::GaxPreconditions.CheckNotNull(entityTypeId, nameof(entityTypeId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The entityType ID. Never <c>null</c>. /// </summary> public string EntityTypeId { get; } /// <inheritdoc /> public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, EntityTypeId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as EntityTypeName); /// <inheritdoc /> public bool Equals(EntityTypeName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(EntityTypeName a, EntityTypeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(EntityTypeName a, EntityTypeName b) => !(a == b); } /// <summary> /// Resource name for the 'intent' resource. /// </summary> public sealed partial class IntentName : gax::IResourceName, sys::IEquatable<IntentName> { private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/agent/intents/{intent}"); /// <summary> /// Parses the given intent resource name in string form into a new /// <see cref="IntentName"/> instance. /// </summary> /// <param name="intentName">The intent resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="IntentName"/> if successful.</returns> public static IntentName Parse(string intentName) { gax::GaxPreconditions.CheckNotNull(intentName, nameof(intentName)); gax::TemplatedResourceName resourceName = s_template.ParseName(intentName); return new IntentName(resourceName[0], resourceName[1]); } /// <summary> /// Tries to parse the given intent resource name in string form into a new /// <see cref="IntentName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="intentName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="intentName">The intent resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="IntentName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string intentName, out IntentName result) { gax::GaxPreconditions.CheckNotNull(intentName, nameof(intentName)); gax::TemplatedResourceName resourceName; if (s_template.TryParseName(intentName, out resourceName)) { result = new IntentName(resourceName[0], resourceName[1]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="IntentName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="intentId">The intent ID. Must not be <c>null</c>.</param> public IntentName(string projectId, string intentId) { ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); IntentId = gax::GaxPreconditions.CheckNotNull(intentId, nameof(intentId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The intent ID. Never <c>null</c>. /// </summary> public string IntentId { get; } /// <inheritdoc /> public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, IntentId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as IntentName); /// <inheritdoc /> public bool Equals(IntentName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(IntentName a, IntentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(IntentName a, IntentName b) => !(a == b); } /// <summary> /// Resource name for the 'agent' resource. /// </summary> public sealed partial class AgentName : gax::IResourceName, sys::IEquatable<AgentName> { private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/agents/{agent}"); /// <summary> /// Parses the given agent resource name in string form into a new /// <see cref="AgentName"/> instance. /// </summary> /// <param name="agentName">The agent resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AgentName"/> if successful.</returns> public static AgentName Parse(string agentName) { gax::GaxPreconditions.CheckNotNull(agentName, nameof(agentName)); gax::TemplatedResourceName resourceName = s_template.ParseName(agentName); return new AgentName(resourceName[0], resourceName[1]); } /// <summary> /// Tries to parse the given agent resource name in string form into a new /// <see cref="AgentName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="agentName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="agentName">The agent resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="AgentName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string agentName, out AgentName result) { gax::GaxPreconditions.CheckNotNull(agentName, nameof(agentName)); gax::TemplatedResourceName resourceName; if (s_template.TryParseName(agentName, out resourceName)) { result = new AgentName(resourceName[0], resourceName[1]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="AgentName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="agentId">The agent ID. Must not be <c>null</c>.</param> public AgentName(string projectId, string agentId) { ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); AgentId = gax::GaxPreconditions.CheckNotNull(agentId, nameof(agentId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The agent ID. Never <c>null</c>. /// </summary> public string AgentId { get; } /// <inheritdoc /> public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, AgentId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as AgentName); /// <inheritdoc /> public bool Equals(AgentName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(AgentName a, AgentName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(AgentName a, AgentName b) => !(a == b); } /// <summary> /// Resource name for the 'session_entity_type' resource. /// </summary> public sealed partial class SessionEntityTypeName : gax::IResourceName, sys::IEquatable<SessionEntityTypeName> { private static readonly gax::PathTemplate s_template = new gax::PathTemplate("projects/{project}/agent/sessions/{session}/entityTypes/{entity_type}"); /// <summary> /// Parses the given session_entity_type resource name in string form into a new /// <see cref="SessionEntityTypeName"/> instance. /// </summary> /// <param name="sessionEntityTypeName">The session_entity_type resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="SessionEntityTypeName"/> if successful.</returns> public static SessionEntityTypeName Parse(string sessionEntityTypeName) { gax::GaxPreconditions.CheckNotNull(sessionEntityTypeName, nameof(sessionEntityTypeName)); gax::TemplatedResourceName resourceName = s_template.ParseName(sessionEntityTypeName); return new SessionEntityTypeName(resourceName[0], resourceName[1], resourceName[2]); } /// <summary> /// Tries to parse the given session_entity_type resource name in string form into a new /// <see cref="SessionEntityTypeName"/> instance. /// </summary> /// <remarks> /// This method still throws <see cref="sys::ArgumentNullException"/> if <paramref name="sessionEntityTypeName"/> is null, /// as this would usually indicate a programming error rather than a data error. /// </remarks> /// <param name="sessionEntityTypeName">The session_entity_type resource name in string form. Must not be <c>null</c>.</param> /// <param name="result">When this method returns, the parsed <see cref="SessionEntityTypeName"/>, /// or <c>null</c> if parsing fails.</param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string sessionEntityTypeName, out SessionEntityTypeName result) { gax::GaxPreconditions.CheckNotNull(sessionEntityTypeName, nameof(sessionEntityTypeName)); gax::TemplatedResourceName resourceName; if (s_template.TryParseName(sessionEntityTypeName, out resourceName)) { result = new SessionEntityTypeName(resourceName[0], resourceName[1], resourceName[2]); return true; } else { result = null; return false; } } /// <summary> /// Constructs a new instance of the <see cref="SessionEntityTypeName"/> resource name class /// from its component parts. /// </summary> /// <param name="projectId">The project ID. Must not be <c>null</c>.</param> /// <param name="sessionId">The session ID. Must not be <c>null</c>.</param> /// <param name="entityTypeId">The entityType ID. Must not be <c>null</c>.</param> public SessionEntityTypeName(string projectId, string sessionId, string entityTypeId) { ProjectId = gax::GaxPreconditions.CheckNotNull(projectId, nameof(projectId)); SessionId = gax::GaxPreconditions.CheckNotNull(sessionId, nameof(sessionId)); EntityTypeId = gax::GaxPreconditions.CheckNotNull(entityTypeId, nameof(entityTypeId)); } /// <summary> /// The project ID. Never <c>null</c>. /// </summary> public string ProjectId { get; } /// <summary> /// The session ID. Never <c>null</c>. /// </summary> public string SessionId { get; } /// <summary> /// The entityType ID. Never <c>null</c>. /// </summary> public string EntityTypeId { get; } /// <inheritdoc /> public gax::ResourceNameKind Kind => gax::ResourceNameKind.Simple; /// <inheritdoc /> public override string ToString() => s_template.Expand(ProjectId, SessionId, EntityTypeId); /// <inheritdoc /> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc /> public override bool Equals(object obj) => Equals(obj as SessionEntityTypeName); /// <inheritdoc /> public bool Equals(SessionEntityTypeName other) => ToString() == other?.ToString(); /// <inheritdoc /> public static bool operator ==(SessionEntityTypeName a, SessionEntityTypeName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc /> public static bool operator !=(SessionEntityTypeName a, SessionEntityTypeName b) => !(a == b); } public partial class BatchCreateEntitiesRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.EntityTypeName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.EntityTypeName ParentAsEntityTypeName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.EntityTypeName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class BatchDeleteEntitiesRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.EntityTypeName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.EntityTypeName ParentAsEntityTypeName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.EntityTypeName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class BatchDeleteEntityTypesRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ProjectAgentName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ProjectAgentName ParentAsProjectAgentName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.ProjectAgentName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class BatchDeleteIntentsRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ProjectAgentName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ProjectAgentName ParentAsProjectAgentName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.ProjectAgentName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class BatchUpdateEntitiesRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.EntityTypeName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.EntityTypeName ParentAsEntityTypeName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.EntityTypeName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class BatchUpdateEntityTypesRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ProjectAgentName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ProjectAgentName ParentAsProjectAgentName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.ProjectAgentName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class BatchUpdateIntentsRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ProjectAgentName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ProjectAgentName ParentAsProjectAgentName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.ProjectAgentName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class Context { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ContextName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ContextName ContextName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.ContextName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class CreateContextRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.SessionName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.SessionName ParentAsSessionName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.SessionName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class CreateEntityTypeRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ProjectAgentName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ProjectAgentName ParentAsProjectAgentName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.ProjectAgentName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class CreateIntentRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ProjectAgentName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ProjectAgentName ParentAsProjectAgentName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.ProjectAgentName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class CreateSessionEntityTypeRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.SessionName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.SessionName ParentAsSessionName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.SessionName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class DeleteAllContextsRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.SessionName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.SessionName ParentAsSessionName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.SessionName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class DeleteContextRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ContextName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ContextName ContextName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.ContextName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class DeleteEntityTypeRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.EntityTypeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.EntityTypeName EntityTypeName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.EntityTypeName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class DeleteIntentRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.IntentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.IntentName IntentName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.IntentName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class DeleteSessionEntityTypeRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.SessionEntityTypeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.SessionEntityTypeName SessionEntityTypeName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.SessionEntityTypeName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class DetectIntentRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.SessionName"/>-typed view over the <see cref="Session"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.SessionName SessionAsSessionName { get { return string.IsNullOrEmpty(Session) ? null : Google.Cloud.Dialogflow.V2.SessionName.Parse(Session); } set { Session = value != null ? value.ToString() : ""; } } } public partial class EntityType { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.EntityTypeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.EntityTypeName EntityTypeName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.EntityTypeName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class ExportAgentRequest { /// <summary> /// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gaxres::ProjectName ParentAsProjectName { get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class GetAgentRequest { /// <summary> /// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gaxres::ProjectName ParentAsProjectName { get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class GetContextRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ContextName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ContextName ContextName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.ContextName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class GetEntityTypeRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.EntityTypeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.EntityTypeName EntityTypeName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.EntityTypeName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class GetIntentRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.IntentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.IntentName IntentName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.IntentName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class GetSessionEntityTypeRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.SessionEntityTypeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.SessionEntityTypeName SessionEntityTypeName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.SessionEntityTypeName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class ImportAgentRequest { /// <summary> /// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gaxres::ProjectName ParentAsProjectName { get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class Intent { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.IntentName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.IntentName IntentName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.IntentName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class ListContextsRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.SessionName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.SessionName ParentAsSessionName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.SessionName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class ListEntityTypesRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ProjectAgentName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ProjectAgentName ParentAsProjectAgentName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.ProjectAgentName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class ListIntentsRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.ProjectAgentName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.ProjectAgentName ParentAsProjectAgentName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.ProjectAgentName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class ListSessionEntityTypesRequest { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.SessionName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.SessionName ParentAsSessionName { get { return string.IsNullOrEmpty(Parent) ? null : Google.Cloud.Dialogflow.V2.SessionName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class RestoreAgentRequest { /// <summary> /// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gaxres::ProjectName ParentAsProjectName { get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class SearchAgentsRequest { /// <summary> /// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gaxres::ProjectName ParentAsProjectName { get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } public partial class SessionEntityType { /// <summary> /// <see cref="Google.Cloud.Dialogflow.V2.SessionEntityTypeName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public Google.Cloud.Dialogflow.V2.SessionEntityTypeName SessionEntityTypeName { get { return string.IsNullOrEmpty(Name) ? null : Google.Cloud.Dialogflow.V2.SessionEntityTypeName.Parse(Name); } set { Name = value != null ? value.ToString() : ""; } } } public partial class TrainAgentRequest { /// <summary> /// <see cref="gaxres::ProjectName"/>-typed view over the <see cref="Parent"/> resource name property. /// </summary> public gaxres::ProjectName ParentAsProjectName { get { return string.IsNullOrEmpty(Parent) ? null : gaxres::ProjectName.Parse(Parent); } set { Parent = value != null ? value.ToString() : ""; } } } }
// 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.Concurrent; using System.Diagnostics; using System.Globalization; using System.IO; using System.Threading; using System.Threading.Tasks; using Microsoft.NodejsTools.Debugger.Commands; using Microsoft.NodejsTools.Debugger.Events; using Microsoft.VisualStudioTools.Project; using Newtonsoft.Json.Linq; namespace Microsoft.NodejsTools.Debugger.Communication { internal sealed class DebuggerClient : IDebuggerClient { private readonly IDebuggerConnection _connection; private ConcurrentDictionary<int, TaskCompletionSource<JObject>> _messages = new ConcurrentDictionary<int, TaskCompletionSource<JObject>>(); private readonly static Newtonsoft.Json.JsonSerializerSettings jsonSettings = new Newtonsoft.Json.JsonSerializerSettings() { DateParseHandling = Newtonsoft.Json.DateParseHandling.None }; public DebuggerClient(IDebuggerConnection connection) { Utilities.ArgumentNotNull("connection", connection); this._connection = connection; this._connection.OutputMessage += this.OnOutputMessage; this._connection.ConnectionClosed += this.OnConnectionClosed; } /// <summary> /// Send a command to debugger. /// </summary> /// <param name="command">Command.</param> /// <param name="cancellationToken">Cancellation token.</param> public async Task SendRequestAsync(DebuggerCommand command, CancellationToken cancellationToken = new CancellationToken()) { cancellationToken.ThrowIfCancellationRequested(); try { var promise = this._messages.GetOrAdd(command.Id, i => new TaskCompletionSource<JObject>()); this._connection.SendMessage(command.ToString()); cancellationToken.ThrowIfCancellationRequested(); cancellationToken.Register(() => promise.TrySetCanceled(), false); var response = await promise.Task.ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); command.ProcessResponse(response); } finally { TaskCompletionSource<JObject> promise; this._messages.TryRemove(command.Id, out promise); } } /// <summary> /// Execudes the provided code, and catches any expected exceptions that may arise from direct or indirect use of <see cref="DebuggerClient.SendRequestAsync"/>. /// (in particular, when the connection is shut down, or is forcibly dropped from the other end). /// </summary> /// <remarks> /// This is intended to be used primarily with fire-and-forget async void methods that run on threadpool threads and cannot leak those exceptions /// without crashing the process. /// </remarks> public static async void RunWithRequestExceptionsHandled(Func<Task> action) { try { await action().ConfigureAwait(false); } catch (IOException) { } catch (OperationCanceledException) { } } /// <summary> /// Break point event handler. /// </summary> public event EventHandler<BreakpointEventArgs> BreakpointEvent; /// <summary> /// Compile script event handler. /// </summary> public event EventHandler<CompileScriptEventArgs> CompileScriptEvent; /// <summary> /// Exception event handler. /// </summary> public event EventHandler<ExceptionEventArgs> ExceptionEvent; /// <summary> /// Handles disconnect from debugger. /// </summary> /// <param name="sender">Sender.</param> /// <param name="e">Event arguments.</param> private void OnConnectionClosed(object sender, EventArgs e) { var messages = Interlocked.Exchange(ref this._messages, new ConcurrentDictionary<int, TaskCompletionSource<JObject>>()); foreach (var kv in messages) { var exception = new IOException(Resources.DebuggerConnectionClosed); kv.Value.SetException(exception); } messages.Clear(); } /// <summary> /// Process message from debugger connection. /// </summary> /// <param name="sender">Sender.</param> /// <param name="args">Event arguments.</param> private void OnOutputMessage(object sender, MessageEventArgs args) { var message = Newtonsoft.Json.JsonConvert.DeserializeObject<JObject>(args.Message, jsonSettings); var messageType = (string)message["type"]; switch (messageType) { case "event": HandleEventMessage(message); break; case "response": HandleResponseMessage(message); break; default: Debug.Fail(string.Format(CultureInfo.CurrentCulture, "Unrecognized type '{0}' in message: {1}", messageType, message)); break; } } /// <summary> /// Handles event message. /// </summary> /// <param name="message">Message.</param> private void HandleEventMessage(JObject message) { var eventType = (string)message["event"]; switch (eventType) { case "afterCompile": EventHandler<CompileScriptEventArgs> compileScriptHandler = CompileScriptEvent; if (compileScriptHandler != null) { var compileScriptEvent = new CompileScriptEvent(message); compileScriptHandler(this, new CompileScriptEventArgs(compileScriptEvent)); } break; case "break": EventHandler<BreakpointEventArgs> breakpointHandler = BreakpointEvent; if (breakpointHandler != null) { var breakpointEvent = new BreakpointEvent(message); breakpointHandler(this, new BreakpointEventArgs(breakpointEvent)); } break; case "exception": EventHandler<ExceptionEventArgs> exceptionHandler = ExceptionEvent; if (exceptionHandler != null) { var exceptionEvent = new ExceptionEvent(message); exceptionHandler(this, new ExceptionEventArgs(exceptionEvent)); } break; case "beforeCompile": case "breakForCommand": case "newFunction": case "scriptCollected": case "compileError": break; default: Debug.Fail(string.Format(CultureInfo.CurrentCulture, "Unrecognized type '{0}' in event message: {1}", eventType, message)); break; } } /// <summary> /// Handles response message. /// </summary> /// <param name="message">Message.</param> private void HandleResponseMessage(JObject message) { var messageId = message["request_seq"]; TaskCompletionSource<JObject> promise; if (messageId != null && _messages.TryGetValue((int)messageId, out promise)) { promise.SetResult(message); } else { Debug.Fail(string.Format(CultureInfo.CurrentCulture, "Invalid response identifier '{0}'", messageId ?? "<null>")); } } } }
using System; using System.Collections.Generic; using System.Text; namespace Morph.SimpleLink { public class CC3000_API { [clrcore.Import("_wlan_init_wrapper"), clrcore.CallingConvention("cdecl")] public unsafe static void wlan_init() { } [clrcore.Import("_wlan_start"), clrcore.CallingConvention("cdecl")] public unsafe static void wlan_start(ushort usPatchesAvailableAtHost) { } [clrcore.Import("_wlan_stop"), clrcore.CallingConvention("cdecl")] public unsafe static void wlan_stop() { } [clrcore.Import("_wlan_connect"), clrcore.CallingConvention("cdecl")] public unsafe static long wlan_connect(ulong ulSecType, char* ssid, long ssid_len, byte* bssid, byte* key, long key_len) { return 0; } [clrcore.Import("_wlan_is_connected"), clrcore.CallingConvention("cdecl")] public unsafe static ulong wlan_is_connected() { return 0; } [clrcore.Import("_wlan_is_dhcp"), clrcore.CallingConvention("cdecl")] public unsafe static ulong wlan_is_dhcp() { return 0; } [clrcore.Import("_wlan_disconnect"), clrcore.CallingConvention("cdecl")] public unsafe static long wlan_disconnect() { return 0; } //[clrcore.Import("_wlan_add_profile"), clrcore.CallingConvention("cdecl")] //public unsafe static long wlan_add_profile(ulong ulSecType, char* ucSsid, // ulong ulSsidLen, // char* ucBssid, // ulong ulPriority, // ulong ulPairwiseCipher_Or_Key, // ulong ulGroupCipher_TxKeyLen, // ulong ulKeyMgmt, // char* ucPf_OrKey, // ulong ulPassPhraseLen) { return 0; } //[clrcore.Import("_wlan_ioctl_del_profile"), clrcore.CallingConvention("cdecl")] //public unsafe static long wlan_ioctl_del_profile(ulong ulIndex) { return 0; } //[clrcore.Import("_wlan_set_event_mask"), clrcore.CallingConvention("cdecl")] //public unsafe static long wlan_set_event_mask(ulong ulMask) { return 0; } [clrcore.Import("_wlan_ioctl_statusget"), clrcore.CallingConvention("cdecl")] public unsafe static long wlan_ioctl_statusget() { return 0; } //[clrcore.Import("_wlan_ioctl_set_connection_policy"), clrcore.CallingConvention("cdecl")] //public unsafe static long wlan_ioctl_set_connection_policy( // ulong should_connect_to_open_ap, // ulong should_use_fast_connect, // ulong ulUseProfiles) { return 0; } [clrcore.Import("_wlan_ioctl_get_scan_results"), clrcore.CallingConvention("cdecl")] public unsafe static long wlan_ioctl_get_scan_results(ulong ulScanTimeout, char* ucResults) { return 0; } [clrcore.Import("_wlan_ioctl_set_scan_params"), clrcore.CallingConvention("cdecl")] public unsafe static long wlan_ioctl_set_scan_params(ulong uiEnable, ulong uiMinDwellTime, ulong uiMaxDwellTime, ulong uiNumOfProbeResponces, ulong uiChannelMask, long iRSSIThreshold, ulong uiSNRThreshold, ulong uiDefaultTxPower, ulong* aiIntervalList) { return 0; } //[clrcore.Import("_wlan_first_time_config_start"), clrcore.CallingConvention("cdecl")] //public unsafe static long wlan_first_time_config_start() { return 0; } //[clrcore.Import("_wlan_first_time_config_stop"), clrcore.CallingConvention("cdecl")] //public unsafe static long wlan_first_time_config_stop() { return 0; } //[clrcore.Import("_wlan_first_time_config_set_prefix"), clrcore.CallingConvention("cdecl")] //public unsafe static long wlan_first_time_config_set_prefix(char* cNewPrefix) { return 0; } } public class CC3000_Socket_API { public struct sockaddr { public ushort sa_family; public unsafe fixed char sa_data[14]; } public struct sockaddr_in { public short sin_family; // e.g. AF_INET public ushort sin_port; // e.g. htons(3490) public ulong sin_addr; // see struct in_addr, below public unsafe fixed char sin_zero[8]; // zero this if you want to } public struct fd_set { public unsafe fixed long fds_bits[1]; //__FD_SETSIZE / __NFDBITS = 1 } public struct timeval { public long tv_sec; /* seconds */ public long tv_usec; /* microseconds */ } [clrcore.Import("_socket"), clrcore.CallingConvention("cdecl")] public unsafe static int socket(long domain, long type, long protocol) { return 0; } [clrcore.Import("_closesocket"), clrcore.CallingConvention("cdecl")] public unsafe static long closesocket(long sd) { return 0; } [clrcore.Import("_accept"), clrcore.CallingConvention("cdecl")] public unsafe static long accept(long sd, void* addr, ulong* addrlen) { return 0; } [clrcore.Import("_bind"), clrcore.CallingConvention("cdecl")] public unsafe static long bind(long sd, void* addr, long addrlen) { return 0; } [clrcore.Import("_listen"), clrcore.CallingConvention("cdecl")] public unsafe static long listen(long sd, long backlog) { return 0; } [clrcore.Import("_connect"), clrcore.CallingConvention("cdecl")] public unsafe static long connect(long sd, void* addr, long addrlen) { return 0; } [clrcore.Import("_select"), clrcore.CallingConvention("cdecl")] public unsafe static int select(long nfds, void* readsds, void* writesds, void* exceptsds, void* timeout) { return 0; } [clrcore.Import("_setsockopt"), clrcore.CallingConvention("cdecl")] public unsafe static int setsockopt(long sd, long level, long optname, void* optval, ulong optlen) { return 0; } [clrcore.Import("_getsockopt"), clrcore.CallingConvention("cdecl")] public unsafe static int getsockopt(long sd, long level, long optname, void* optval, ulong* optlen) { return 0; } [clrcore.Import("_recv"), clrcore.CallingConvention("cdecl")] public unsafe static int recv(long sd, void* buf, long len, long flags) { return 0; } [clrcore.Import("_recvfrom"), clrcore.CallingConvention("cdecl")] public unsafe static int recvfrom(long sd, void* buf, long len, long flags, sockaddr* from, ulong* fromlen) { return 0; } [clrcore.Import("_send"), clrcore.CallingConvention("cdecl")] public unsafe static int send(long sd, void* buf, long len, long flags) { return 0; } [clrcore.Import("_sendto"), clrcore.CallingConvention("cdecl")] public unsafe static int sendto(long sd, void* buf, long len, long flags, void* to, ulong tolen) { return 0; } [clrcore.Import("_resolve_hostname"), clrcore.CallingConvention("cdecl")] public unsafe static int resolve_hostname(char* hostname, ushort usNameLen, ulong* out_ip_addr) { return 0; } } }
// Copyright (c) 2017 Jan Pluskal, Viliam Letavay // //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. /** * Autogenerated by Thrift Compiler (0.9.3) * * DO NOT EDIT UNLESS YOU ARE SURE THAT YOU KNOW WHAT YOU ARE DOING * @generated */ using System; using System.Text; using Thrift.Protocol; namespace Netfox.SnooperMessenger.Protocol { #if !SILVERLIGHT [Serializable] #endif public partial class MNMessagesSyncDeltaRTCEventLog : TBase { private MNMessagesSyncMessageMetadata _MessageMetadata; private bool _Answered; private long _StartTime; private long _Duration; private int _EventType; public MNMessagesSyncMessageMetadata MessageMetadata { get { return _MessageMetadata; } set { __isset.MessageMetadata = true; this._MessageMetadata = value; } } public bool Answered { get { return _Answered; } set { __isset.Answered = true; this._Answered = value; } } public long StartTime { get { return _StartTime; } set { __isset.StartTime = true; this._StartTime = value; } } public long Duration { get { return _Duration; } set { __isset.Duration = true; this._Duration = value; } } public int EventType { get { return _EventType; } set { __isset.EventType = true; this._EventType = value; } } public Isset __isset; #if !SILVERLIGHT [Serializable] #endif public struct Isset { public bool MessageMetadata; public bool Answered; public bool StartTime; public bool Duration; public bool EventType; } public MNMessagesSyncDeltaRTCEventLog() { } public void Read (TProtocol iprot) { iprot.IncrementRecursionDepth(); try { TField field; iprot.ReadStructBegin(); while (true) { field = iprot.ReadFieldBegin(); if (field.Type == TType.Stop) { break; } switch (field.ID) { case 1: if (field.Type == TType.Struct) { MessageMetadata = new MNMessagesSyncMessageMetadata(); MessageMetadata.Read(iprot); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 2: if (field.Type == TType.Bool) { Answered = iprot.ReadBool(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 3: if (field.Type == TType.I64) { StartTime = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 4: if (field.Type == TType.I64) { Duration = iprot.ReadI64(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; case 5: if (field.Type == TType.I32) { EventType = iprot.ReadI32(); } else { TProtocolUtil.Skip(iprot, field.Type); } break; default: TProtocolUtil.Skip(iprot, field.Type); break; } iprot.ReadFieldEnd(); } iprot.ReadStructEnd(); } finally { iprot.DecrementRecursionDepth(); } } public void Write(TProtocol oprot) { oprot.IncrementRecursionDepth(); try { TStruct struc = new TStruct("MNMessagesSyncDeltaRTCEventLog"); oprot.WriteStructBegin(struc); TField field = new TField(); if (MessageMetadata != null && __isset.MessageMetadata) { field.Name = "MessageMetadata"; field.Type = TType.Struct; field.ID = 1; oprot.WriteFieldBegin(field); MessageMetadata.Write(oprot); oprot.WriteFieldEnd(); } if (__isset.Answered) { field.Name = "Answered"; field.Type = TType.Bool; field.ID = 2; oprot.WriteFieldBegin(field); oprot.WriteBool(Answered); oprot.WriteFieldEnd(); } if (__isset.StartTime) { field.Name = "StartTime"; field.Type = TType.I64; field.ID = 3; oprot.WriteFieldBegin(field); oprot.WriteI64(StartTime); oprot.WriteFieldEnd(); } if (__isset.Duration) { field.Name = "Duration"; field.Type = TType.I64; field.ID = 4; oprot.WriteFieldBegin(field); oprot.WriteI64(Duration); oprot.WriteFieldEnd(); } if (__isset.EventType) { field.Name = "EventType"; field.Type = TType.I32; field.ID = 5; oprot.WriteFieldBegin(field); oprot.WriteI32(EventType); oprot.WriteFieldEnd(); } oprot.WriteFieldStop(); oprot.WriteStructEnd(); } finally { oprot.DecrementRecursionDepth(); } } public override string ToString() { StringBuilder __sb = new StringBuilder("MNMessagesSyncDeltaRTCEventLog("); bool __first = true; if (MessageMetadata != null && __isset.MessageMetadata) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("MessageMetadata: "); __sb.Append(MessageMetadata== null ? "<null>" : MessageMetadata.ToString()); } if (__isset.Answered) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Answered: "); __sb.Append(Answered); } if (__isset.StartTime) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("StartTime: "); __sb.Append(StartTime); } if (__isset.Duration) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("Duration: "); __sb.Append(Duration); } if (__isset.EventType) { if(!__first) { __sb.Append(", "); } __first = false; __sb.Append("EventType: "); __sb.Append(EventType); } __sb.Append(")"); return __sb.ToString(); } } }
/* ==================================================================== Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for Additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ==================================================================== */ namespace NPOI.DDF { using System; using System.IO; using System.Text; using System.Collections; using NPOI.Util; using System.Collections.Generic; /// <summary> /// Escher container records store other escher records as children. /// The container records themselves never store any information beyond /// the standard header used by all escher records. This one record is /// used to represent many different types of records. /// @author Glen Stampoultzis /// </summary> internal class EscherContainerRecord : EscherRecord { public const short DGG_CONTAINER = unchecked((short)0xF000); public const short BSTORE_CONTAINER = unchecked((short)0xF001); public const short DG_CONTAINER = unchecked((short)0xF002); public const short SPGR_CONTAINER = unchecked((short)0xF003); public const short SP_CONTAINER = unchecked((short)0xF004); public const short SOLVER_CONTAINER = unchecked((short)0xF005); private List<EscherRecord> childRecords = new List<EscherRecord>(); /// <summary> /// The contract of this method is to deSerialize an escher record including /// it's children. /// </summary> /// <param name="data">The byte array containing the Serialized escher /// records.</param> /// <param name="offset">The offset into the byte array.</param> /// <param name="recordFactory">A factory for creating new escher records</param> /// <returns>The number of bytes written.</returns> public override int FillFields(byte[] data, int offset, EscherRecordFactory recordFactory) { int bytesRemaining = ReadHeader(data, offset); int bytesWritten = 8; offset += 8; while (bytesRemaining > 0 && offset < data.Length) { EscherRecord child = recordFactory.CreateRecord(data, offset); int childBytesWritten = child.FillFields(data, offset, recordFactory); bytesWritten += childBytesWritten; offset += childBytesWritten; bytesRemaining -= childBytesWritten; AddChildRecord(child); if (offset >= data.Length && bytesRemaining > 0) { Console.WriteLine("WARNING: " + bytesRemaining + " bytes remaining but no space left"); } } return bytesWritten; } /// <summary> /// Serializes to an existing byte array without serialization listener. /// This is done by delegating to Serialize(int, byte[], EscherSerializationListener). /// </summary> /// <param name="offset">the offset within the data byte array.</param> /// <param name="data"> the data array to Serialize to.</param> /// <param name="listener">a listener for begin and end serialization events.</param> /// <returns>The number of bytes written.</returns> public override int Serialize(int offset, byte[] data, EscherSerializationListener listener) { listener.BeforeRecordSerialize(offset, RecordId, this); LittleEndian.PutShort(data, offset, Options); LittleEndian.PutShort(data, offset + 2, RecordId); int remainingBytes = 0; for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord r = (EscherRecord)iterator.Current; remainingBytes += r.RecordSize; } LittleEndian.PutInt(data, offset + 4, remainingBytes); int pos = offset + 8; for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord r = (EscherRecord)iterator.Current; pos += r.Serialize(pos, data,listener); } listener.AfterRecordSerialize(pos, RecordId, pos - offset, this); return pos - offset; } /// <summary> /// Subclasses should effeciently return the number of bytes required to /// Serialize the record. /// </summary> /// <value>number of bytes</value> public override int RecordSize { get { int childRecordsSize = 0; for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord r = (EscherRecord)iterator.Current; childRecordsSize += r.RecordSize; } return 8 + childRecordsSize; } } /// <summary> /// Do any of our (top level) children have the /// given recordId? /// </summary> /// <param name="recordId">The record id.</param> /// <returns> /// <c>true</c> if [has child of type] [the specified record id]; otherwise, <c>false</c>. /// </returns> public bool HasChildOfType(short recordId) { for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord r = (EscherRecord)iterator.Current; if (r.RecordId == recordId) { return true; } } return false; } /// <summary> /// Returns a list of all the child (escher) records /// of the container. /// </summary> /// <value></value> public override List<EscherRecord> ChildRecords { get { return new List<EscherRecord>(childRecords); } set { if (value == childRecords) { throw new InvalidOperationException("Child records private data member has escaped"); } childRecords.Clear(); childRecords.AddRange(value); } } public bool RemoveChildRecord(EscherRecord toBeRemoved) { return childRecords.Remove(toBeRemoved); } public List<EscherRecord>.Enumerator GetChildIterator() { return childRecords.GetEnumerator(); } /// <summary> /// Returns all of our children which are also /// EscherContainers (may be 0, 1, or vary rarely /// 2 or 3) /// </summary> /// <value>The child containers.</value> public IList<EscherContainerRecord> ChildContainers { get { IList<EscherContainerRecord> containers = new List<EscherContainerRecord>(); for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord r = (EscherRecord)iterator.Current; if (r is EscherContainerRecord) { containers.Add((EscherContainerRecord)r); } } return containers; } } /// <summary> /// Subclasses should return the short name for this escher record. /// </summary> /// <value></value> public override String RecordName { get { switch ((short)RecordId) { case DGG_CONTAINER: return "DggContainer"; case BSTORE_CONTAINER: return "BStoreContainer"; case DG_CONTAINER: return "DgContainer"; case SPGR_CONTAINER: return "SpgrContainer"; case SP_CONTAINER: return "SpContainer"; case SOLVER_CONTAINER: return "SolverContainer"; default: return "Container 0x" + HexDump.ToHex(RecordId); } } } /// <summary> /// The display methods allows escher variables to print the record names /// according to their hierarchy. /// </summary> /// <param name="indent">The current indent level.</param> public override void Display(int indent) { base.Display(indent); for (IEnumerator iterator = childRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord escherRecord = (EscherRecord)iterator.Current; escherRecord.Display(indent + 1); } } /// <summary> /// Adds the child record. /// </summary> /// <param name="record">The record.</param> public void AddChildRecord(EscherRecord record) { this.childRecords.Add(record); } /// <summary> /// Returns a <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </summary> /// <returns> /// A <see cref="T:System.String"/> that represents the current <see cref="T:System.Object"/>. /// </returns> public override string ToString() { return ToString(""); } /// <summary> /// Toes the string. /// </summary> /// <param name="indent">The indent.</param> /// <returns></returns> public String ToString(String indent) { String nl = Environment.NewLine; StringBuilder children = new StringBuilder(); if (ChildRecords.Count> 0) { children.Append(" children: " + nl); int count = 0; for (IEnumerator iterator = ChildRecords.GetEnumerator(); iterator.MoveNext(); ) { String newIndent = indent + " "; EscherRecord record = (EscherRecord)iterator.Current; children.Append(newIndent + "Child " + count + ":" + nl); if (record is EscherContainerRecord) { EscherContainerRecord ecr = (EscherContainerRecord)record; children.Append(ecr.ToString(newIndent)); } else { children.Append(record.ToString()); } count++; } } return indent + this.GetType().Name + " (" + RecordName + "):" + nl + indent + " isContainer: " + IsContainerRecord + nl + indent + " options: 0x" + HexDump.ToHex(Options) + nl + indent + " recordId: 0x" + HexDump.ToHex(RecordId) + nl + indent + " numchildren: " + ChildRecords.Count + nl + indent + children.ToString(); } /// <summary> /// Gets the child by id. /// </summary> /// <param name="recordId">The record id.</param> /// <returns></returns> public EscherSpRecord GetChildById(short recordId) { for (IEnumerator iterator = childRecords.GetEnumerator(); iterator.MoveNext(); ) { EscherRecord escherRecord = (EscherRecord)iterator.Current; if (escherRecord.RecordId == recordId) return (EscherSpRecord)escherRecord; } return null; } /// <summary> /// Recursively find records with the specified record ID /// </summary> /// <param name="recordId"></param> /// <param name="out1">list to store found records</param> public void GetRecordsById(short recordId, ref ArrayList out1) { for (IEnumerator it = ChildRecords.GetEnumerator(); it.MoveNext(); ) { Object er = it.Current; EscherRecord r = (EscherRecord)er; if (r is EscherContainerRecord) { EscherContainerRecord c = (EscherContainerRecord)r; c.GetRecordsById(recordId, ref out1); } else if (r.RecordId == recordId) { out1.Add(er); } } } } }
//! \file ImagePGX.cs //! \date Tue Dec 08 02:50:45 2015 //! \brief Glib2 image format. // // Copyright (C) 2015 by morkt // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. // using GameRes.Utility; using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.Drawing; using System.IO; using System.Linq; using System.Windows.Media; namespace GameRes.Formats.Glib2 { internal class PgxMetaData : ImageMetaData { public int PackedSize; public int Flags; } internal class StxLayerInfo { public string Path; public Rectangle? Rect; public string Effect; public int Blend; } [Export(typeof(ImageFormat))] public class PgxFormat : ImageFormat { public override string Tag { get { return "PGX"; } } public override string Description { get { return "Glib2 engine image format"; } } public override uint Signature { get { return 0x00584750; } } // 'PGX' static readonly InfoReader InfoCache = new InfoReader(); public override ImageMetaData ReadMetaData (IBinaryStream stream) { var header = stream.ReadHeader (0x18); return new PgxMetaData { Width = header.ToUInt32 (8), Height = header.ToUInt32 (12), BPP = (header.ToInt16 (0x10) & 1) == 0 ? 24 : 32, PackedSize = header.ToInt32 (0x14), Flags = header.ToUInt16 (0x12), }; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { var meta = (PgxMetaData)info; stream.Position = 0x20; if (0 != (meta.Flags & 0x1000)) { ReadGms (stream); } PixelFormat format = 32 == meta.BPP ? PixelFormats.Bgra32 : PixelFormats.Bgr32; int stride = (int)meta.Width * 4; var pixels = new byte[stride * (int)meta.Height]; // stream.Seek (-meta.PackedSize, SeekOrigin.End); LzssUnpack (stream, pixels); var layer = InfoCache.GetInfo (info.FileName); if (null != layer && null != layer.Rect) { info.OffsetX = layer.Rect.Value.X; info.OffsetY = layer.Rect.Value.Y; } return ImageData.Create (info, format, null, pixels); } void ReadGms (IBinaryStream input) { var header = new byte[0x10]; if (0x10 != input.Read (header, 0, 0x10)) throw new EndOfStreamException(); byte swap = header[13]; header[13] = header[9]; header[9] = swap; swap = header[15]; header[15] = header[11]; header[11] = swap; swap = header[4]; header[4] = header[8]; header[8] = swap; swap = header[6]; header[6] = header[10]; header[10] = swap; int unpacked_size = LittleEndian.ToInt32 (header, 12); var gms_info = new byte[unpacked_size]; LzssUnpack (input, gms_info); // foreach (byte in gms_info) byte ^= 0xFF // decrypted array contains image meta data (see InfoReader class) } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("PgxFormat.Write not implemented"); } static void LzssUnpack (IBinaryStream input, byte[] output) { GLib.GOpener.LzssUnpack (input.AsStream, output); } } internal class InfoReader { string m_last_info_dir; Dictionary<string, StxLayerInfo> m_layer_map; internal class StxEntry { public string FullName; public string Name; public int Attr; public uint InfoOffset; public uint InfoSize; } public StxLayerInfo GetInfo (string image_name) { try { var info_name = VFS.CombinePath (VFS.GetDirectoryName (image_name), "info"); if (!VFS.FileExists (info_name)) return null; if (string.IsNullOrEmpty (m_last_info_dir) || string.Join (":", VFS.FullPath) != m_last_info_dir) ParseInfo (info_name); var layer_name = Path.GetFileName (image_name); return GetLayerInfo (layer_name); } catch (Exception X) { Trace.WriteLine (X.Message, "[Glib2] STX parse error"); return null; } } StxLayerInfo GetLayerInfo (string layer_name) { if (null == m_layer_map) return null; StxLayerInfo info; m_layer_map.TryGetValue (layer_name, out info); return info; } void ParseInfo (string info_name) { if (null == m_layer_map) m_layer_map = new Dictionary<string, StxLayerInfo>(); else m_layer_map.Clear(); using (var info = VFS.OpenView (info_name)) { if (!info.View.AsciiEqual (0, "CDBD")) return; int count = info.View.ReadInt32 (4); uint current_offset = 0x10; uint info_base = current_offset + info.View.ReadUInt32 (8); uint info_total_size = info.View.ReadUInt32 (12); info.View.Reserve (0, info_base+info_total_size); uint names_base = current_offset + (uint)count * 0x18; var dir = new List<StxEntry> (count); for (int i = 0; i < count; ++i) { uint name_offset = names_base + info.View.ReadUInt32 (current_offset); int parent_dir = info.View.ReadInt32 (current_offset+8); int attr = info.View.ReadInt32 (current_offset+0xC); uint info_offset = info.View.ReadUInt32 (current_offset+0x10); uint info_size = info.View.ReadUInt32 (current_offset+0x14); var name = info.View.ReadString (name_offset, info_base-name_offset); string path_name = name; if (parent_dir != -1) path_name = Path.Combine (dir[parent_dir].FullName, path_name); if (attr != -1 && info_size != 0) info_offset += info_base; var entry = new StxEntry { FullName = path_name, Name = name, Attr = attr, InfoOffset = info_offset, InfoSize = info_size, }; if (name == "filename" && parent_dir != -1 && info_size != 0) { uint filename_length = info.View.ReadUInt32 (info_offset); var filename = info.View.ReadString (info_offset+4, filename_length); m_layer_map[filename] = new StxLayerInfo { Path = dir[parent_dir].FullName + Path.DirectorySeparatorChar, }; } dir.Add (entry); current_offset += 0x18; } foreach (var layer in m_layer_map.Values) { foreach (var field in dir.Where (e => e.Attr != -1 && e.FullName.StartsWith (layer.Path))) { if ("rect" == field.Name && 0x14 == field.InfoSize) { int left = info.View.ReadInt32 (field.InfoOffset+4); int top = info.View.ReadInt32 (field.InfoOffset+8); int right = info.View.ReadInt32 (field.InfoOffset+12); int bottom = info.View.ReadInt32 (field.InfoOffset+16); layer.Rect = new Rectangle (left, top, right-left, bottom-top); } else if ("effect" == field.Name && field.InfoSize > 4) { // "norm" uint effect_length = info.View.ReadUInt32 (field.InfoOffset); layer.Effect = info.View.ReadString (field.InfoOffset+4, effect_length); if (layer.Effect != "norm") Trace.WriteLine (string.Format ("{0}: {1}effect = {2}", info_name, layer.Path, layer.Effect), "[Glib2.STX]"); } else if ("blend" == field.Name && 4 == field.InfoSize) { // 0xFF -> opaque layer.Blend = info.View.ReadInt32 (field.InfoOffset); if (layer.Blend != 0xFF) Trace.WriteLine (string.Format ("{0}: {1}blend = {2}", info_name, layer.Path, layer.Blend), "[Glib2.STX]"); } } } } m_last_info_dir = string.Join (":", VFS.FullPath); } } }
using AjaxControlToolkit.Design; using System; using System.ComponentModel; using System.Web.UI; using System.Web.UI.WebControls; namespace AjaxControlToolkit { /// <summary> /// TabPanel is a part of the TabContainer element. It can be used to organize page content. /// Each TabPanel defines its HeaderText or HeaderTemplate as well as the ContentTemplate that /// defines its content.The most recent tab should remain selected after a postback, and the /// Enabled state of tabs should be preserved after a postback. /// </summary> [RequiredScript(typeof(CommonToolkitScripts))] [RequiredScript(typeof(DynamicPopulateExtender))] [RequiredScript(typeof(TabContainer))] [ClientCssResource(Constants.TabsName)] [ClientScriptResource("Sys.Extended.UI.TabPanel", Constants.TabsName)] [ToolboxItem(false)] [Designer(typeof(TabPanelDesigner))] public class TabPanel : ScriptControlBase { bool _active; ITemplate _contentTemplate; ITemplate _headerTemplate; TabContainer _owner; Control _headerControl; public TabPanel() : base(false, HtmlTextWriterTag.Div) { } /// <summary> /// Text to display in the tab /// </summary> /// <remarks>This property renders HTML to a page. /// Encode this property value as a plain text if the source of the value is not trusted to avoid XSS attacks</remarks> [DefaultValue("")] [Category("Appearance")] [ClientPropertyName("headerText")] public string HeaderText { get { return (string)(ViewState["HeaderText"] ?? string.Empty); } set { ViewState["HeaderText"] = value; } } /// <summary> /// TemplateInstance.Single ITemplate to use to render the header /// </summary> [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateInstance(TemplateInstance.Single)] [Browsable(false)] [MergableProperty(false)] public ITemplate HeaderTemplate { get { return _headerTemplate; } set { _headerTemplate = value; } } /// <summary> /// TemplateInstance.Single ITemplate to use for rendering the body /// </summary> [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateInstance(TemplateInstance.Single)] [Browsable(false)] [MergableProperty(false)] public ITemplate ContentTemplate { get { return _contentTemplate; } set { _contentTemplate = value; } } /// <summary> /// Determines whether or not to display a tab for the TabPanel by default /// </summary> /// <remarks> /// This can be changed on the client side /// </remarks> [DefaultValue(true)] [Category("Behavior")] [ExtenderControlProperty] [ClientPropertyName("enabled")] public override bool Enabled { get { return base.Enabled; } set { base.Enabled = value; } } /// <summary> /// Detemines whether or not to display scrollbars (None, Horizontal, Vertical, Both, Auto) /// in the body of the TabPanel /// </summary> [DefaultValue(ScrollBars.None)] [Category("Behavior")] [ExtenderControlProperty] [ClientPropertyName("scrollBars")] public ScrollBars ScrollBars { get { return (ScrollBars)(ViewState["ScrollBars"] ?? ScrollBars.None); } set { ViewState["ScrollBars"] = value; } } /// <summary> /// The name of a JavaScript function to attach to the tab's client-side Click event /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("click")] public string OnClientClick { get { return (string)(ViewState["OnClientClick"] ?? string.Empty); } set { ViewState["OnClientClick"] = value; } } /// <summary> /// The URL of the web service to call /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlProperty] [ClientPropertyName("dynamicServicePath")] [UrlProperty] public string DynamicServicePath { get { return (string)(ViewState["DynamicServicePath"] ?? string.Empty); } set { ViewState["DynamicServicePath"] = value; } } /// <summary> /// The name of a method to call on the page or web service /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlProperty] [ClientPropertyName("dynamicServiceMethod")] public string DynamicServiceMethod { get { return (string)(ViewState["DynamicServiceMethod"] ?? string.Empty); } set { ViewState["DynamicServiceMethod"] = value; } } /// <summary> /// An arbitrary string value to be passed to the dynamically populated Web method /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlProperty] [ClientPropertyName("dynamicContextKey")] public string DynamicContextKey { get { return (string)(ViewState["DynamicContextKey"] ?? string.Empty); } set { ViewState["DynamicContextKey"] = value; } } /// <summary> /// Determines whether or not to load a tab (Always, Once, None) when the container's onDemand property is true /// </summary> [DefaultValue(OnDemandMode.Always)] [Category("Behavior")] [ExtenderControlProperty] [ClientPropertyName("onDemandMode")] public OnDemandMode OnDemandMode { get { return (OnDemandMode)(ViewState["OnDemandMode"] ?? OnDemandMode.Always); } set { ViewState["OnDemandMode"] = value; } } /// <summary> /// A handler to attach to the client-side populating event /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("populating")] public string OnClientPopulating { get { return (string)(ViewState["OnClientPopulating"] ?? string.Empty); } set { ViewState["OnClientPopulating"] = value; } } /// <summary> /// A handler to attach to the client-side populated event /// </summary> [DefaultValue("")] [Category("Behavior")] [ExtenderControlEvent] [ClientPropertyName("populated")] public string OnClientPopulated { get { return (string)(ViewState["OnClientPopulated"] ?? string.Empty); } set { ViewState["OnClientPopulated"] = value; } } internal bool Active { get { return _active; } set { _active = value; } } /// <summary> /// Introduces UpdatePanelID to the client side by prototyping it /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [ExtenderControlProperty] [ClientPropertyName("updatePanelID")] public string UpdatePanelID { get; set; } /// <summary> /// Determines the loading status of the tab in Once demand mode /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] [ExtenderControlProperty] [ClientPropertyName("wasLoadedOnce")] public bool WasLoadedOnce { get; set; } protected override void OnInit(EventArgs e) { base.OnInit(e); if(_headerTemplate != null) { _headerControl = new Control(); _headerTemplate.InstantiateIn(_headerControl); Controls.Add(_headerControl); } if(_contentTemplate == null) return; var c = new Control(); _contentTemplate.InstantiateIn(c); if(_owner.OnDemand && OnDemandMode != OnDemandMode.None) { var invisiblePanelID = ClientID + "_onDemandPanel"; var invisiblePanel = new Panel() { ID = invisiblePanelID, Visible = false }; invisiblePanel.Controls.Add(c); var updatePanel = new UpdatePanel() { ID = ClientID + "_updatePanel", UpdateMode = UpdatePanelUpdateMode.Conditional }; updatePanel.Load += UpdatePanelOnLoad; updatePanel.ContentTemplateContainer.Controls.Add(invisiblePanel); Controls.Add(updatePanel); UpdatePanelID = updatePanel.ClientID; } else { Controls.Add(c); } } void UpdatePanelOnLoad(object sender, EventArgs e) { if(!(sender is UpdatePanel)) return; var updatePanelID = (sender as UpdatePanel).ID; var tabID = updatePanelID.Substring(0, updatePanelID.Length - 12); if(!Active) return; var invisiblePanel = FindControl(tabID + "_onDemandPanel"); if(invisiblePanel != null && invisiblePanel is Panel) invisiblePanel.Visible = true; } protected internal virtual void RenderHeader(HtmlTextWriter writer) { writer.AddAttribute(HtmlTextWriterAttribute.Id, ClientID + "_tab"); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ajax__tab"); RenderBeginTag(writer); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ajax__tab_outer"); RenderBeginTag(writer); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ajax__tab_inner"); RenderBeginTag(writer); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ajax__tab_tab"); writer.AddAttribute(HtmlTextWriterAttribute.Id, "__tab_" + ClientID); writer.AddAttribute(HtmlTextWriterAttribute.Href, "#"); writer.AddStyleAttribute(HtmlTextWriterStyle.TextDecoration, "none"); if(_owner.UseVerticalStripPlacement) writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block"); writer.RenderBeginTag(HtmlTextWriterTag.A); RenderBeginTag(writer); if(_headerControl != null) { _headerControl.Visible = true; _headerControl.RenderControl(writer); _headerControl.Visible = false; } else { writer.Write(HeaderText); } writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); writer.RenderEndTag(); } public override void RenderBeginTag(HtmlTextWriter writer) { if(_owner.UseVerticalStripPlacement) writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "block"); writer.RenderBeginTag(HtmlTextWriterTag.Span); } protected override void Render(HtmlTextWriter writer) { if(_headerControl != null) _headerControl.Visible = false; base.AddAttributesToRender(writer); writer.AddAttribute(HtmlTextWriterAttribute.Class, "ajax__tab_panel"); if(!Active || !Enabled) { writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none"); writer.AddStyleAttribute(HtmlTextWriterStyle.Visibility, "hidden"); } writer.RenderBeginTag(HtmlTextWriterTag.Div); RenderChildren(writer); writer.RenderEndTag(); RegisterScriptDescriptors(); } protected virtual void RegisterScriptDescriptors() { ScriptManager.RegisterScriptDescriptors(this); } protected override void DescribeComponent(ScriptComponentDescriptor descriptor) { base.DescribeComponent(descriptor); descriptor.AddElementProperty("headerTab", "__tab_" + ClientID); if(_owner == null) return; descriptor.AddComponentProperty("owner", _owner.ClientID); descriptor.AddProperty("ownerID", _owner.ClientID); } internal void SetOwner(TabContainer owner) { _owner = owner; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Reflection; using System.Reflection.Emit; using System.Text; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using System.Web.Razor.Editor; using System.Web.Razor.Parser.SyntaxTree; using System.Web.Routing; using System.Xml.Linq; using BForms.Models; using BForms.Mvc; using BForms.Renderers; using BForms.Utilities; namespace BForms.Html { public static class SortableListExtensions { public static BsSortableListHtmlBuilder<TOrderModel> BsSortableListFor<TOrderModel>(this HtmlHelper helper, IEnumerable<TOrderModel> model, Expression<Func<TOrderModel, BsSortableListConfiguration<TOrderModel>>> config, Expression<Func<TOrderModel, HtmlProperties>> listProperties, Expression<Func<TOrderModel, HtmlProperties>> itemProperties, Expression<Func<TOrderModel, HtmlProperties>> labelProperties, Expression<Func<TOrderModel, HtmlProperties>> badgeProperties) { if (config == null) { throw new Exception("Configuration expression cannot be null"); } return new BsSortableListHtmlBuilder<TOrderModel>(model, helper.ViewContext, config, listProperties, itemProperties, labelProperties, badgeProperties); } public static BsSortableListHtmlBuilder<TOrderModel> BsSortableListFor<TOrderModel>(this HtmlHelper helper, IEnumerable<TOrderModel> model, Expression<Func<TOrderModel, BsSortableListConfiguration<TOrderModel>>> config) { return BsSortableListFor(helper, model, config, null, null, null, null); } public static BsSortableListHtmlBuilder<TOrderModel> BsSortableListFor<TOrderModel>(this HtmlHelper helper, IEnumerable<TOrderModel> model, Expression<Func<TOrderModel, BsSortableListConfiguration<TOrderModel>>> config, Expression<Func<TOrderModel, HtmlProperties>> listProperties) { return BsSortableListFor(helper, model, config, listProperties, null, null, null); } public static BsSortableListHtmlBuilder<TOrderModel> BsSortableListFor<TOrderModel>(this HtmlHelper helper, IEnumerable<TOrderModel> model, Expression<Func<TOrderModel, BsSortableListConfiguration<TOrderModel>>> config, Expression<Func<TOrderModel, HtmlProperties>> listProperties, Expression<Func<TOrderModel, HtmlProperties>> itemProperties) { return BsSortableListFor(helper, model, config, listProperties, itemProperties, null, null); } } public class SortableListItemWrapper { public TagBuilder LabelTag { get; set; } public TagBuilder ItemTag { get; set; } public TagBuilder BadgeTag { get; set; } /// <summary> /// @RootTag represents the tag which will wrap around any nested list /// </summary> public TagBuilder RootTag { get; set; } public List<SortableListItemWrapper> Children { get; set; } public SortableListItemWrapper(List<SortableListItemWrapper> children) { RootTag = new TagBuilder("ol"); ItemTag = new TagBuilder("li"); LabelTag = new TagBuilder("p"); BadgeTag = new TagBuilder("span"); Children = children; } public SortableListItemWrapper(TagBuilder root = null, TagBuilder item = null, TagBuilder label = null, TagBuilder badge = null, List<SortableListItemWrapper> children = null) { RootTag = root ?? new TagBuilder("ol"); ItemTag = item ?? new TagBuilder("li"); LabelTag = label ?? new TagBuilder("span"); BadgeTag = badge ?? new TagBuilder("span"); Children = children; } } public class HtmlProperties { public string Text { get; set; } public object HtmlAttributes { get; set; } public object DataAttributes { get; set; } public HtmlProperties() { Text = String.Empty; HtmlAttributes = new Dictionary<string, object>(); DataAttributes = new Dictionary<string, object>(); } public HtmlProperties(string text, IDictionary<string, object> htmlAttributes, IDictionary<string, object> dataAttributes) { Text = text; HtmlAttributes = htmlAttributes ?? new Dictionary<string, object>(); DataAttributes = dataAttributes ?? new Dictionary<string, object>(); } public HtmlProperties(string text, object htmlAttributes, object dataAttributes) { Text = text; HtmlAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(htmlAttributes); DataAttributes = HtmlHelper.AnonymousObjectToHtmlAttributes(dataAttributes); } } public class UnwrappedHtmlProperties { string Text { get; set; } public object HtmlAttributes { get; set; } public object DataAttributes { get; set; } } public class BsSortableListConfiguration<TModel> { public string Id { get; set; } public string Order { get; set; } public string Text { get; set; } // TODO : give this member a more sugestive name public Expression<Func<TModel, bool>> AppendsTo { get; set; } } public class BsSortableListHtmlBuilder<TModel> : BsBaseComponent { public SortableListItemWrapper List { get; set; } public IEnumerable<TModel> Model { get; set; } private IEnumerable<TModel> _reducedTree; public string ParentPropertyName = "ParentId"; private Dictionary<string, IEnumerable<string>> _permitedConnections; internal Dictionary<string, object> globalHtmlAttributes; internal Dictionary<string, object> globalDataAttributes; // Each of these expressions represents the last given configuration for a specific property // Storing them prevents erasing allready configured properties after each @List rebuilding private Expression<Func<TModel, BsSortableListConfiguration<TModel>>> _config; private Expression<Func<TModel, HtmlProperties>> _globalProperties; private Expression<Func<TModel, HtmlProperties>> _itemProperties; private Expression<Func<TModel, HtmlProperties>> _labelProperties; private Expression<Func<TModel, HtmlProperties>> _badgeProperties; private Expression<Func<TModel, HtmlProperties>> _emptyHtmlPropertiesExpression; public BsSortableListHtmlBuilder(IEnumerable<TModel> model, ViewContext viewContext, Expression<Func<TModel, BsSortableListConfiguration<TModel>>> config, Expression<Func<TModel, HtmlProperties>> globalProperties, Expression<Func<TModel, HtmlProperties>> itemProperties, Expression<Func<TModel, HtmlProperties>> labelProperties, Expression<Func<TModel, HtmlProperties>> badgeProperties) : base(viewContext) { Model = model; _emptyHtmlPropertiesExpression = x => new HtmlProperties(); _reducedTree = GetReducedTree(model); List = Build(model, config, globalProperties, itemProperties, labelProperties, badgeProperties); _config = config; _globalProperties = globalProperties ?? _emptyHtmlPropertiesExpression; _itemProperties = itemProperties ?? _emptyHtmlPropertiesExpression; _labelProperties = labelProperties ?? _emptyHtmlPropertiesExpression; _badgeProperties = badgeProperties ?? _emptyHtmlPropertiesExpression; globalHtmlAttributes = new Dictionary<string, object>(); globalDataAttributes = new Dictionary<string, object>() { { "migration-permited", true } }; } #region Build & Render private SortableListItemWrapper Build(IEnumerable<TModel> modelList, Expression<Func<TModel, BsSortableListConfiguration<TModel>>> config, Expression<Func<TModel, HtmlProperties>> globalProperties, Expression<Func<TModel, HtmlProperties>> itemProperties, Expression<Func<TModel, HtmlProperties>> labelProperties, Expression<Func<TModel, HtmlProperties>> badgeProperties) { var sortableListItemWrapper = new SortableListItemWrapper(); if (modelList != null && modelList.Any()) { sortableListItemWrapper.Children = new List<SortableListItemWrapper>(); _permitedConnections = GetPermitedConnections(_reducedTree, config); foreach (var item in modelList) { sortableListItemWrapper.Children.Add(Build(item, config, globalProperties, itemProperties, labelProperties, badgeProperties)); } } return sortableListItemWrapper; } private SortableListItemWrapper Build(TModel model, Expression<Func<TModel, BsSortableListConfiguration<TModel>>> config, Expression<Func<TModel, HtmlProperties>> globalProperties, Expression<Func<TModel, HtmlProperties>> itemProperties, Expression<Func<TModel, HtmlProperties>> labelProperties, Expression<Func<TModel, HtmlProperties>> badgeProperties) { var sortableListItemWrapper = new SortableListItemWrapper(); #region Apply attributes var itemProps = itemProperties != null ? itemProperties.Compile().Invoke(model) : new HtmlProperties(null, null, null); var labelProps = labelProperties != null ? labelProperties.Compile().Invoke(model) : new HtmlProperties(null, null, null); var badgeProps = badgeProperties != null ? badgeProperties.Compile().Invoke(model) : new HtmlProperties(null, null, null); var globalProps = globalProperties != null ? globalProperties.Compile().Invoke(model) : new HtmlProperties(null, null, null); var configProps = config != null ? config.Compile().Invoke(model) : null; var htmlAttributes = new RouteValueDictionary(); var dataAttributes = new RouteValueDictionary(); #region Root sortableListItemWrapper.RootTag.MergeAttributes(DictionaryFromAttributes(globalProps.HtmlAttributes)); sortableListItemWrapper.RootTag.MergeAttributes(DictionaryFromAttributes(globalProps.DataAttributes, "data-")); #endregion #region Item if (configProps != null) { var connectionString = String.Join(" ", _permitedConnections[configProps.Id].OrderBy(x => x)); dataAttributes = DictionaryFromAttributes(itemProps.DataAttributes, "data-"); dataAttributes.Add("data-id", configProps.Id); dataAttributes.Add("data-order", configProps.Order); dataAttributes.Add("data-appends-to", connectionString); } sortableListItemWrapper.ItemTag.MergeAttributes(DictionaryFromAttributes(itemProps.HtmlAttributes)); sortableListItemWrapper.ItemTag.MergeAttributes(dataAttributes); #endregion #region Label htmlAttributes = DictionaryFromAttributes(labelProps.HtmlAttributes); sortableListItemWrapper.LabelTag.MergeAttributes(htmlAttributes); sortableListItemWrapper.LabelTag.MergeAttributes(DictionaryFromAttributes(labelProps.DataAttributes, "data-")); sortableListItemWrapper.LabelTag.InnerHtml = " " + (configProps != null ? configProps.Text : String.Empty); #endregion #region Badge sortableListItemWrapper.BadgeTag.MergeAttributes(DictionaryFromAttributes(badgeProps.HtmlAttributes)); sortableListItemWrapper.BadgeTag.MergeAttributes(DictionaryFromAttributes(badgeProps.DataAttributes, "data-")); sortableListItemWrapper.BadgeTag.InnerHtml += badgeProps.Text; #endregion #endregion #region Build nested list var properties = model.GetType().GetProperties(); PropertyInfo nestedValuesProperty = null; // Find the first property in @model's properties // decorated with a BsControlAttribute matching BsControlType.SortableList foreach (PropertyInfo prop in properties) { if (nestedValuesProperty != null) { break; } var attributes = prop.GetCustomAttributes(true); foreach (var attr in attributes) { var bsControl = attr as BsControlAttribute; if (bsControl != null && bsControl.ControlType == BsControlType.SortableList) { nestedValuesProperty = prop; break; } } } if (nestedValuesProperty != null) { var value = nestedValuesProperty.GetValue(model, null); sortableListItemWrapper.Children = new List<SortableListItemWrapper>(); if (value != null && (value as IEnumerable<TModel>) != null) { foreach (var item in (value as IEnumerable<TModel>)) { sortableListItemWrapper.Children.Add(Build(item, config, globalProperties, itemProperties, labelProperties, badgeProperties)); } } } #endregion return sortableListItemWrapper; } #region Tree iteration & connection validations private Dictionary<string, IEnumerable<string>> GetPermitedConnections(IEnumerable<TModel> model, Expression<Func<TModel, BsSortableListConfiguration<TModel>>> config) { var connections = new Dictionary<string, IEnumerable<string>>(); if (config == null) { return null; } foreach (var item in model) { var permitedConnections = new List<string>(); var configValues = config.Compile().Invoke(item); var candidateItems = model.Where(x => !x.Equals(item)); Expression<Func<TModel, bool>> validationExpression = configValues != null ? configValues.AppendsTo : null; var itemId = configValues != null ? configValues.Id : String.Empty; foreach (var candidateItem in candidateItems) { if (IsValidConnection(item, candidateItem, validationExpression)) { var candidateId = config.Compile().Invoke(candidateItem).Id; permitedConnections.Add(candidateId); } } connections.Add(itemId, permitedConnections); } return connections; } private IEnumerable<TModel> GetReducedTree(TModel model) { var items = new List<TModel>(); var children = GetNestedTreeProperty(model); if (children != null) { items = items.Concat(GetReducedTree(children)).ToList(); } return items; } private IEnumerable<TModel> GetReducedTree(IEnumerable<TModel> tree) { var items = new List<TModel>(); if (tree != null && tree.Any()) { foreach (var item in tree) { items.Add(item); var children = GetNestedTreeProperty(item); if (children != null) { items = items.Concat(GetReducedTree(children)).ToList(); } } } return items; } private IEnumerable<TModel> GetNestedTreeProperty(TModel model) { var properties = model.GetType().GetProperties(); PropertyInfo nestedValuesProperty = null; // Find the first property in @model's properties // decorated with a BsControlAttribute matching BsControlType.SortableList foreach (PropertyInfo prop in properties) { if (nestedValuesProperty != null) { break; } var attributes = prop.GetCustomAttributes(true); foreach (var attr in attributes) { var bsControl = attr as BsControlAttribute; if (bsControl != null && bsControl.ControlType == BsControlType.SortableList) { nestedValuesProperty = prop; break; } } } if (nestedValuesProperty != null) { var value = nestedValuesProperty.GetValue(model, null); return value != null && (value as IEnumerable<TModel>) != null ? value as IEnumerable<TModel> : null; } return null; } private bool IsValidConnection(TModel model, TModel candidateModel, Expression<Func<TModel, bool>> expression) { return expression == null || expression.Compile().Invoke(candidateModel); } #endregion public string RenderInternal(SortableListItemWrapper list) { var htmlString = String.Empty; if (list.BadgeTag.Attributes.ContainsKey("class")) { list.BadgeTag.Attributes["class"] += " label"; } else { list.BadgeTag.Attributes.Add("class", "label"); } if (list.ItemTag.Attributes.ContainsKey("class")) { list.ItemTag.Attributes["class"] += " bs-sortable-item"; } else { list.ItemTag.Attributes.Add("class", "bs-sortable-item"); } #region Nested elements if (list.RootTag.Attributes.ContainsKey("class")) { list.RootTag.Attributes["class"] += " bs-sortable"; } else { list.RootTag.Attributes.Add("class", "bs-sortable"); } if (list.Children != null && list.Children.Any()) { foreach (var child in list.Children) { list.RootTag.InnerHtml += RenderInternal(child); } } #endregion list.ItemTag.InnerHtml += list.BadgeTag.ToString() + list.LabelTag.ToString() + list.RootTag.ToString(); htmlString = list.ItemTag.ToString(); return htmlString; } public BsSortableListHtmlBuilder<TModel> Renderer(BsBaseRenderer<BsSortableListHtmlBuilder<TModel>> renderer) { renderer.Register(this); this.renderer = renderer; return this; } #endregion #region Fluent methods public BsSortableListHtmlBuilder<TModel> ItemProperties(Expression<Func<TModel, HtmlProperties>> itemProperties) { this.List = Build(this.Model, _config, _globalProperties, itemProperties, _labelProperties, _badgeProperties); _itemProperties = itemProperties; return this; } public BsSortableListHtmlBuilder<TModel> LabelProperties(Expression<Func<TModel, HtmlProperties>> labelProperties) { this.List = Build(this.Model, _config, _globalProperties, _itemProperties, labelProperties, _badgeProperties); _labelProperties = labelProperties; return this; } public BsSortableListHtmlBuilder<TModel> BadgeProperties(Expression<Func<TModel, HtmlProperties>> badgeProperties) { this.List = Build(this.Model, _config, _globalProperties, _itemProperties, _labelProperties, badgeProperties); _badgeProperties = badgeProperties; return this; } public BsSortableListHtmlBuilder<TModel> ListProperties(Expression<Func<TModel, HtmlProperties>> listProperties) { this.List = Build(this.Model, _config, listProperties, _itemProperties, _labelProperties, _badgeProperties); _globalProperties = listProperties; return this; } public BsSortableListHtmlBuilder<TModel> Configure(Expression<Func<TModel, BsSortableListConfiguration<TModel>>> config) { this.List = Build(this.Model, config, _globalProperties, _itemProperties, _labelProperties, _badgeProperties); _config = config; return this; } public BsSortableListHtmlBuilder<TModel> ParentProperty(string propertyName) { this.ParentPropertyName = propertyName; return this; } public BsSortableListHtmlBuilder<TModel> MigrationPermited(bool permited) { if (globalDataAttributes.ContainsKey("migration-permited")) { globalDataAttributes["migration-permited"] = permited; } else { globalDataAttributes.Add("migration-permited", permited); } return this; } #region Individual component configuration public BsSortableListHtmlBuilder<TModel> HtmlAttributes(object attributes) { var globalPropertiesFunc = _globalProperties.Compile(); _globalProperties = x => new HtmlProperties { HtmlAttributes = attributes, DataAttributes = globalPropertiesFunc.Invoke(x).DataAttributes, Text = globalPropertiesFunc.Invoke(x).Text }; this.List = Build(this.Model, _config, _globalProperties, _itemProperties, _labelProperties, _badgeProperties); return this; } public BsSortableListHtmlBuilder<TModel> DataAttributes(object attributes) { var globalPropertiesFunc = _globalProperties.Compile(); _globalProperties = x => new HtmlProperties { HtmlAttributes = globalPropertiesFunc.Invoke(x).HtmlAttributes, DataAttributes = attributes, Text = globalPropertiesFunc.Invoke(x).Text }; this.List = Build(this.Model, _config, _globalProperties, _itemProperties, _labelProperties, _badgeProperties); return this; } public BsSortableListHtmlBuilder<TModel> ItemHtmlAttributes(Expression<Func<TModel, object>> attributes) { var itemPropertiesFunc = _itemProperties.Compile(); var attributesFunc = attributes.Compile(); _itemProperties = x => new HtmlProperties { HtmlAttributes = attributesFunc.Invoke(x), DataAttributes = itemPropertiesFunc.Invoke(x).DataAttributes, Text = itemPropertiesFunc.Invoke(x).Text }; this.List = Build(this.Model, _config, _globalProperties, _itemProperties, _labelProperties, _badgeProperties); return this; } public BsSortableListHtmlBuilder<TModel> BadgeHtmlAttributes(Expression<Func<TModel, object>> attributes) { var badgePropertiesFunc = _badgeProperties.Compile(); var attributesFunc = attributes.Compile(); _badgeProperties = x => new HtmlProperties { HtmlAttributes = attributesFunc.Invoke(x), DataAttributes = badgePropertiesFunc.Invoke(x).DataAttributes, Text = badgePropertiesFunc.Invoke(x).Text }; this.List = Build(this.Model, _config, _globalProperties, _itemProperties, _labelProperties, _badgeProperties); return this; } public BsSortableListHtmlBuilder<TModel> LabelHtmlAttributes(Expression<Func<TModel, object>> attributes) { var labelPropertiesFunc = _labelProperties.Compile(); var attributesFunc = attributes.Compile(); _labelProperties = x => new HtmlProperties { HtmlAttributes = attributesFunc.Invoke(x), DataAttributes = labelPropertiesFunc.Invoke(x).DataAttributes, Text = labelPropertiesFunc.Invoke(x).Text }; this.List = Build(this.Model, _config, _globalProperties, _itemProperties, _labelProperties, _badgeProperties); return this; } public BsSortableListHtmlBuilder<TModel> BadgeText(Expression<Func<TModel, string>> text) { var badgePropertiesFunc = _badgeProperties.Compile(); var textFunc = text.Compile(); _badgeProperties = x => new HtmlProperties { HtmlAttributes = badgePropertiesFunc.Invoke(x).HtmlAttributes, DataAttributes = badgePropertiesFunc.Invoke(x).DataAttributes, Text = textFunc.Invoke(x) }; this.List = Build(this.Model, _config, _globalProperties, _itemProperties, _labelProperties, _badgeProperties); return this; } public BsSortableListHtmlBuilder<TModel> LabelText(Expression<Func<TModel, string>> text) { var labelPropertiesFunc = _labelProperties.Compile(); var textFunc = text.Compile(); _labelProperties = x => new HtmlProperties { HtmlAttributes = labelPropertiesFunc.Invoke(x).HtmlAttributes, DataAttributes = labelPropertiesFunc.Invoke(x).DataAttributes, Text = textFunc.Invoke(x) }; this.List = Build(this.Model, _config, _globalProperties, _itemProperties, _labelProperties, _badgeProperties); return this; } #endregion #endregion #region Helpers private RouteValueDictionary DictionaryFromAttributes(object attributes, string keyPrefix = "") { var returnValue = new RouteValueDictionary(); if (attributes != null) { returnValue = attributes is IDictionary<string, object> ? attributes as RouteValueDictionary : HtmlHelper.AnonymousObjectToHtmlAttributes(attributes); } returnValue = returnValue ?? new RouteValueDictionary(); if (!String.IsNullOrEmpty(keyPrefix)) { returnValue = new RouteValueDictionary(returnValue.ToDictionary(x => keyPrefix + x.Key, y => y.Value)); } return returnValue; } #endregion } public class BsSortableBaseRenderer<TModel> : BsBaseRenderer<BsSortableListHtmlBuilder<TModel>> { public override string Render() { var innerHtml = this.Builder.List.Children.Aggregate(String.Empty, (current, item) => current + this.RenderInternal(item)); var ol = new TagBuilder("ol") { InnerHtml = innerHtml }; ol.MergeAttributes(this.Builder.globalHtmlAttributes); ol.MergeAttributes(this.Builder.globalDataAttributes.ToDictionary(x => "data-" + x.Key, y => y.Value)); if (this.Builder.globalHtmlAttributes.ContainsKey("class")) { ol.Attributes["class"] += " bs-sortable"; } else { ol.Attributes.Add("class", "bs-sortable"); } var container = new TagBuilder("div") { InnerHtml = ol.ToString() }; container.Attributes.Add("class", "sortable-container"); container.Attributes.Add("data-parent-property", this.Builder.ParentPropertyName); container.Attributes.Add("data-renderer", "base"); return container.ToString(); } protected string RenderInternal(SortableListItemWrapper list) { var htmlString = String.Empty; if (list.BadgeTag.Attributes.ContainsKey("class")) { list.BadgeTag.Attributes["class"] += " label"; } else { list.BadgeTag.Attributes.Add("class", "label"); } if (list.ItemTag.Attributes.ContainsKey("class")) { list.ItemTag.Attributes["class"] += " bs-sortable-item"; } else { list.ItemTag.Attributes.Add("class", "bs-sortable-item"); } #region Nested elements if (list.RootTag.Attributes.ContainsKey("class")) { list.RootTag.Attributes["class"] += " bs-sortable"; } else { list.RootTag.Attributes.Add("class", "bs-sortable"); } if (list.Children != null && list.Children.Any()) { foreach (var child in list.Children) { list.RootTag.InnerHtml += RenderInternal(child); } } #endregion list.ItemTag.InnerHtml += list.BadgeTag.ToString() + list.LabelTag.ToString() + list.RootTag.ToString(); htmlString = list.ItemTag.ToString(); return htmlString; } } public class BsSortableLightRenderer<TModel> : BsBaseRenderer<BsSortableListHtmlBuilder<TModel>> { public override string Render() { var innerHtml = this.Builder.List.Children.Aggregate(String.Empty, (current, item) => current + this.RenderInternal(item)); var ul = new TagBuilder("ul") { InnerHtml = innerHtml }; ul.MergeAttributes(this.Builder.globalHtmlAttributes); ul.MergeAttributes(this.Builder.globalDataAttributes.ToDictionary(x => "data-" + x.Key, y => y.Value)); if (this.Builder.globalHtmlAttributes.ContainsKey("class")) { ul.Attributes["class"] += " bs-sortable nav nav-pills nav-stacked"; } else { ul.Attributes.Add("class", "bs-sortable nav nav-pills nav-stacked"); } ul.Attributes.Add("style", "margin-top: 2px"); var container = new TagBuilder("div") { InnerHtml = ul.ToString() }; container.Attributes.Add("class", "sortable-container"); container.Attributes.Add("data-parent-property", this.Builder.ParentPropertyName); container.Attributes.Add("data-renderer", "light"); return container.ToString(); } public string RenderInternal(SortableListItemWrapper list) { var htmlString = String.Empty; list.RootTag = new TagBuilder("ul"); if (list.ItemTag.Attributes.ContainsKey("class")) { list.ItemTag.Attributes["class"] += " bs-sortable-item active"; } else { list.ItemTag.Attributes.Add("class", "bs-sortable-item active"); } #region Nested elements if (list.RootTag.Attributes.ContainsKey("class")) { list.RootTag.Attributes["class"] += " bs-sortable nav nav-pills nav-stacked"; } else { list.RootTag.Attributes.Add("class", "bs-sortable nav nav-pills nav-stacked"); } if (list.RootTag.Attributes.ContainsKey("style")) { list.RootTag.Attributes["style"] += "margin-left: 40px; margin-top: 4px;"; } else { list.RootTag.Attributes.Add("style", "margin-left: 40px; margin-top: 4px;"); } if (list.Children != null && list.Children.Any()) { foreach (var child in list.Children) { list.RootTag.InnerHtml += RenderInternal(child); } } #endregion var anchor = new TagBuilder("a"); anchor.Attributes.Add("href", "#"); anchor.SetInnerText(list.LabelTag.InnerHtml); var span = new TagBuilder("span"); span.Attributes.Add("class", "badge pull-right"); span.InnerHtml = list.BadgeTag.InnerHtml; anchor.InnerHtml = span.ToString() + anchor.InnerHtml; list.ItemTag.InnerHtml = anchor.ToString() + list.RootTag.ToString(); // list.ItemTag.InnerHtml += spanTag.ToString() + list.RootTag.ToString(); // htmlString = list.ItemTag.ToString() + list.RootTag.ToString(); htmlString = list.ItemTag.ToString(); return htmlString; } } }
namespace Ioke.Lang { using System.Collections; using System.Collections.Generic; using System.Collections.Specialized; using System.Text; using Ioke.Lang.Util; public class DefaultArgumentsDefinition { public static int IndexOf(IList objs, object obj) { int i = 0; foreach(object o in objs) { if(o == obj) { return i; } i++; } return -1; } public class Argument { string name; public Argument(string name) { this.name = name; } public string Name { get { return name; } } } public class UnevaluatedArgument : Argument { bool required; public UnevaluatedArgument(string name, bool required) : base(name) { this.required = required; } public bool Required { get { return required; } } } public class OptionalArgument : Argument { object defaultValue; public OptionalArgument(string name, object defaultValue) : base(name) { this.defaultValue = defaultValue; } public object DefaultValue { get { return defaultValue; } } } public class KeywordArgument : Argument { object defaultValue; public KeywordArgument(string name, object defaultValue) : base(name) { this.defaultValue = defaultValue; } public object DefaultValue { get { return defaultValue; } } } public static DefaultArgumentsDefinition Empty() { return new DefaultArgumentsDefinition(new SaneList<Argument>(), new SaneList<string>(), null, null, 0, 0, false); } private readonly int min; private readonly int max; private readonly IList<Argument> arguments; private readonly ICollection<string> keywords; private readonly string rest; private readonly string krest; internal readonly bool restUneval; protected DefaultArgumentsDefinition(IList<Argument> arguments, ICollection<string> keywords, string rest, string krest, int min, int max, bool restUneval) { this.arguments = arguments; this.keywords = keywords; this.rest = rest; this.krest = krest; this.min = min; this.max = max; this.restUneval = restUneval; } public ICollection<string> Keywords { get { return keywords; } } public IList<Argument> Arguments { get { return arguments; } } public int Max { get { return max; } } public int Min { get { return min; } } public string RestName { get { return rest; } } public string KrestName { get { return krest; } } public bool IsEmpty { get { return min == 0 && max == 0 && arguments.Count == 0 && keywords.Count == 0 && rest == null && krest == null; } } public string GetCode() { return GetCode(true); } public string GetCode(bool lastComma) { bool any = false; StringBuilder sb = new StringBuilder(); foreach(Argument argument in arguments) { any = true; if(!(argument is KeywordArgument)) { if(argument is UnevaluatedArgument) { sb.Append("[").Append(argument.Name).Append("]"); if(!((UnevaluatedArgument)argument).Required) { sb.Append(" nil"); } } else { sb.Append(argument.Name); } } else { sb.Append(argument.Name).Append(":"); } if((argument is OptionalArgument) && ((OptionalArgument)argument).DefaultValue != null) { sb.Append(" "); object defValue = ((OptionalArgument)argument).DefaultValue; if(defValue is string) { sb.Append(defValue); } else { sb.Append(Message.Code(IokeObject.As(defValue, null))); } } else if((argument is KeywordArgument) && ((KeywordArgument)argument).DefaultValue != null) { sb.Append(" "); object defValue = ((KeywordArgument)argument).DefaultValue; if(defValue is string) { sb.Append(defValue); } else { sb.Append(Message.Code(IokeObject.As(defValue, null))); } } sb.Append(", "); } if(rest != null) { any = true; if(restUneval) { sb.Append("+[").Append(rest).Append("], "); } else { sb.Append("+").Append(rest).Append(", "); } } if(krest != null) { any = true; sb.Append("+:").Append(krest).Append(", "); } if(!lastComma && any) { sb.Remove(sb.Length - 2, 2); } return sb.ToString(); } public int CheckArgumentCount(IokeObject context, IokeObject message, object on) { Runtime runtime = context.runtime; IList arguments = message.Arguments; int argCount = arguments.Count; int keySize = keywords.Count; if(argCount < min || (max != -1 && argCount > (max+keySize))) { int finalArgCount = argCount; if(argCount < min) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Invocation", "TooFewArguments"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("missing", runtime.NewNumber(min-argCount)); runtime.ErrorCondition(condition); } else { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Invocation", "TooManyArguments"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("extra", runtime.NewList(ArrayList.Adapter(arguments).GetRange(max, finalArgCount-max))); runtime.WithReturningRestart("ignoreExtraArguments", context, () => {runtime.ErrorCondition(condition);}); argCount = max; } } return argCount; } private class NewArgumentGivingRestart : Restart.ArgumentGivingRestart { string argname; public NewArgumentGivingRestart(string name) : this(name, "newArguments") {} public NewArgumentGivingRestart(string name, string argname) : base(name) { this.argname = argname; } public override IList<string> ArgumentNames { get { return new SaneList<string>() {argname}; } } } public int GetEvaluatedArguments(IokeObject context, IokeObject message, object on, IList argumentsWithoutKeywords, IDictionary<string, object> givenKeywords) { Runtime runtime = context.runtime; IList arguments = message.Arguments; int argCount = 0; foreach(object o in arguments) { if(Message.IsKeyword(o)) { givenKeywords[IokeObject.As(o, context).Name] = Interpreter.GetEvaluatedArgument(((Message)IokeObject.dataOf(o)).next, context); } else if(Message.HasName(o, "*") && IokeObject.As(o, context).Arguments.Count == 1) { // Splat object result = Interpreter.GetEvaluatedArgument(IokeObject.As(o, context).Arguments[0], context); if(IokeObject.dataOf(result) is IokeList) { IList elements = IokeList.GetList(result); foreach(object ox in elements) argumentsWithoutKeywords.Add(ox); argCount += elements.Count; } else if(IokeObject.dataOf(result) is Dict) { IDictionary keys = Dict.GetMap(result); foreach(DictionaryEntry me in keys) { givenKeywords[Text.GetText(IokeObject.ConvertToText(me.Key, message, context, true)) + ":"] = me.Value; } } else if(IokeObject.FindCell((IokeObject)result, "asTuple") != runtime.nul) { object tupledValue = Interpreter.Send(runtime.asTuple, context, result); object[] values = Tuple.GetElements(tupledValue); foreach(object val in values) argumentsWithoutKeywords.Add(val); argCount += values.Length; } else { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Invocation", "NotSpreadable"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("given", result); IList outp = IokeList.GetList(runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);}, context, new Restart.DefaultValuesGivingRestart("ignoreArgument", runtime.nil, 0), new Restart.DefaultValuesGivingRestart("takeArgumentAsIs", IokeObject.As(result, context), 1) )); foreach(object ox in outp) argumentsWithoutKeywords.Add(ox); argCount += outp.Count; } } else { var xx = Interpreter.GetEvaluatedArgument(o, context); argumentsWithoutKeywords.Add(xx); argCount++; } } while(argCount < min || (max != -1 && argCount > max)) { int finalArgCount = argCount; if(argCount < min) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Invocation", "TooFewArguments"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("missing", runtime.NewNumber(min-argCount)); IList newArguments = IokeList.GetList(runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);}, context, new NewArgumentGivingRestart("provideExtraArguments"), new Restart.DefaultValuesGivingRestart("substituteNilArguments", runtime.nil, min-argCount))); foreach(object ox in newArguments) argumentsWithoutKeywords.Add(ox); argCount += newArguments.Count; } else { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Invocation", "TooManyArguments"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("extra", runtime.NewList(ArrayList.Adapter(argumentsWithoutKeywords).GetRange(max, finalArgCount-max))); runtime.WithReturningRestart("ignoreExtraArguments", context, ()=>{runtime.ErrorCondition(condition);}); argCount = max; } } var intersection = new SaneHashSet<string>(givenKeywords.Keys); foreach(string k in keywords) intersection.Remove(k); if(krest == null && intersection.Count > 0) { IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Invocation", "MismatchedKeywords"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); IList expected = new SaneArrayList(); foreach(string s in keywords) { expected.Add(runtime.NewText(s)); } condition.SetCell("expected", runtime.NewList(expected)); IList extra = new SaneArrayList(); foreach(string s in intersection) { extra.Add(runtime.NewText(s)); } condition.SetCell("extra", runtime.NewList(extra)); runtime.WithReturningRestart("ignoreExtraKeywords", context, ()=>{runtime.ErrorCondition(condition);}); } return argCount; } public void AssignArgumentValues(IokeObject locals, IokeObject context, IokeObject message, object on, Call call) { if(call.cachedPositional != null) { AssignArgumentValues(locals, context, message, on, call.cachedPositional, call.cachedKeywords, call.cachedArgCount); } else { IList argumentsWithoutKeywords = new SaneArrayList(); IDictionary<string, object> givenKeywords = new SaneDictionary<string, object>(); int argCount = GetEvaluatedArguments(context, message, on, argumentsWithoutKeywords, givenKeywords); call.cachedPositional = argumentsWithoutKeywords; call.cachedKeywords = givenKeywords; call.cachedArgCount = argCount; AssignArgumentValues(locals, context, message, on, argumentsWithoutKeywords, givenKeywords, argCount); } } public void AssignArgumentValues(IokeObject locals, IokeObject context, IokeObject message, object on) { IList argumentsWithoutKeywords = new SaneArrayList(); IDictionary<string, object> givenKeywords = new SaneDictionary<string, object>(); int argCount = GetEvaluatedArguments(context, message, on, argumentsWithoutKeywords, givenKeywords); AssignArgumentValues(locals, context, message, on, argumentsWithoutKeywords, givenKeywords, argCount); } private void AssignArgumentValues(IokeObject locals, IokeObject context, IokeObject message, object on, IList argumentsWithoutKeywords, IDictionary<string, object> givenKeywords, int argCount) { Runtime runtime = context.runtime; var intersection = new SaneHashSet<string>(givenKeywords.Keys); foreach(string k in keywords) intersection.Remove(k); int ix = 0; for(int i=0, j=this.arguments.Count;i<j;i++) { Argument a = this.arguments[i]; if(a is KeywordArgument) { string nm = a.Name + ":"; object result = null; if(givenKeywords.ContainsKey(nm)) { object given = givenKeywords[nm]; result = given; locals.SetCell(a.Name, result); } else { object defVal = ((KeywordArgument)a).DefaultValue; if(!(defVal is string)) { IokeObject m1 = IokeObject.As(defVal, context); result = runtime.interpreter.Evaluate(m1, locals, locals.RealContext, locals); locals.SetCell(a.Name, result); } } } else if((a is OptionalArgument) && ix>=argCount) { object defVal = ((OptionalArgument)a).DefaultValue; if(!(defVal is string)) { IokeObject m2 = IokeObject.As(defVal, context); locals.SetCell(a.Name, runtime.interpreter.Evaluate(m2, locals, locals.RealContext, locals)); } } else { locals.SetCell(a.Name, argumentsWithoutKeywords[ix++]); } } if(krest != null) { var krests = new SaneHashtable(); foreach(string s in intersection) { object given = givenKeywords[s]; object result = given; krests[runtime.GetSymbol(s.Substring(0, s.Length-1))] = result; } locals.SetCell(krest, runtime.NewDict(krests)); } if(rest != null) { IList rests = new SaneArrayList(); for(int j=argumentsWithoutKeywords.Count;ix<j;ix++) { rests.Add(argumentsWithoutKeywords[ix]); } locals.SetCell(rest, runtime.NewList(rests)); } } public static DefaultArgumentsDefinition CreateFrom(IList args, int start, int end, IokeObject message, object on, IokeObject context) { Runtime runtime = context.runtime; IList<Argument> arguments = new SaneList<Argument>(); IList<string> keywords = new SaneList<string>(); int min = 0; int max = 0; bool hadOptional = false; string rest = null; string krest = null; foreach(object obj in ArrayList.Adapter(args).GetRange(start, end-start)) { Message m = (Message)IokeObject.dataOf(obj); string mname = m.Name; if(!"+:".Equals(mname) && m.IsKeyword()) { string name = mname; IokeObject dValue = context.runtime.nilMessage; if(m.next != null) { dValue = m.next; } arguments.Add(new KeywordArgument(name.Substring(0, name.Length-1), dValue)); keywords.Add(name); } else if(mname.Equals("+")) { string name = Message.GetName(m.Arguments(null)[0]); if(name.StartsWith(":")) { krest = name.Substring(1); } else { rest = name; max = -1; } hadOptional = true; } else if(mname.Equals("+:")) { string name = m.next != null ? Message.GetName(m.next) : Message.GetName(m.Arguments(null)[0]); krest = name; hadOptional = true; } else if(m.next != null) { string name = mname; hadOptional = true; if(max != -1) { max++; } arguments.Add(new OptionalArgument(name, m.next)); } else { if(hadOptional) { int index = IndexOf(args, obj) + start; IokeObject condition = IokeObject.As(IokeObject.GetCellChain(runtime.Condition, message, context, "Error", "Invocation", "ArgumentWithoutDefaultValue"), context).Mimic(message, context); condition.SetCell("message", message); condition.SetCell("context", context); condition.SetCell("receiver", on); condition.SetCell("argumentName", runtime.GetSymbol(m.Name)); condition.SetCell("index", runtime.NewNumber(index)); IList newValue = IokeList.GetList(runtime.WithRestartReturningArguments(()=>{runtime.ErrorCondition(condition);}, context, new NewArgumentGivingRestart("provideDefaultValue", "defaultValue"), new Restart.DefaultValuesGivingRestart("substituteNilDefault", runtime.nil, 1))); if(max != -1) { max++; } arguments.Add(new OptionalArgument(m.Name, runtime.CreateMessage(Message.Wrap(IokeObject.As(newValue[0], context))))); } else { min++; max++; arguments.Add(new Argument(IokeObject.As(obj, context).Name)); } } } return new DefaultArgumentsDefinition(arguments, keywords, rest, krest, min, max, false); } public class Builder { protected int min = 0; protected int max = 0; protected IList<Argument> arguments = new SaneList<Argument>(); protected ICollection<string> keywords = new SaneHashSet<string>(); protected string rest = null; protected string krest = null; protected bool restUneval = false; public virtual Builder WithRequiredPositionalUnevaluated(string name) { arguments.Add(new UnevaluatedArgument(name, true)); min++; if(max != -1) { max++; } return this; } public virtual Builder WithOptionalPositionalUnevaluated(string name) { arguments.Add(new UnevaluatedArgument(name, false)); if(max != -1) { max++; } return this; } public virtual Builder WithRestUnevaluated(string name) { rest = name; restUneval = true; max = -1; return this; } public virtual Builder WithRest(string name) { rest = name; max = -1; return this; } public virtual Builder WithKeywordRest(string name) { krest = name; return this; } public virtual Builder WithKeywordRestUnevaluated(string name) { krest = name; restUneval = true; return this; } public virtual Builder WithRequiredPositional(string name) { arguments.Add(new Argument(name)); min++; if(max != -1) { max++; } return this; } public virtual Builder WithKeyword(string name) { arguments.Add(new KeywordArgument(name, "nil")); keywords.Add(name + ":"); return this; } public virtual Builder WithOptionalPositional(string name, string defaultValue) { arguments.Add(new OptionalArgument(name, defaultValue)); if(max != -1) { max++; } return this; } public virtual DefaultArgumentsDefinition Arguments { get { return new DefaultArgumentsDefinition(arguments, keywords, rest, krest, min, max, restUneval); } } } public static Builder builder() { return new Builder(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Baseline; using Marten.Linq; #nullable enable namespace Marten.Pagination { /// <summary> /// Class to return The async paged list from a paged query. /// </summary> /// <typeparam name="T">Document Type</typeparam> public class PagedList<T>: IPagedList<T> { private readonly List<T> _items = new List<T>(); private PagedList() { } /// <summary> /// Return the paged query result /// </summary> /// <param name="index">Index to fetch item from paged query result</param> /// <returns>/returns item from paged query result</returns> public T this[int index] { get { return _items[index]; } } /// <summary> /// Return the number of records in the paged query result /// </summary> public long Count { get { return _items.Count(); } } /// <summary> /// Generic Enumerator /// </summary> /// <returns>Generic Enumerator of paged query result</returns> public IEnumerator<T> GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } /// <summary> /// Enumerator /// </summary> /// <returns>Enumerator of paged query result</returns> IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable<T>)_items).GetEnumerator(); } /// <summary> /// Gets current page number /// </summary> public long PageNumber { get; protected set; } /// <summary> /// Gets page size /// </summary> public long PageSize { get; protected set; } /// <summary> /// Gets number of pages /// </summary> public long PageCount { get; protected set; } /// <summary> /// Gets the total number records /// </summary> public long TotalItemCount { get; protected set; } /// <summary> /// Gets a value indicating whether there is a previous page /// </summary> public bool HasPreviousPage { get; protected set; } /// <summary> /// Gets a value indicating whether there is next page /// </summary> public bool HasNextPage { get; protected set; } /// <summary> /// Gets a value indicating whether the current page is first page /// </summary> public bool IsFirstPage { get; protected set; } /// <summary> /// Gets a value indicating whether the current page is last page /// </summary> public bool IsLastPage { get; protected set; } /// <summary> /// Gets one-based index of first item in current page /// </summary> public long FirstItemOnPage { get; protected set; } /// <summary> /// Gets one-based index of last item in current page /// </summary> public long LastItemOnPage { get; protected set; } /// <summary> /// Static method to create a new instance of the <see cref="PagedList{T} /// </summary> /// <param name="queryable"></param> /// <param name="pageNumber"></param> /// <param name="pageSize"></param> public static PagedList<T> Create(IQueryable<T> queryable, int pageNumber, int pageSize) { var pagedList = new PagedList<T>(); pagedList.Init(queryable, pageNumber, pageSize); return pagedList; } /// <summary> /// Async static method to create a new instance of the <see cref="PagedList{T} /// </summary> /// <param name="queryable"></param> /// <param name="pageNumber"></param> /// <param name="pageSize"></param> public static async Task<PagedList<T>> CreateAsync(IQueryable<T> queryable, int pageNumber, int pageSize, CancellationToken token = default) { var pagedList = new PagedList<T>(); await pagedList.InitAsync(queryable, pageNumber, pageSize, token).ConfigureAwait(false); return pagedList; } /// <summary> /// Initializes a new instance of the <see cref="PagedList{T}" /> class. /// </summary> /// <param name="queryable">Query for which data has to be fetched</param> /// <param name="pageSize">Page size</param> /// <param name="totalItemCount">Total count of all records</param> public void Init(IQueryable<T> queryable, int pageNumber, int pageSize) { var query = PrepareQuery(queryable, pageNumber, pageSize, out QueryStatistics statistics); var items = query.ToList(); ProcessResults(pageSize, items, statistics); } /// <summary> /// Initializes a new instance of the <see cref="PagedList{T}" /> class. /// </summary> /// <param name="queryable">Query for which data has to be fetched</param> /// <param name="pageSize">Page size</param> /// <param name="totalItemCount">Total count of all records</param> public async Task InitAsync(IQueryable<T> queryable, int pageNumber, int pageSize, CancellationToken token = default) { var query = PrepareQuery(queryable, pageNumber, pageSize, out QueryStatistics statistics); var items = await query.ToListAsync(token).ConfigureAwait(false); ProcessResults(pageSize, items, statistics); } private IQueryable<T> PrepareQuery(IQueryable<T> queryable, int pageNumber, int pageSize, out QueryStatistics statistics) { // throw an argument exception if page number is less than one if (pageNumber < 1) { throw new ArgumentOutOfRangeException($"pageNumber = {pageNumber}. PageNumber cannot be below 1."); } // throw an argument exception if page Size is less than one if (pageSize < 1) { throw new ArgumentOutOfRangeException($"pageSize = {pageSize}. PageSize cannot be below 1."); } PageNumber = pageNumber; PageSize = pageSize; return pageNumber == 1 ? queryable.As<IMartenQueryable<T>>().Stats(out statistics).Take(pageSize) : queryable.As<IMartenQueryable<T>>().Stats(out statistics).Skip((pageNumber - 1) * pageSize).Take(pageSize); } private void ProcessResults(int pageSize, IReadOnlyList<T> items, QueryStatistics statistics) { _items.AddRange(items); // fetch the total record count TotalItemCount = statistics.TotalResults; // compute the number of pages based on page size and total records PageCount = TotalItemCount > 0 ? (int)Math.Ceiling(TotalItemCount / (double)pageSize) : 0; // compute if there is a previous page HasPreviousPage = PageNumber > 1; // compute if there is next page HasNextPage = PageNumber < PageCount; // compute if the current page is first page IsFirstPage = PageCount > 0 && PageNumber == 1; // compute if the current page is last page IsLastPage = PageCount > 0 && PageNumber >= PageCount; // compute one-based index of first item on a specific page FirstItemOnPage = PageCount > 0 ? ((PageNumber - 1) * PageSize) + 1 : 0; // compute one-based index of last item on a specific page var numberOfLastItemOnPage = FirstItemOnPage + PageSize - 1; LastItemOnPage = numberOfLastItemOnPage > TotalItemCount ? TotalItemCount : numberOfLastItemOnPage; } } }
// // AccountDialog.cs // // Author: // Paul Lange <palango@gmx.de> // // Copyright (C) 2010 Novell, Inc. // Copyright (C) 2010 Paul Lange // // 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 Mono.Unix; using Hyena; using Hyena.Widgets; namespace FSpot.Exporters.Gallery { public class AccountDialog { public AccountDialog (Gtk.Window parent) : this (parent, null, false) { add_dialog.Response += HandleAddResponse; add_button.Sensitive = false; } public AccountDialog (Gtk.Window parent, GalleryAccount account, bool show_error) { var builder = new GtkBeans.Builder (null, "gallery_add_dialog.ui", null); builder.Autoconnect (this); add_dialog = new Gtk.Dialog (builder.GetRawObject ("gallery_add_dialog")); add_dialog.Modal = false; add_dialog.TransientFor = parent; add_dialog.DefaultResponse = Gtk.ResponseType.Ok; this.account = account; status_area.Visible = show_error; if (account != null) { gallery_entry.Text = account.Name; url_entry.Text = account.Url; password_entry.Text = account.Password; username_entry.Text = account.Username; add_button.Label = Gtk.Stock.Ok; add_dialog.Response += HandleEditResponse; } if (remove_button != null) remove_button.Visible = account != null; add_dialog.Show (); gallery_entry.Changed += HandleChanged; url_entry.Changed += HandleChanged; password_entry.Changed += HandleChanged; username_entry.Changed += HandleChanged; HandleChanged (null, null); } private void HandleChanged (object sender, System.EventArgs args) { name = gallery_entry.Text; url = url_entry.Text; password = password_entry.Text; username = username_entry.Text; if (name == string.Empty || url == string.Empty || password == string.Empty || username == string.Empty) add_button.Sensitive = false; else add_button.Sensitive = true; } [GLib.ConnectBefore] protected void HandleAddResponse (object sender, Gtk.ResponseArgs args) { if (args.ResponseId == Gtk.ResponseType.Ok) { try { Uri uri = new Uri (url); if (uri.Scheme != Uri.UriSchemeHttp && uri.Scheme != Uri.UriSchemeHttps) throw new System.UriFormatException (); //Check for name uniqueness foreach (GalleryAccount acc in GalleryAccountManager.GetInstance ().GetAccounts ()) if (acc.Name == name) throw new ArgumentException ("name"); GalleryAccount created = new GalleryAccount (name, url, username, password); created.Connect (); GalleryAccountManager.GetInstance ().AddAccount (created); account = created; } catch (System.UriFormatException) { HigMessageDialog md = new HigMessageDialog (add_dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Invalid URL"), Catalog.GetString ("The gallery URL entry does not appear to be a valid URL")); md.Run (); md.Destroy (); return; } catch (GalleryException e) { HigMessageDialog md = new HigMessageDialog (add_dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Error while connecting to Gallery"), string.Format (Catalog.GetString ("The following error was encountered while attempting to log in: {0}"), e.Message)); if (e.ResponseText != null) { Log.Debug (e.Message); Log.Debug (e.ResponseText); } md.Run (); md.Destroy (); return; } catch (ArgumentException ae) { HigMessageDialog md = new HigMessageDialog (add_dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("A Gallery with this name already exists"), string.Format (Catalog.GetString ("There is already a Gallery with the same name in your registered Galleries. Please choose a unique name."))); Log.Exception (ae); md.Run (); md.Destroy (); return; } catch (System.Net.WebException we) { HigMessageDialog md = new HigMessageDialog (add_dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Error while connecting to Gallery"), string.Format (Catalog.GetString ("The following error was encountered while attempting to log in: {0}"), we.Message)); md.Run (); md.Destroy (); return; } catch (System.Exception se) { HigMessageDialog md = new HigMessageDialog (add_dialog, Gtk.DialogFlags.Modal | Gtk.DialogFlags.DestroyWithParent, Gtk.MessageType.Error, Gtk.ButtonsType.Ok, Catalog.GetString ("Error while connecting to Gallery"), string.Format (Catalog.GetString ("The following error was encountered while attempting to log in: {0}"), se.Message)); Log.Exception (se); md.Run (); md.Destroy (); return; } } add_dialog.Destroy (); } protected void HandleEditResponse (object sender, Gtk.ResponseArgs args) { if (args.ResponseId == Gtk.ResponseType.Ok) { account.Name = name; account.Url = url; account.Username = username; account.Password = password; GalleryAccountManager.GetInstance ().MarkChanged (true, account); } else if (args.ResponseId == Gtk.ResponseType.Reject) { // NOTE we are using Reject to signal the remove action. GalleryAccountManager.GetInstance ().RemoveAccount (account); } add_dialog.Destroy (); } private GalleryAccount account; private string name; private string url; private string password; private string username; #pragma warning disable 649 // widgets [GtkBeans.Builder.Object] Gtk.Dialog add_dialog; [GtkBeans.Builder.Object] Gtk.Entry url_entry; [GtkBeans.Builder.Object] Gtk.Entry password_entry; [GtkBeans.Builder.Object] Gtk.Entry gallery_entry; [GtkBeans.Builder.Object] Gtk.Entry username_entry; [GtkBeans.Builder.Object] Gtk.Button add_button; [GtkBeans.Builder.Object] Gtk.Button remove_button; [GtkBeans.Builder.Object] Gtk.HBox status_area; #pragma warning restore 649 } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V8.Resources { /// <summary>Resource name for the <c>DisplayKeywordView</c> resource.</summary> public sealed partial class DisplayKeywordViewName : gax::IResourceName, sys::IEquatable<DisplayKeywordViewName> { /// <summary>The possible contents of <see cref="DisplayKeywordViewName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c> /// . /// </summary> CustomerAdGroupCriterion = 1, } private static gax::PathTemplate s_customerAdGroupCriterion = new gax::PathTemplate("customers/{customer_id}/displayKeywordViews/{ad_group_id_criterion_id}"); /// <summary>Creates a <see cref="DisplayKeywordViewName"/> containing an unparsed resource name.</summary> /// <param name="unparsedResourceName">The unparsed resource name. Must not be <c>null</c>.</param> /// <returns> /// A new instance of <see cref="DisplayKeywordViewName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static DisplayKeywordViewName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new DisplayKeywordViewName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="DisplayKeywordViewName"/> with the pattern /// <c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="DisplayKeywordViewName"/> constructed from the provided ids.</returns> public static DisplayKeywordViewName FromCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => new DisplayKeywordViewName(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="DisplayKeywordViewName"/> with pattern /// <c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DisplayKeywordViewName"/> with pattern /// <c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string criterionId) => FormatCustomerAdGroupCriterion(customerId, adGroupId, criterionId); /// <summary> /// Formats the IDs into the string representation of this <see cref="DisplayKeywordViewName"/> with pattern /// <c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="DisplayKeywordViewName"/> with pattern /// <c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c>. /// </returns> public static string FormatCustomerAdGroupCriterion(string customerId, string adGroupId, string criterionId) => s_customerAdGroupCriterion.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId)))}"); /// <summary> /// Parses the given resource name string into a new <see cref="DisplayKeywordViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="displayKeywordViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="DisplayKeywordViewName"/> if successful.</returns> public static DisplayKeywordViewName Parse(string displayKeywordViewName) => Parse(displayKeywordViewName, false); /// <summary> /// Parses the given resource name string into a new <see cref="DisplayKeywordViewName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="displayKeywordViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <returns>The parsed <see cref="DisplayKeywordViewName"/> if successful.</returns> public static DisplayKeywordViewName Parse(string displayKeywordViewName, bool allowUnparsed) => TryParse(displayKeywordViewName, allowUnparsed, out DisplayKeywordViewName result) ? result : throw new sys::ArgumentException("The given resource-name matches no pattern."); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DisplayKeywordViewName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// </remarks> /// <param name="displayKeywordViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="DisplayKeywordViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string displayKeywordViewName, out DisplayKeywordViewName result) => TryParse(displayKeywordViewName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="DisplayKeywordViewName"/> instance; /// optionally allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item> /// <description><c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c></description> /// </item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="displayKeywordViewName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="allowUnparsed"> /// If <c>true</c> will successfully store an unparseable resource name into the <see cref="UnparsedResource"/> /// property; otherwise will throw an <see cref="sys::ArgumentException"/> if an unparseable resource name is /// specified. /// </param> /// <param name="result"> /// When this method returns, the parsed <see cref="DisplayKeywordViewName"/>, or <c>null</c> if parsing failed. /// </param> /// <returns><c>true</c> if the name was parsed successfully; <c>false</c> otherwise.</returns> public static bool TryParse(string displayKeywordViewName, bool allowUnparsed, out DisplayKeywordViewName result) { gax::GaxPreconditions.CheckNotNull(displayKeywordViewName, nameof(displayKeywordViewName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupCriterion.TryParseName(displayKeywordViewName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupCriterion(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(displayKeywordViewName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private DisplayKeywordViewName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string criterionId = null, string customerId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; CriterionId = criterionId; CustomerId = customerId; } /// <summary> /// Constructs a new instance of a <see cref="DisplayKeywordViewName"/> class from the component parts of /// pattern <c>customers/{customer_id}/displayKeywordViews/{ad_group_id}~{criterion_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="criterionId">The <c>Criterion</c> ID. Must not be <c>null</c> or empty.</param> public DisplayKeywordViewName(string customerId, string adGroupId, string criterionId) : this(ResourceNameType.CustomerAdGroupCriterion, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), criterionId: gax::GaxPreconditions.CheckNotNullOrEmpty(criterionId, nameof(criterionId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Criterion</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CriterionId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary>Whether this instance contains a resource name with a known pattern.</summary> public bool IsKnownPattern => Type != ResourceNameType.Unparsed; /// <summary>The string representation of the resource name.</summary> /// <returns>The string representation of the resource name.</returns> public override string ToString() { switch (Type) { case ResourceNameType.Unparsed: return UnparsedResource.ToString(); case ResourceNameType.CustomerAdGroupCriterion: return s_customerAdGroupCriterion.Expand(CustomerId, $"{AdGroupId}~{CriterionId}"); default: throw new sys::InvalidOperationException("Unrecognized resource-type."); } } /// <summary>Returns a hash code for this resource name.</summary> public override int GetHashCode() => ToString().GetHashCode(); /// <inheritdoc/> public override bool Equals(object obj) => Equals(obj as DisplayKeywordViewName); /// <inheritdoc/> public bool Equals(DisplayKeywordViewName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(DisplayKeywordViewName a, DisplayKeywordViewName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(DisplayKeywordViewName a, DisplayKeywordViewName b) => !(a == b); } public partial class DisplayKeywordView { /// <summary> /// <see cref="DisplayKeywordViewName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal DisplayKeywordViewName ResourceNameAsDisplayKeywordViewName { get => string.IsNullOrEmpty(ResourceName) ? null : DisplayKeywordViewName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } } }
/* * Copyright 2002-2015 Drew Noakes * * Modified by Yakov Danilov <yakodani@gmail.com> for Imazen LLC (Ported from Java to C#) * 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. * * More information about this project is available at: * * https://drewnoakes.com/code/exif/ * https://github.com/drewnoakes/metadata-extractor */ using Com.Drew.Metadata; using JetBrains.Annotations; using Sharpen; namespace Com.Drew.Metadata.Exif.Makernotes { /// <summary> /// Provides human-readable string representations of tag values stored in a /// <see cref="PentaxMakernoteDirectory"/> /// . /// <p> /// Some information about this makernote taken from here: /// http://www.ozhiker.com/electronics/pjmt/jpeg_info/pentax_mn.html /// </summary> /// <author>Drew Noakes https://drewnoakes.com</author> public class PentaxMakernoteDescriptor : TagDescriptor<PentaxMakernoteDirectory> { public PentaxMakernoteDescriptor([NotNull] PentaxMakernoteDirectory directory) : base(directory) { } [CanBeNull] public override string GetDescription(int tagType) { switch (tagType) { case PentaxMakernoteDirectory.TagCaptureMode: { return GetCaptureModeDescription(); } case PentaxMakernoteDirectory.TagQualityLevel: { return GetQualityLevelDescription(); } case PentaxMakernoteDirectory.TagFocusMode: { return GetFocusModeDescription(); } case PentaxMakernoteDirectory.TagFlashMode: { return GetFlashModeDescription(); } case PentaxMakernoteDirectory.TagWhiteBalance: { return GetWhiteBalanceDescription(); } case PentaxMakernoteDirectory.TagDigitalZoom: { return GetDigitalZoomDescription(); } case PentaxMakernoteDirectory.TagSharpness: { return GetSharpnessDescription(); } case PentaxMakernoteDirectory.TagContrast: { return GetContrastDescription(); } case PentaxMakernoteDirectory.TagSaturation: { return GetSaturationDescription(); } case PentaxMakernoteDirectory.TagIsoSpeed: { return GetIsoSpeedDescription(); } case PentaxMakernoteDirectory.TagColour: { return GetColourDescription(); } default: { return base.GetDescription(tagType); } } } [CanBeNull] public virtual string GetColourDescription() { return GetIndexedDescription(PentaxMakernoteDirectory.TagColour, 1, "Normal", "Black & White", "Sepia"); } [CanBeNull] public virtual string GetIsoSpeedDescription() { int? value = _directory.GetInteger(PentaxMakernoteDirectory.TagIsoSpeed); if (value == null) { return null; } switch (value) { case 10: { // TODO there must be other values which aren't catered for here return "ISO 100"; } case 16: { return "ISO 200"; } case 100: { return "ISO 100"; } case 200: { return "ISO 200"; } default: { return "Unknown (" + value + ")"; } } } [CanBeNull] public virtual string GetSaturationDescription() { return GetIndexedDescription(PentaxMakernoteDirectory.TagSaturation, "Normal", "Low", "High"); } [CanBeNull] public virtual string GetContrastDescription() { return GetIndexedDescription(PentaxMakernoteDirectory.TagContrast, "Normal", "Low", "High"); } [CanBeNull] public virtual string GetSharpnessDescription() { return GetIndexedDescription(PentaxMakernoteDirectory.TagSharpness, "Normal", "Soft", "Hard"); } [CanBeNull] public virtual string GetDigitalZoomDescription() { float? value = _directory.GetFloatObject(PentaxMakernoteDirectory.TagDigitalZoom); if (value == null) { return null; } if (value == 0) { return "Off"; } return Sharpen.Extensions.ConvertToString((float)value); } [CanBeNull] public virtual string GetWhiteBalanceDescription() { return GetIndexedDescription(PentaxMakernoteDirectory.TagWhiteBalance, "Auto", "Daylight", "Shade", "Tungsten", "Fluorescent", "Manual"); } [CanBeNull] public virtual string GetFlashModeDescription() { return GetIndexedDescription(PentaxMakernoteDirectory.TagFlashMode, 1, "Auto", "Flash On", null, "Flash Off", null, "Red-eye Reduction"); } [CanBeNull] public virtual string GetFocusModeDescription() { return GetIndexedDescription(PentaxMakernoteDirectory.TagFocusMode, 2, "Custom", "Auto"); } [CanBeNull] public virtual string GetQualityLevelDescription() { return GetIndexedDescription(PentaxMakernoteDirectory.TagQualityLevel, "Good", "Better", "Best"); } [CanBeNull] public virtual string GetCaptureModeDescription() { return GetIndexedDescription(PentaxMakernoteDirectory.TagCaptureMode, "Auto", "Night-scene", "Manual", null, "Multiple"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. // using System; using System.Collections; using System.Diagnostics; using System.Reflection; using System.Security; namespace System.Runtime.InteropServices.WindowsRuntime { internal sealed class CLRIReferenceImpl<T> : CLRIPropertyValueImpl, IReference<T>, IGetProxyTarget { private T _value; public CLRIReferenceImpl(PropertyType type, T obj) : base(type, obj) { Debug.Assert(obj != null, "Must not be null"); _value = obj; } public T Value { get { return _value; } } public override string ToString() { if (_value != null) { return _value.ToString(); } else { return base.ToString(); } } object IGetProxyTarget.GetTarget() { return (object)_value; } // We have T in an IReference<T>. Need to QI for IReference<T> with the appropriate GUID, call // the get_Value property, allocate an appropriately-sized managed object, marshal the native object // to the managed object, and free the native method. Also we want the return value boxed (aka normal value type boxing). // // This method is called by VM. internal static Object UnboxHelper(Object wrapper) { Debug.Assert(wrapper != null); IReference<T> reference = (IReference<T>)wrapper; Debug.Assert(reference != null, "CLRIReferenceImpl::UnboxHelper - QI'ed for IReference<" + typeof(T) + ">, but that failed."); return reference.Value; } } // T can be any WinRT-compatible type internal sealed class CLRIReferenceArrayImpl<T> : CLRIPropertyValueImpl, IGetProxyTarget, IReferenceArray<T>, IList // Jupiter data binding needs IList/IEnumerable { private T[] _value; private IList _list; public CLRIReferenceArrayImpl(PropertyType type, T[] obj) : base(type, obj) { Debug.Assert(obj != null, "Must not be null"); _value = obj; _list = (IList)_value; } public T[] Value { get { return _value; } } public override string ToString() { if (_value != null) { return _value.ToString(); } else { return base.ToString(); } } // // IEnumerable methods. Used by data-binding in Jupiter when you try to data bind // against a managed array // IEnumerator IEnumerable.GetEnumerator() { return ((IEnumerable)_value).GetEnumerator(); } // // IList & ICollection methods. // This enables two-way data binding and index access in Jupiter // Object IList.this[int index] { get { return _list[index]; } set { _list[index] = value; } } int IList.Add(Object value) { return _list.Add(value); } bool IList.Contains(Object value) { return _list.Contains(value); } void IList.Clear() { _list.Clear(); } bool IList.IsReadOnly { get { return _list.IsReadOnly; } } bool IList.IsFixedSize { get { return _list.IsFixedSize; } } int IList.IndexOf(Object value) { return _list.IndexOf(value); } void IList.Insert(int index, Object value) { _list.Insert(index, value); } void IList.Remove(Object value) { _list.Remove(value); } void IList.RemoveAt(int index) { _list.RemoveAt(index); } void ICollection.CopyTo(Array array, int index) { _list.CopyTo(array, index); } int ICollection.Count { get { return _list.Count; } } Object ICollection.SyncRoot { get { return _list.SyncRoot; } } bool ICollection.IsSynchronized { get { return _list.IsSynchronized; } } object IGetProxyTarget.GetTarget() { return (object)_value; } // We have T in an IReferenceArray<T>. Need to QI for IReferenceArray<T> with the appropriate GUID, call // the get_Value property, allocate an appropriately-sized managed object, marshal the native object // to the managed object, and free the native method. // // This method is called by VM. internal static Object UnboxHelper(Object wrapper) { Debug.Assert(wrapper != null); IReferenceArray<T> reference = (IReferenceArray<T>)wrapper; Debug.Assert(reference != null, "CLRIReferenceArrayImpl::UnboxHelper - QI'ed for IReferenceArray<" + typeof(T) + ">, but that failed."); T[] marshaled = reference.Value; return marshaled; } } // For creating instances of Windows Runtime's IReference<T> and IReferenceArray<T>. internal static class IReferenceFactory { internal static readonly Type s_pointType = Type.GetType("Windows.Foundation.Point, " + AssemblyRef.SystemRuntimeWindowsRuntime); internal static readonly Type s_rectType = Type.GetType("Windows.Foundation.Rect, " + AssemblyRef.SystemRuntimeWindowsRuntime); internal static readonly Type s_sizeType = Type.GetType("Windows.Foundation.Size, " + AssemblyRef.SystemRuntimeWindowsRuntime); internal static Object CreateIReference(Object obj) { Debug.Assert(obj != null, "Null should not be boxed."); Type type = obj.GetType(); if (type.IsArray) return CreateIReferenceArray((Array)obj); if (type == typeof(int)) return new CLRIReferenceImpl<int>(PropertyType.Int32, (int)obj); if (type == typeof(String)) return new CLRIReferenceImpl<String>(PropertyType.String, (String)obj); if (type == typeof(byte)) return new CLRIReferenceImpl<byte>(PropertyType.UInt8, (byte)obj); if (type == typeof(short)) return new CLRIReferenceImpl<short>(PropertyType.Int16, (short)obj); if (type == typeof(ushort)) return new CLRIReferenceImpl<ushort>(PropertyType.UInt16, (ushort)obj); if (type == typeof(uint)) return new CLRIReferenceImpl<uint>(PropertyType.UInt32, (uint)obj); if (type == typeof(long)) return new CLRIReferenceImpl<long>(PropertyType.Int64, (long)obj); if (type == typeof(ulong)) return new CLRIReferenceImpl<ulong>(PropertyType.UInt64, (ulong)obj); if (type == typeof(float)) return new CLRIReferenceImpl<float>(PropertyType.Single, (float)obj); if (type == typeof(double)) return new CLRIReferenceImpl<double>(PropertyType.Double, (double)obj); if (type == typeof(char)) return new CLRIReferenceImpl<char>(PropertyType.Char16, (char)obj); if (type == typeof(bool)) return new CLRIReferenceImpl<bool>(PropertyType.Boolean, (bool)obj); if (type == typeof(Guid)) return new CLRIReferenceImpl<Guid>(PropertyType.Guid, (Guid)obj); if (type == typeof(DateTimeOffset)) return new CLRIReferenceImpl<DateTimeOffset>(PropertyType.DateTime, (DateTimeOffset)obj); if (type == typeof(TimeSpan)) return new CLRIReferenceImpl<TimeSpan>(PropertyType.TimeSpan, (TimeSpan)obj); if (type == typeof(Object)) return new CLRIReferenceImpl<Object>(PropertyType.Inspectable, (Object)obj); if (type == typeof(RuntimeType)) { // If the type is System.RuntimeType, we want to use System.Type marshaler (it's parent of the type) return new CLRIReferenceImpl<Type>(PropertyType.Other, (Type)obj); } // Handle arbitrary WinRT-compatible value types, and recognize a few special types. PropertyType? propType = null; if (type == s_pointType) { propType = PropertyType.Point; } else if (type == s_rectType) { propType = PropertyType.Rect; } else if (type == s_sizeType) { propType = PropertyType.Size; } else if (type.IsValueType || obj is Delegate) { propType = PropertyType.Other; } if (propType.HasValue) { Type specificType = typeof(CLRIReferenceImpl<>).MakeGenericType(type); return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj }); } Debug.Fail("We should not see non-WinRT type here"); return null; } internal static Object CreateIReferenceArray(Array obj) { Debug.Assert(obj != null); Debug.Assert(obj.GetType().IsArray); Type type = obj.GetType().GetElementType(); Debug.Assert(obj.Rank == 1 && obj.GetLowerBound(0) == 0 && !type.IsArray); if (type == typeof(int)) return new CLRIReferenceArrayImpl<int>(PropertyType.Int32Array, (int[])obj); if (type == typeof(String)) return new CLRIReferenceArrayImpl<String>(PropertyType.StringArray, (String[])obj); if (type == typeof(byte)) return new CLRIReferenceArrayImpl<byte>(PropertyType.UInt8Array, (byte[])obj); if (type == typeof(short)) return new CLRIReferenceArrayImpl<short>(PropertyType.Int16Array, (short[])obj); if (type == typeof(ushort)) return new CLRIReferenceArrayImpl<ushort>(PropertyType.UInt16Array, (ushort[])obj); if (type == typeof(uint)) return new CLRIReferenceArrayImpl<uint>(PropertyType.UInt32Array, (uint[])obj); if (type == typeof(long)) return new CLRIReferenceArrayImpl<long>(PropertyType.Int64Array, (long[])obj); if (type == typeof(ulong)) return new CLRIReferenceArrayImpl<ulong>(PropertyType.UInt64Array, (ulong[])obj); if (type == typeof(float)) return new CLRIReferenceArrayImpl<float>(PropertyType.SingleArray, (float[])obj); if (type == typeof(double)) return new CLRIReferenceArrayImpl<double>(PropertyType.DoubleArray, (double[])obj); if (type == typeof(char)) return new CLRIReferenceArrayImpl<char>(PropertyType.Char16Array, (char[])obj); if (type == typeof(bool)) return new CLRIReferenceArrayImpl<bool>(PropertyType.BooleanArray, (bool[])obj); if (type == typeof(Guid)) return new CLRIReferenceArrayImpl<Guid>(PropertyType.GuidArray, (Guid[])obj); if (type == typeof(DateTimeOffset)) return new CLRIReferenceArrayImpl<DateTimeOffset>(PropertyType.DateTimeArray, (DateTimeOffset[])obj); if (type == typeof(TimeSpan)) return new CLRIReferenceArrayImpl<TimeSpan>(PropertyType.TimeSpanArray, (TimeSpan[])obj); if (type == typeof(Type)) { // Note: The array type will be System.Type, not System.RuntimeType return new CLRIReferenceArrayImpl<Type>(PropertyType.OtherArray, (Type[])obj); } PropertyType? propType = null; if (type == s_pointType) { propType = PropertyType.PointArray; } else if (type == s_rectType) { propType = PropertyType.RectArray; } else if (type == s_sizeType) { propType = PropertyType.SizeArray; } else if (type.IsValueType) { // note that KeyValuePair`2 is a reference type on the WinRT side so the array // must be wrapped with CLRIReferenceArrayImpl<Object> if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(System.Collections.Generic.KeyValuePair<,>)) { Object[] objArray = new Object[obj.Length]; for (int i = 0; i < objArray.Length; i++) { objArray[i] = obj.GetValue(i); } obj = objArray; } else { propType = PropertyType.OtherArray; } } else if (typeof(Delegate).IsAssignableFrom(type)) { propType = PropertyType.OtherArray; } if (propType.HasValue) { // All WinRT value type will be Property.Other Type specificType = typeof(CLRIReferenceArrayImpl<>).MakeGenericType(type); return Activator.CreateInstance(specificType, new Object[] { propType.Value, obj }); } else { // All WinRT reference type (including arbitary managed type) will be PropertyType.ObjectArray return new CLRIReferenceArrayImpl<Object>(PropertyType.InspectableArray, (Object[])obj); } } } }
#region Copyright (c) 2009 S. van Deursen /* The CuttingEdge.Conditions library enables developers to validate pre- and postconditions in a fluent * manner. * * To contact me, please visit my blog at http://www.cuttingedge.it/blogs/steven/ * * Copyright (c) 2009 S. van Deursen * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and * associated documentation files (the "Software"), to deal in the Software without restriction, including * without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the * following conditions: * * The above copyright notice and this permission notice shall be included in all copies or substantial * portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT * LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO * EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER * IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE * USE OR OTHER DEALINGS IN THE SOFTWARE. */ #endregion using System; using System.Linq.Expressions; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CuttingEdge.Conditions.UnitTests.EvaluationTests { [TestClass] public class EvaluationEvaluateTests { [TestMethod] [Description("Calling Evaluate on integer x with boolean 'true' should pass.")] public void EvaluateTest01() { int a = 3; Condition.Requires(a).Evaluate(true); } [TestMethod] [Description("Calling the Evaluate overload with the description on integer x with boolean 'true' should pass.")] public void EvaluateTest02() { int a = 3; Condition.Requires(a).Evaluate(true, String.Empty); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling Evaluate on integer x with boolean 'false' should fail.")] public void EvaluateTest03() { int a = 3; Condition.Requires(a).Evaluate(false); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling the Evaluate overload with the description on integer x with boolean 'false' should fail.")] public void EvaluateTest04() { int a = 3; Condition.Requires(a).Evaluate(false, String.Empty); } [TestMethod] [Description("Calling Evaluate on integer x (3) with expression '(x) => (x == 3)' should pass.")] public void EvaluateTest05() { int a = 3; Expression<Func<int, bool>> expression = x => (x == 3); Condition.Requires(a).Evaluate(expression); } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling Evaluate on integer x (3) with expression '(x) => (x == 4)' should fail.")] public void EvaluateTest06() { int a = 3; Condition.Requires(a).Evaluate(x => x == 4); } [TestMethod] [Description("Calling Evaluate on string x (hoi) with expression '(x) => (x == hoi)' should pass.")] public void EvaluateTest07() { string a = "hoi"; Condition.Requires(a).Evaluate(x => x == "hoi"); } [TestMethod] [Description("Calling Evaluate on object x with expression 'x => true' should pass.")] public void EvaluateTest08() { object a = new object(); Condition.Requires(a).Evaluate(x => true); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] [Description("Calling Evaluate on null object x with expression '(x) => (x != null)' should fail with ArgumentNullException.")] public void EvaluateTest09() { object a = null; Condition.Requires(a).Evaluate(x => x != null); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] [Description("Calling Evaluate on null object x with expression '(x) => (x == 3)' should fail with ArgumentNullException.")] public void EvaluateTest10() { int? a = null; Condition.Requires(a).Evaluate(x => x == 3); } [TestMethod] [ExpectedException(typeof(ArgumentNullException))] [Description("Calling Evaluate on null object x with boolean 'false' should fail with ArgumentNullException.")] public void EvaluateTest11() { object a = null; Condition.Requires(a).Evaluate(false); } [TestMethod] [ExpectedException(typeof(System.ComponentModel.InvalidEnumArgumentException))] [Description("Calling Evaluate on enum x with boolean 'false' should fail with InvalidEnumArgumentException.")] public void EvaluateTest12() { DayOfWeek day = DayOfWeek.Thursday; Condition.Requires(day).Evaluate(false); } [TestMethod] [ExpectedException(typeof(System.ComponentModel.InvalidEnumArgumentException))] [Description("Calling Evaluate on enum x with expression 'x => false' should fail with InvalidEnumArgumentException.")] public void EvaluateTest13() { DayOfWeek day = DayOfWeek.Thursday; Condition.Requires(day).Evaluate(x => false); } [TestMethod] [Description("Calling the Evaluate overload containing the description message, should result in a exception message containing that description.")] public void EvaluateTest14() { string expectedMessage = "value should not be null. The actual value is null." + Environment.NewLine + TestHelper.CultureSensitiveArgumentExceptionParameterText + ": value"; object a = null; try { Condition.Requires(a).Evaluate(a != null, "{0} should not be null"); } catch (Exception ex) { Assert.AreEqual(expectedMessage, ex.Message); } } [TestMethod] [Description("Calling the Evaluate overload containing a invalid description message, should pass and result in a exception message containing that description.")] public void EvaluateTest15() { string expectedMessage = "{1} should not be null. The actual value is null." + Environment.NewLine + TestHelper.CultureSensitiveArgumentExceptionParameterText + ": value"; object a = null; try { Condition.Requires(a).Evaluate(a != null, "{1} should not be null"); } catch (Exception ex) { Assert.AreEqual(expectedMessage, ex.Message); } } [TestMethod] [ExpectedException(typeof(ArgumentException))] [Description("Calling Evaluate with lambda 'null' should fail with an ArgumentException.")] public void EvaluateTest16() { Condition.Requires(3).Evaluate(null); } [TestMethod] [ExpectedException(typeof(PostconditionException))] [Description("Calling Evaluate with lambda 'null' should fail with an PostconditionException.")] public void EvaluateTest17() { Condition.Ensures(3).Evaluate(null); } [TestMethod] [Description("Calling Evaluate with boolen 'false' should succeed when exceptions are suppressed.")] public void EvaluateTest18() { Condition.Requires(3).SuppressExceptionsForTest().Evaluate(false); } [TestMethod] [Description("Calling Evaluate with lambda 'null' should succeed when exceptions are suppressed.")] public void EvaluateTest19() { Condition.Requires(3).SuppressExceptionsForTest().Evaluate(null); } } }
//--------------------------------------------------------------------------- // // File: HtmlSchema.cs // // Copyright (C) Microsoft Corporation. All rights reserved. // // Description: Static information about HTML structure // //--------------------------------------------------------------------------- namespace Html { using System.Diagnostics; using System.Collections; /// <summary> /// HtmlSchema class /// maintains static information about HTML structure /// can be used by HtmlParser to check conditions under which an element starts or ends, etc. /// </summary> internal class HtmlSchema { // --------------------------------------------------------------------- // // Constructors // // --------------------------------------------------------------------- #region Constructors /// <summary> /// static constructor, initializes the ArrayLists /// that hold the elements in various sub-components of the schema /// e.g _htmlEmptyElements, etc. /// </summary> static HtmlSchema() { // initializes the list of all html elements InitializeInlineElements(); InitializeBlockElements(); InitializeOtherOpenableElements(); // initialize empty elements list InitializeEmptyElements(); // initialize list of elements closing on the outer element end InitializeElementsClosingOnParentElementEnd(); // initalize list of elements that close when a new element starts InitializeElementsClosingOnNewElementStart(); // Initialize character entities InitializeHtmlCharacterEntities(); } #endregion Constructors; // --------------------------------------------------------------------- // // Internal Methods // // --------------------------------------------------------------------- #region Internal Methods /// <summary> /// returns true when xmlElementName corresponds to empty element /// </summary> /// <param name="xmlElementName"> /// string representing name to test /// </param> internal static bool IsEmptyElement(string xmlElementName) { // convert to lowercase before we check // because element names are not case sensitive return _htmlEmptyElements.Contains(xmlElementName.ToLower()); } /// <summary> /// returns true if xmlElementName represents a block formattinng element. /// It used in an algorithm of transferring inline elements over block elements /// in HtmlParser /// </summary> /// <param name="xmlElementName"></param> /// <returns></returns> internal static bool IsBlockElement(string xmlElementName) { return _htmlBlockElements.Contains(xmlElementName); } /// <summary> /// returns true if the xmlElementName represents an inline formatting element /// </summary> /// <param name="xmlElementName"></param> /// <returns></returns> internal static bool IsInlineElement(string xmlElementName) { return _htmlInlineElements.Contains(xmlElementName); } /// <summary> /// It is a list of known html elements which we /// want to allow to produce bt HTML parser, /// but don'tt want to act as inline, block or no-scope. /// Presence in this list will allow to open /// elements during html parsing, and adding the /// to a tree produced by html parser. /// </summary> internal static bool IsKnownOpenableElement(string xmlElementName) { return _htmlOtherOpenableElements.Contains(xmlElementName); } /// <summary> /// returns true when xmlElementName closes when the outer element closes /// this is true of elements with optional start tags /// </summary> /// <param name="xmlElementName"> /// string representing name to test /// </param> internal static bool ClosesOnParentElementEnd(string xmlElementName) { // convert to lowercase when testing return _htmlElementsClosingOnParentElementEnd.Contains(xmlElementName.ToLower()); } /// <summary> /// returns true if the current element closes when the new element, whose name has just been read, starts /// </summary> /// <param name="currentElementName"> /// string representing current element name /// </param> /// <param name="elementName"></param> /// string representing name of the next element that will start internal static bool ClosesOnNextElementStart(string currentElementName, string nextElementName) { Debug.Assert(currentElementName == currentElementName.ToLower()); switch (currentElementName) { case "colgroup": return _htmlElementsClosingColgroup.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "dd": return _htmlElementsClosingDD.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "dt": return _htmlElementsClosingDT.Contains(nextElementName) && HtmlSchema.IsBlockElement(nextElementName); case "li": return _htmlElementsClosingLI.Contains(nextElementName); case "p": return HtmlSchema.IsBlockElement(nextElementName); case "tbody": return _htmlElementsClosingTbody.Contains(nextElementName); case "tfoot": return _htmlElementsClosingTfoot.Contains(nextElementName); case "thead": return _htmlElementsClosingThead.Contains(nextElementName); case "tr": return _htmlElementsClosingTR.Contains(nextElementName); case "td": return _htmlElementsClosingTD.Contains(nextElementName); case "th": return _htmlElementsClosingTH.Contains(nextElementName); } return false; } /// <summary> /// returns true if the string passed as argument is an Html entity name /// </summary> /// <param name="entityName"> /// string to be tested for Html entity name /// </param> internal static bool IsEntity(string entityName) { // we do not convert entity strings to lowercase because these names are case-sensitive if (_htmlCharacterEntities.Contains(entityName)) { return true; } else { return false; } } /// <summary> /// returns the character represented by the entity name string which is passed as an argument, if the string is an entity name /// as specified in _htmlCharacterEntities, returns the character value of 0 otherwise /// </summary> /// <param name="entityName"> /// string representing entity name whose character value is desired /// </param> internal static char EntityCharacterValue(string entityName) { if (_htmlCharacterEntities.Contains(entityName)) { return (char) _htmlCharacterEntities[entityName]; } else { return (char)0; } } #endregion Internal Methods // --------------------------------------------------------------------- // // Internal Properties // // --------------------------------------------------------------------- #region Internal Properties #endregion Internal Indexers // --------------------------------------------------------------------- // // Private Methods // // --------------------------------------------------------------------- #region Private Methods private static void InitializeInlineElements() { _htmlInlineElements = new ArrayList(); _htmlInlineElements.Add("a"); _htmlInlineElements.Add("abbr"); _htmlInlineElements.Add("acronym"); _htmlInlineElements.Add("address"); _htmlInlineElements.Add("b"); _htmlInlineElements.Add("bdo"); // ??? _htmlInlineElements.Add("big"); _htmlInlineElements.Add("button"); _htmlInlineElements.Add("code"); _htmlInlineElements.Add("del"); // deleted text _htmlInlineElements.Add("dfn"); _htmlInlineElements.Add("em"); _htmlInlineElements.Add("font"); _htmlInlineElements.Add("i"); _htmlInlineElements.Add("ins"); // inserted text _htmlInlineElements.Add("kbd"); // text to entered by a user _htmlInlineElements.Add("label"); _htmlInlineElements.Add("legend"); // ??? _htmlInlineElements.Add("q"); // short inline quotation _htmlInlineElements.Add("s"); // strike-through text style _htmlInlineElements.Add("samp"); // Specifies a code sample _htmlInlineElements.Add("small"); _htmlInlineElements.Add("span"); _htmlInlineElements.Add("strike"); _htmlInlineElements.Add("strong"); _htmlInlineElements.Add("sub"); _htmlInlineElements.Add("sup"); _htmlInlineElements.Add("u"); _htmlInlineElements.Add("var"); // indicates an instance of a program variable } private static void InitializeBlockElements() { _htmlBlockElements = new ArrayList(); _htmlBlockElements.Add("blockquote"); _htmlBlockElements.Add("body"); _htmlBlockElements.Add("caption"); _htmlBlockElements.Add("center"); _htmlBlockElements.Add("cite"); _htmlBlockElements.Add("dd"); _htmlBlockElements.Add("dir"); // treat as UL element _htmlBlockElements.Add("div"); _htmlBlockElements.Add("dl"); _htmlBlockElements.Add("dt"); _htmlBlockElements.Add("form"); // Not a block according to XHTML spec _htmlBlockElements.Add("h1"); _htmlBlockElements.Add("h2"); _htmlBlockElements.Add("h3"); _htmlBlockElements.Add("h4"); _htmlBlockElements.Add("h5"); _htmlBlockElements.Add("h6"); _htmlBlockElements.Add("html"); _htmlBlockElements.Add("li"); _htmlBlockElements.Add("menu"); // treat as UL element _htmlBlockElements.Add("ol"); _htmlBlockElements.Add("p"); _htmlBlockElements.Add("pre"); // Renders text in a fixed-width font _htmlBlockElements.Add("table"); _htmlBlockElements.Add("tbody"); _htmlBlockElements.Add("td"); _htmlBlockElements.Add("textarea"); _htmlBlockElements.Add("tfoot"); _htmlBlockElements.Add("th"); _htmlBlockElements.Add("thead"); _htmlBlockElements.Add("tr"); _htmlBlockElements.Add("tt"); _htmlBlockElements.Add("ul"); } /// <summary> /// initializes _htmlEmptyElements with empty elements in HTML 4 spec at /// http://www.w3.org/TR/REC-html40/index/elements.html /// </summary> private static void InitializeEmptyElements() { // Build a list of empty (no-scope) elements // (element not requiring closing tags, and not accepting any content) _htmlEmptyElements = new ArrayList(); _htmlEmptyElements.Add("area"); _htmlEmptyElements.Add("base"); _htmlEmptyElements.Add("basefont"); _htmlEmptyElements.Add("br"); _htmlEmptyElements.Add("col"); _htmlEmptyElements.Add("frame"); _htmlEmptyElements.Add("hr"); _htmlEmptyElements.Add("img"); _htmlEmptyElements.Add("input"); _htmlEmptyElements.Add("isindex"); _htmlEmptyElements.Add("link"); _htmlEmptyElements.Add("meta"); _htmlEmptyElements.Add("param"); } private static void InitializeOtherOpenableElements() { // It is a list of known html elements which we // want to allow to produce bt HTML parser, // but don'tt want to act as inline, block or no-scope. // Presence in this list will allow to open // elements during html parsing, and adding the // to a tree produced by html parser. _htmlOtherOpenableElements = new ArrayList(); _htmlOtherOpenableElements.Add("applet"); _htmlOtherOpenableElements.Add("base"); _htmlOtherOpenableElements.Add("basefont"); _htmlOtherOpenableElements.Add("colgroup"); _htmlOtherOpenableElements.Add("fieldset"); //_htmlOtherOpenableElements.Add("form"); --> treated as block _htmlOtherOpenableElements.Add("frameset"); _htmlOtherOpenableElements.Add("head"); _htmlOtherOpenableElements.Add("iframe"); _htmlOtherOpenableElements.Add("map"); _htmlOtherOpenableElements.Add("noframes"); _htmlOtherOpenableElements.Add("noscript"); _htmlOtherOpenableElements.Add("object"); _htmlOtherOpenableElements.Add("optgroup"); _htmlOtherOpenableElements.Add("option"); _htmlOtherOpenableElements.Add("script"); _htmlOtherOpenableElements.Add("select"); _htmlOtherOpenableElements.Add("style"); _htmlOtherOpenableElements.Add("title"); } /// <summary> /// initializes _htmlElementsClosingOnParentElementEnd with the list of HTML 4 elements for which closing tags are optional /// we assume that for any element for which closing tags are optional, the element closes when it's outer element /// (in which it is nested) does /// </summary> private static void InitializeElementsClosingOnParentElementEnd() { _htmlElementsClosingOnParentElementEnd = new ArrayList(); _htmlElementsClosingOnParentElementEnd.Add("body"); _htmlElementsClosingOnParentElementEnd.Add("colgroup"); _htmlElementsClosingOnParentElementEnd.Add("dd"); _htmlElementsClosingOnParentElementEnd.Add("dt"); _htmlElementsClosingOnParentElementEnd.Add("head"); _htmlElementsClosingOnParentElementEnd.Add("html"); _htmlElementsClosingOnParentElementEnd.Add("li"); _htmlElementsClosingOnParentElementEnd.Add("p"); _htmlElementsClosingOnParentElementEnd.Add("tbody"); _htmlElementsClosingOnParentElementEnd.Add("td"); _htmlElementsClosingOnParentElementEnd.Add("tfoot"); _htmlElementsClosingOnParentElementEnd.Add("thead"); _htmlElementsClosingOnParentElementEnd.Add("th"); _htmlElementsClosingOnParentElementEnd.Add("tr"); } private static void InitializeElementsClosingOnNewElementStart() { _htmlElementsClosingColgroup = new ArrayList(); _htmlElementsClosingColgroup.Add("colgroup"); _htmlElementsClosingColgroup.Add("tr"); _htmlElementsClosingColgroup.Add("thead"); _htmlElementsClosingColgroup.Add("tfoot"); _htmlElementsClosingColgroup.Add("tbody"); _htmlElementsClosingDD = new ArrayList(); _htmlElementsClosingDD.Add("dd"); _htmlElementsClosingDD.Add("dt"); // TODO: dd may end in other cases as well - if a new "p" starts, etc. // TODO: these are the basic "legal" cases but there may be more recovery _htmlElementsClosingDT = new ArrayList(); _htmlElementsClosingDD.Add("dd"); _htmlElementsClosingDD.Add("dt"); // TODO: dd may end in other cases as well - if a new "p" starts, etc. // TODO: these are the basic "legal" cases but there may be more recovery _htmlElementsClosingLI = new ArrayList(); _htmlElementsClosingLI.Add("li"); // TODO: more complex recovery _htmlElementsClosingTbody = new ArrayList(); _htmlElementsClosingTbody.Add("tbody"); _htmlElementsClosingTbody.Add("thead"); _htmlElementsClosingTbody.Add("tfoot"); // TODO: more complex recovery _htmlElementsClosingTR = new ArrayList(); // NOTE: tr should not really close on a new thead // because if there are rows before a thead, it is assumed to be in tbody, whose start tag is optional // and thead can't come after tbody // however, if we do encounter this, it's probably best to end the row and ignore the thead or treat // it as part of the table _htmlElementsClosingTR.Add("thead"); _htmlElementsClosingTR.Add("tfoot"); _htmlElementsClosingTR.Add("tbody"); _htmlElementsClosingTR.Add("tr"); // TODO: more complex recovery _htmlElementsClosingTD = new ArrayList(); _htmlElementsClosingTD.Add("td"); _htmlElementsClosingTD.Add("th"); _htmlElementsClosingTD.Add("tr"); _htmlElementsClosingTD.Add("tbody"); _htmlElementsClosingTD.Add("tfoot"); _htmlElementsClosingTD.Add("thead"); // TODO: more complex recovery _htmlElementsClosingTH = new ArrayList(); _htmlElementsClosingTH.Add("td"); _htmlElementsClosingTH.Add("th"); _htmlElementsClosingTH.Add("tr"); _htmlElementsClosingTH.Add("tbody"); _htmlElementsClosingTH.Add("tfoot"); _htmlElementsClosingTH.Add("thead"); // TODO: more complex recovery _htmlElementsClosingThead = new ArrayList(); _htmlElementsClosingThead.Add("tbody"); _htmlElementsClosingThead.Add("tfoot"); // TODO: more complex recovery _htmlElementsClosingTfoot = new ArrayList(); _htmlElementsClosingTfoot.Add("tbody"); // although thead comes before tfoot, we add it because if it is found the tfoot should close // and some recovery processing be done on the thead _htmlElementsClosingTfoot.Add("thead"); // TODO: more complex recovery } /// <summary> /// initializes _htmlCharacterEntities hashtable with the character corresponding to entity names /// </summary> private static void InitializeHtmlCharacterEntities() { _htmlCharacterEntities = new Hashtable(); _htmlCharacterEntities["Aacute"] = (char)193; _htmlCharacterEntities["aacute"] = (char)225; _htmlCharacterEntities["Acirc"] = (char)194; _htmlCharacterEntities["acirc"] = (char)226; _htmlCharacterEntities["acute"] = (char)180; _htmlCharacterEntities["AElig"] = (char)198; _htmlCharacterEntities["aelig"] = (char)230; _htmlCharacterEntities["Agrave"] = (char)192; _htmlCharacterEntities["agrave"] = (char)224; _htmlCharacterEntities["alefsym"] = (char)8501; _htmlCharacterEntities["Alpha"] = (char)913; _htmlCharacterEntities["alpha"] = (char)945; _htmlCharacterEntities["amp"] = (char)38; _htmlCharacterEntities["and"] = (char)8743; _htmlCharacterEntities["ang"] = (char)8736; _htmlCharacterEntities["Aring"] = (char)197; _htmlCharacterEntities["aring"] = (char)229; _htmlCharacterEntities["asymp"] = (char)8776; _htmlCharacterEntities["Atilde"] = (char)195; _htmlCharacterEntities["atilde"] = (char)227; _htmlCharacterEntities["Auml"] = (char)196; _htmlCharacterEntities["auml"] = (char)228; _htmlCharacterEntities["bdquo"] = (char)8222; _htmlCharacterEntities["Beta"] = (char)914; _htmlCharacterEntities["beta"] = (char)946; _htmlCharacterEntities["brvbar"] = (char)166; _htmlCharacterEntities["bull"] = (char)8226; _htmlCharacterEntities["cap"] = (char)8745; _htmlCharacterEntities["Ccedil"] = (char)199; _htmlCharacterEntities["ccedil"] = (char)231; _htmlCharacterEntities["cent"] = (char)162; _htmlCharacterEntities["Chi"] = (char)935; _htmlCharacterEntities["chi"] = (char)967; _htmlCharacterEntities["circ"] = (char)710; _htmlCharacterEntities["clubs"] = (char)9827; _htmlCharacterEntities["cong"] = (char)8773; _htmlCharacterEntities["copy"] = (char)169; _htmlCharacterEntities["crarr"] = (char)8629; _htmlCharacterEntities["cup"] = (char)8746; _htmlCharacterEntities["curren"] = (char)164; _htmlCharacterEntities["dagger"] = (char)8224; _htmlCharacterEntities["Dagger"] = (char)8225; _htmlCharacterEntities["darr"] = (char)8595; _htmlCharacterEntities["dArr"] = (char)8659; _htmlCharacterEntities["deg"] = (char)176; _htmlCharacterEntities["Delta"] = (char)916; _htmlCharacterEntities["delta"] = (char)948; _htmlCharacterEntities["diams"] = (char)9830; _htmlCharacterEntities["divide"] = (char)247; _htmlCharacterEntities["Eacute"] = (char)201; _htmlCharacterEntities["eacute"] = (char)233; _htmlCharacterEntities["Ecirc"] = (char)202; _htmlCharacterEntities["ecirc"] = (char)234; _htmlCharacterEntities["Egrave"] = (char)200; _htmlCharacterEntities["egrave"] = (char)232; _htmlCharacterEntities["empty"] = (char)8709; _htmlCharacterEntities["emsp"] = (char)8195; _htmlCharacterEntities["ensp"] = (char)8194; _htmlCharacterEntities["Epsilon"] = (char)917; _htmlCharacterEntities["epsilon"] = (char)949; _htmlCharacterEntities["equiv"] = (char)8801; _htmlCharacterEntities["Eta"] = (char)919; _htmlCharacterEntities["eta"] = (char)951; _htmlCharacterEntities["ETH"] = (char)208; _htmlCharacterEntities["eth"] = (char)240; _htmlCharacterEntities["Euml"] = (char)203; _htmlCharacterEntities["euml"] = (char)235; _htmlCharacterEntities["euro"] = (char)8364; _htmlCharacterEntities["exist"] = (char)8707; _htmlCharacterEntities["fnof"] = (char)402; _htmlCharacterEntities["forall"] = (char)8704; _htmlCharacterEntities["frac12"] = (char)189; _htmlCharacterEntities["frac14"] = (char)188; _htmlCharacterEntities["frac34"] = (char)190; _htmlCharacterEntities["frasl"] = (char)8260; _htmlCharacterEntities["Gamma"] = (char)915; _htmlCharacterEntities["gamma"] = (char)947; _htmlCharacterEntities["ge"] = (char)8805; _htmlCharacterEntities["gt"] = (char)62; _htmlCharacterEntities["harr"] = (char)8596; _htmlCharacterEntities["hArr"] = (char)8660; _htmlCharacterEntities["hearts"] = (char)9829; _htmlCharacterEntities["hellip"] = (char)8230; _htmlCharacterEntities["Iacute"] = (char)205; _htmlCharacterEntities["iacute"] = (char)237; _htmlCharacterEntities["Icirc"] = (char)206; _htmlCharacterEntities["icirc"] = (char)238; _htmlCharacterEntities["iexcl"] = (char)161; _htmlCharacterEntities["Igrave"] = (char)204; _htmlCharacterEntities["igrave"] = (char)236; _htmlCharacterEntities["image"] = (char)8465; _htmlCharacterEntities["infin"] = (char)8734; _htmlCharacterEntities["int"] = (char)8747; _htmlCharacterEntities["Iota"] = (char)921; _htmlCharacterEntities["iota"] = (char)953; _htmlCharacterEntities["iquest"] = (char)191; _htmlCharacterEntities["isin"] = (char)8712; _htmlCharacterEntities["Iuml"] = (char)207; _htmlCharacterEntities["iuml"] = (char)239; _htmlCharacterEntities["Kappa"] = (char)922; _htmlCharacterEntities["kappa"] = (char)954; _htmlCharacterEntities["Lambda"] = (char)923; _htmlCharacterEntities["lambda"] = (char)955; _htmlCharacterEntities["lang"] = (char)9001; _htmlCharacterEntities["laquo"] = (char)171; _htmlCharacterEntities["larr"] = (char)8592; _htmlCharacterEntities["lArr"] = (char)8656; _htmlCharacterEntities["lceil"] = (char)8968; _htmlCharacterEntities["ldquo"] = (char)8220; _htmlCharacterEntities["le"] = (char)8804; _htmlCharacterEntities["lfloor"] = (char)8970; _htmlCharacterEntities["lowast"] = (char)8727; _htmlCharacterEntities["loz"] = (char)9674; _htmlCharacterEntities["lrm"] = (char)8206; _htmlCharacterEntities["lsaquo"] = (char)8249; _htmlCharacterEntities["lsquo"] = (char)8216; _htmlCharacterEntities["lt"] = (char)60; _htmlCharacterEntities["macr"] = (char)175; _htmlCharacterEntities["mdash"] = (char)8212; _htmlCharacterEntities["micro"] = (char)181; _htmlCharacterEntities["middot"] = (char)183; _htmlCharacterEntities["minus"] = (char)8722; _htmlCharacterEntities["Mu"] = (char)924; _htmlCharacterEntities["mu"] = (char)956; _htmlCharacterEntities["nabla"] = (char)8711; _htmlCharacterEntities["nbsp"] = (char)160; _htmlCharacterEntities["ndash"] = (char)8211; _htmlCharacterEntities["ne"] = (char)8800; _htmlCharacterEntities["ni"] = (char)8715; _htmlCharacterEntities["not"] = (char)172; _htmlCharacterEntities["notin"] = (char)8713; _htmlCharacterEntities["nsub"] = (char)8836; _htmlCharacterEntities["Ntilde"] = (char)209; _htmlCharacterEntities["ntilde"] = (char)241; _htmlCharacterEntities["Nu"] = (char)925; _htmlCharacterEntities["nu"] = (char)957; _htmlCharacterEntities["Oacute"] = (char)211; _htmlCharacterEntities["ocirc"] = (char)244; _htmlCharacterEntities["OElig"] = (char)338; _htmlCharacterEntities["oelig"] = (char)339; _htmlCharacterEntities["Ograve"] = (char)210; _htmlCharacterEntities["ograve"] = (char)242; _htmlCharacterEntities["oline"] = (char)8254; _htmlCharacterEntities["Omega"] = (char)937; _htmlCharacterEntities["omega"] = (char)969; _htmlCharacterEntities["Omicron"] = (char)927; _htmlCharacterEntities["omicron"] = (char)959; _htmlCharacterEntities["oplus"] = (char)8853; _htmlCharacterEntities["or"] = (char)8744; _htmlCharacterEntities["ordf"] = (char)170; _htmlCharacterEntities["ordm"] = (char)186; _htmlCharacterEntities["Oslash"] = (char)216; _htmlCharacterEntities["oslash"] = (char)248; _htmlCharacterEntities["Otilde"] = (char)213; _htmlCharacterEntities["otilde"] = (char)245; _htmlCharacterEntities["otimes"] = (char)8855; _htmlCharacterEntities["Ouml"] = (char)214; _htmlCharacterEntities["ouml"] = (char)246; _htmlCharacterEntities["para"] = (char)182; _htmlCharacterEntities["part"] = (char)8706; _htmlCharacterEntities["permil"] = (char)8240; _htmlCharacterEntities["perp"] = (char)8869; _htmlCharacterEntities["Phi"] = (char)934; _htmlCharacterEntities["phi"] = (char)966; _htmlCharacterEntities["pi"] = (char)960; _htmlCharacterEntities["piv"] = (char)982; _htmlCharacterEntities["plusmn"] = (char)177; _htmlCharacterEntities["pound"] = (char)163; _htmlCharacterEntities["prime"] = (char)8242; _htmlCharacterEntities["Prime"] = (char)8243; _htmlCharacterEntities["prod"] = (char)8719; _htmlCharacterEntities["prop"] = (char)8733; _htmlCharacterEntities["Psi"] = (char)936; _htmlCharacterEntities["psi"] = (char)968; _htmlCharacterEntities["quot"] = (char)34; _htmlCharacterEntities["radic"] = (char)8730; _htmlCharacterEntities["rang"] = (char)9002; _htmlCharacterEntities["raquo"] = (char)187; _htmlCharacterEntities["rarr"] = (char)8594; _htmlCharacterEntities["rArr"] = (char)8658; _htmlCharacterEntities["rceil"] = (char)8969; _htmlCharacterEntities["rdquo"] = (char)8221; _htmlCharacterEntities["real"] = (char)8476; _htmlCharacterEntities["reg"] = (char)174; _htmlCharacterEntities["rfloor"] = (char)8971; _htmlCharacterEntities["Rho"] = (char)929; _htmlCharacterEntities["rho"] = (char)961; _htmlCharacterEntities["rlm"] = (char)8207; _htmlCharacterEntities["rsaquo"] = (char)8250; _htmlCharacterEntities["rsquo"] = (char)8217; _htmlCharacterEntities["sbquo"] = (char)8218; _htmlCharacterEntities["Scaron"] = (char)352; _htmlCharacterEntities["scaron"] = (char)353; _htmlCharacterEntities["sdot"] = (char)8901; _htmlCharacterEntities["sect"] = (char)167; _htmlCharacterEntities["shy"] = (char)173; _htmlCharacterEntities["Sigma"] = (char)931; _htmlCharacterEntities["sigma"] = (char)963; _htmlCharacterEntities["sigmaf"] = (char)962; _htmlCharacterEntities["sim"] = (char)8764; _htmlCharacterEntities["spades"] = (char)9824; _htmlCharacterEntities["sub"] = (char)8834; _htmlCharacterEntities["sube"] = (char)8838; _htmlCharacterEntities["sum"] = (char)8721; _htmlCharacterEntities["sup"] = (char)8835; _htmlCharacterEntities["sup1"] = (char)185; _htmlCharacterEntities["sup2"] = (char)178; _htmlCharacterEntities["sup3"] = (char)179; _htmlCharacterEntities["supe"] = (char)8839; _htmlCharacterEntities["szlig"] = (char)223; _htmlCharacterEntities["Tau"] = (char)932; _htmlCharacterEntities["tau"] = (char)964; _htmlCharacterEntities["there4"] = (char)8756; _htmlCharacterEntities["Theta"] = (char)920; _htmlCharacterEntities["theta"] = (char)952; _htmlCharacterEntities["thetasym"] = (char)977; _htmlCharacterEntities["thinsp"] = (char)8201; _htmlCharacterEntities["THORN"] = (char)222; _htmlCharacterEntities["thorn"] = (char)254; _htmlCharacterEntities["tilde"] = (char)732; _htmlCharacterEntities["times"] = (char)215; _htmlCharacterEntities["trade"] = (char)8482; _htmlCharacterEntities["Uacute"] = (char)218; _htmlCharacterEntities["uacute"] = (char)250; _htmlCharacterEntities["uarr"] = (char)8593; _htmlCharacterEntities["uArr"] = (char)8657; _htmlCharacterEntities["Ucirc"] = (char)219; _htmlCharacterEntities["ucirc"] = (char)251; _htmlCharacterEntities["Ugrave"] = (char)217; _htmlCharacterEntities["ugrave"] = (char)249; _htmlCharacterEntities["uml"] = (char)168; _htmlCharacterEntities["upsih"] = (char)978; _htmlCharacterEntities["Upsilon"] = (char)933; _htmlCharacterEntities["upsilon"] = (char)965; _htmlCharacterEntities["Uuml"] = (char)220; _htmlCharacterEntities["uuml"] = (char)252; _htmlCharacterEntities["weierp"] = (char)8472; _htmlCharacterEntities["Xi"] = (char)926; _htmlCharacterEntities["xi"] = (char)958; _htmlCharacterEntities["Yacute"] = (char)221; _htmlCharacterEntities["yacute"] = (char)253; _htmlCharacterEntities["yen"] = (char)165; _htmlCharacterEntities["Yuml"] = (char)376; _htmlCharacterEntities["yuml"] = (char)255; _htmlCharacterEntities["Zeta"] = (char)918; _htmlCharacterEntities["zeta"] = (char)950; _htmlCharacterEntities["zwj"] = (char)8205; _htmlCharacterEntities["zwnj"] = (char)8204; } #endregion Private Methods // --------------------------------------------------------------------- // // Private Fields // // --------------------------------------------------------------------- #region Private Fields // html element names // this is an array list now, but we may want to make it a hashtable later for better performance private static ArrayList _htmlInlineElements; private static ArrayList _htmlBlockElements; private static ArrayList _htmlOtherOpenableElements; // list of html empty element names private static ArrayList _htmlEmptyElements; // names of html elements for which closing tags are optional, and close when the outer nested element closes private static ArrayList _htmlElementsClosingOnParentElementEnd; // names of elements that close certain optional closing tag elements when they start // names of elements closing the colgroup element private static ArrayList _htmlElementsClosingColgroup; // names of elements closing the dd element private static ArrayList _htmlElementsClosingDD; // names of elements closing the dt element private static ArrayList _htmlElementsClosingDT; // names of elements closing the li element private static ArrayList _htmlElementsClosingLI; // names of elements closing the tbody element private static ArrayList _htmlElementsClosingTbody; // names of elements closing the td element private static ArrayList _htmlElementsClosingTD; // names of elements closing the tfoot element private static ArrayList _htmlElementsClosingTfoot; // names of elements closing the thead element private static ArrayList _htmlElementsClosingThead; // names of elements closing the th element private static ArrayList _htmlElementsClosingTH; // names of elements closing the tr element private static ArrayList _htmlElementsClosingTR; // html character entities hashtable private static Hashtable _htmlCharacterEntities; #endregion Private Fields } }
// // 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 !NET_CF && !SILVERLIGHT namespace NLog.Targets { using System; using System.ComponentModel; using System.Diagnostics; using System.Globalization; using System.Security; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Writes log message to the Event Log. /// </summary> /// <seealso href="http://nlog-project.org/wiki/EventLog_target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/EventLog/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/EventLog/Simple/Example.cs" /> /// </example> [Target("EventLog")] public class EventLogTarget : TargetWithLayout, IInstallable { /// <summary> /// Initializes a new instance of the <see cref="EventLogTarget"/> class. /// </summary> public EventLogTarget() { this.Source = AppDomain.CurrentDomain.FriendlyName; this.Log = "Application"; this.MachineName = "."; } /// <summary> /// Gets or sets the name of the machine on which Event Log service is running. /// </summary> /// <docgen category='Event Log Options' order='10' /> [DefaultValue(".")] public string MachineName { get; set; } /// <summary> /// Gets or sets the layout that renders event ID. /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout EventId { get; set; } /// <summary> /// Gets or sets the layout that renders event Category. /// </summary> /// <docgen category='Event Log Options' order='10' /> public Layout Category { get; set; } /// <summary> /// Gets or sets the value to be used as the event Source. /// </summary> /// <remarks> /// By default this is the friendly name of the current AppDomain. /// </remarks> /// <docgen category='Event Log Options' order='10' /> public string Source { get; set; } /// <summary> /// Gets or sets the name of the Event Log to write to. This can be System, Application or /// any user-defined name. /// </summary> /// <docgen category='Event Log Options' order='10' /> [DefaultValue("Application")] public string Log { get; set; } /// <summary> /// Performs installation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Install(InstallationContext installationContext) { if (EventLog.SourceExists(this.Source, this.MachineName)) { string currentLogName = EventLog.LogNameFromSourceName(this.Source, this.MachineName); if (currentLogName != this.Log) { // re-create the association between Log and Source EventLog.DeleteEventSource(this.Source, this.MachineName); var escd = new EventSourceCreationData(this.Source, this.Log) { MachineName = this.MachineName }; EventLog.CreateEventSource(escd); } } else { var escd = new EventSourceCreationData(this.Source, this.Log) { MachineName = this.MachineName }; EventLog.CreateEventSource(escd); } } /// <summary> /// Performs uninstallation which requires administrative permissions. /// </summary> /// <param name="installationContext">The installation context.</param> public void Uninstall(InstallationContext installationContext) { EventLog.DeleteEventSource(this.Source, this.MachineName); } /// <summary> /// Determines whether the item is installed. /// </summary> /// <param name="installationContext">The installation context.</param> /// <returns> /// Value indicating whether the item is installed or null if it is not possible to determine. /// </returns> public bool? IsInstalled(InstallationContext installationContext) { return EventLog.SourceExists(this.Source, this.MachineName); } /// <summary> /// Initializes the target. /// </summary> protected override void InitializeTarget() { base.InitializeTarget(); var s = EventLog.LogNameFromSourceName(this.Source, this.MachineName); if (s != this.Log) { this.CreateEventSourceIfNeeded(); } } /// <summary> /// Writes the specified logging event to the event log. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(LogEventInfo logEvent) { string message = this.Layout.Render(logEvent); if (message.Length > 16384) { // limitation of EventLog API message = message.Substring(0, 16384); } EventLogEntryType entryType; if (logEvent.Level >= LogLevel.Error) { entryType = EventLogEntryType.Error; } else if (logEvent.Level >= LogLevel.Warn) { entryType = EventLogEntryType.Warning; } else { entryType = EventLogEntryType.Information; } int eventId = 0; if (this.EventId != null) { eventId = Convert.ToInt32(this.EventId.Render(logEvent), CultureInfo.InvariantCulture); } short category = 0; if (this.Category != null) { category = Convert.ToInt16(this.Category.Render(logEvent), CultureInfo.InvariantCulture); } EventLog.WriteEntry(this.Source, message, entryType, eventId, category); } private void CreateEventSourceIfNeeded() { // if we throw anywhere, we remain non-operational try { if (EventLog.SourceExists(this.Source, this.MachineName)) { string currentLogName = EventLog.LogNameFromSourceName(this.Source, this.MachineName); if (currentLogName != this.Log) { // re-create the association between Log and Source EventLog.DeleteEventSource(this.Source, this.MachineName); var escd = new EventSourceCreationData(this.Source, this.Log) { MachineName = this.MachineName }; EventLog.CreateEventSource(escd); } } else { var escd = new EventSourceCreationData(this.Source, this.Log) { MachineName = this.MachineName }; EventLog.CreateEventSource(escd); } } catch (Exception exception) { if (exception.MustBeRethrown()) { throw; } InternalLogger.Error("Error when connecting to EventLog: {0}", exception); throw; } } } } #endif
using System; using System.Collections.Concurrent; using System.Diagnostics; using System.Linq; using System.Threading; using System.Threading.Tasks; using Cuemon.Extensions.Runtime.Caching.Assets; using Cuemon.Extensions.Xunit.Hosting; using Cuemon.Runtime.Caching; using Microsoft.Extensions.DependencyInjection; using Xunit; using Xunit.Abstractions; namespace Cuemon.Extensions.Runtime.Caching { public class CacheEnumerableExtensionsTest : HostTest<HostFixture> { private readonly SlimMemoryCache _cache; private readonly SlimMemoryCacheOptions _cacheOptions = new SlimMemoryCacheOptions(); public CacheEnumerableExtensionsTest(HostFixture hostFixture, ITestOutputHelper output = null) : base(hostFixture, output) { _cache = hostFixture.ServiceProvider.GetRequiredService<SlimMemoryCache>(); } [Fact] public void GetOrAdd_ShouldCacheAndReturnItemInOneGoUsingSlidingExpirationOfTenSeconds() { var items = 1000; var expires = TimeSpan.FromSeconds(10); var keys = Generate.RangeOf(items, i => Guid.NewGuid().ToString("N")).ToList(); var bag = new ConcurrentBag<long>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.ForEach(keys, key => { bag.Add(_cacheOptions.KeyProvider(key, CacheEntry.NoScope)); var value = Generate.RandomString(5); Assert.Equal(value, _cache.GetOrAdd(key, expires, () => value)); }); Assert.Equal(items, _cache.Count()); Assert.True(bag.OrderBy(l => l).SequenceEqual(_cache.Where(pair => pair.Value.Namespace == CacheEntry.NoScope).Select(pair => pair.Key).OrderBy(l => l))); // insure thread safety validation Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count()); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateUsingSlidingExpirationOfTenSeconds() { var expires = TimeSpan.FromSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<string>(ExpensiveRandomString); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs()); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(17, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingOneParameterUsingSlidingExpirationOfTenSeconds() { var expires = TimeSpan.FromSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, string>(p1 => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1); }); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs(3)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(3, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingTwoParameterUsingSlidingExpirationOfTenSeconds() { var expires = TimeSpan.FromSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, int, string>((p1, p2) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2); }); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(2, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingThreeParameterUsingSlidingExpirationOfTenSeconds() { var expires = TimeSpan.FromSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, int, int, string>((p1, p2, p3) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2 + p3); }); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1, 3)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(5, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingFourParameterUsingSlidingExpirationOfTenSeconds() { var expires = TimeSpan.FromSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, int, int, int, string>((p1, p2, p3, p4) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2 + p3 + p4); }); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1, 3, 2)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(7, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingFiveParameterUsingSlidingExpirationOfTenSeconds() { var expires = TimeSpan.FromSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<byte, int, int, int, int, string>((p1, p2, p3, p4, p5) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2 + p3 + p4 + p5); }); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1, 3, 2, 4)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(11, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateUsingAbsoluteExpirationOfTenSeconds() { var expires = DateTime.UtcNow.AddSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<string>(ExpensiveRandomString); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs()); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(17, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingOneParameterUsingAbsoluteExpirationOfTenSeconds() { var expires = DateTime.UtcNow.AddSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, string>(p1 => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1); }); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs(3)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(3, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingTwoParameterUsingAbsoluteExpirationOfTenSeconds() { var expires = DateTime.UtcNow.AddSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, int, string>((p1, p2) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2); }); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(2, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingThreeParameterUsingAbsoluteExpirationOfTenSeconds() { var expires = DateTime.UtcNow.AddSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, int, int, string>((p1, p2, p3) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2 + p3); }); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1, 3)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(5, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingFourParameterUsingAbsoluteExpirationOfTenSeconds() { var expires = DateTime.UtcNow.AddSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, int, int, int, string>((p1, p2, p3, p4) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2 + p3 + p4); }); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1, 3, 2)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(7, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingFiveParameterUsingAbsoluteExpirationOfTenSeconds() { var expires = DateTime.UtcNow.AddSeconds(10); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<byte, int, int, int, int, string>((p1, p2, p3, p4, p5) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2 + p3 + p4 + p5); }); var rs = _cache.Memoize(expires, value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1, 3, 2, 4)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(11, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateUsingDependencyExpirationOfTenSeconds() { var expires = new Func<CountdownDependency>(() => new CountdownDependency(TimeSpan.FromSeconds(10))); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<string>(ExpensiveRandomString); var rs = _cache.Memoize(expires(), value); var sw = Stopwatch.StartNew(); values.Add(rs()); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(17, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingOneParameterUsingDependencyExpirationOfTenSeconds() { var expires = new Func<CountdownDependency>(() => new CountdownDependency(TimeSpan.FromSeconds(10))); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, string>(p1 => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1); }); var rs = _cache.Memoize(expires(), value); var sw = Stopwatch.StartNew(); values.Add(rs(3)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(3, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingTwoParameterUsingDependencyExpirationOfTenSeconds() { var expires = new Func<CountdownDependency>(() => new CountdownDependency(TimeSpan.FromSeconds(10))); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, int, string>((p1, p2) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2); }); var rs = _cache.Memoize(expires(), value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(2, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingThreeParameterUsingDependencyExpirationOfTenSeconds() { var expires = new Func<CountdownDependency>(() => new CountdownDependency(TimeSpan.FromSeconds(10))); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, int, int, string>((p1, p2, p3) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2 + p3); }); var rs = _cache.Memoize(expires(), value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1, 3)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(5, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingFourParameterUsingDependencyExpirationOfTenSeconds() { var expires = new Func<CountdownDependency>(() => new CountdownDependency(TimeSpan.FromSeconds(10))); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<int, int, int, int, string>((p1, p2, p3, p4) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2 + p3 + p4); }); var rs = _cache.Memoize(expires(), value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1, 3, 2)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(7, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } [Fact] public void Memoize_ShouldCacheAndReturnFunctionDelegateHavingFiveParameterUsingDependencyExpirationOfTenSeconds() { var expires = new Func<CountdownDependency>(() => new CountdownDependency(TimeSpan.FromSeconds(10))); var timeSpans = new ConcurrentBag<TimeSpan>(); var values = new ConcurrentBag<string>(); // we use Parallel because we want to assure thread safety of the extension method Parallel.For(0, 1000, i => { var value = new Func<byte, int, int, int, int, string>((p1, p2, p3, p4, p5) => { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(p1 + p2 + p3 + p4 + p5); }); var rs = _cache.Memoize(expires(), value); var sw = Stopwatch.StartNew(); values.Add(rs(1, 1, 3, 2, 4)); sw.Stop(); timeSpans.Add(sw.Elapsed); }); var s = Assert.Single(values.Distinct()); Assert.Equal(11, s.Length); Assert.True(Condition.IsPrime(s.Length)); var turtle = timeSpans.Where(ts => ts > TimeSpan.FromSeconds(1)).ToList(); var rabbit = timeSpans.Where(ts => ts < TimeSpan.FromSeconds(1)).ToList(); foreach (var writeLockHit in turtle) { Assert.InRange(writeLockHit, TimeSpan.FromSeconds(1), TimeSpan.FromSeconds(5)); } TestOutput.WriteLine($"Suspected hit-rate of PadLock: {turtle.Count}."); TestOutput.WriteLine($"The rest, {rabbit.Count}, had {rabbit.Count(ts => ts < TimeSpan.FromMilliseconds(25))} in expected range (<25ms)."); TestOutput.WriteLine(s); foreach (var nonLockHit in rabbit) { Assert.InRange(nonLockHit, TimeSpan.Zero, TimeSpan.FromSeconds(1)); } Assert.Equal(1, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); Thread.Sleep(TimeSpan.FromSeconds(11)); Assert.Equal(0, _cache.Count(CacheEnumerableExtensions.MemoizationScope)); } private string ExpensiveRandomString() { Thread.Sleep(TimeSpan.FromSeconds(1)); return Generate.RandomString(17); } public override void ConfigureServices(IServiceCollection services) { services.AddSingleton<SlimMemoryCache>(); } } }
using System; using System.Data; using Csla; using Csla.Data; using SelfLoadRO.DataAccess; using SelfLoadRO.DataAccess.ERLevel; namespace SelfLoadRO.Business.ERLevel { /// <summary> /// C02_Continent (read only object).<br/> /// This is a generated base class of <see cref="C02_Continent"/> business object. /// This class is a root object. /// </summary> /// <remarks> /// This class contains one child collection:<br/> /// - <see cref="C03_SubContinentObjects"/> of type <see cref="C03_SubContinentColl"/> (1:M relation to <see cref="C04_SubContinent"/>) /// </remarks> [Serializable] public partial class C02_Continent : ReadOnlyBase<C02_Continent> { #region Business Properties /// <summary> /// Maintains metadata about <see cref="Continent_ID"/> property. /// </summary> public static readonly PropertyInfo<int> Continent_IDProperty = RegisterProperty<int>(p => p.Continent_ID, "Continents ID", -1); /// <summary> /// Gets the Continents ID. /// </summary> /// <value>The Continents ID.</value> public int Continent_ID { get { return GetProperty(Continent_IDProperty); } } /// <summary> /// Maintains metadata about <see cref="Continent_Name"/> property. /// </summary> public static readonly PropertyInfo<string> Continent_NameProperty = RegisterProperty<string>(p => p.Continent_Name, "Continents Name"); /// <summary> /// Gets the Continents Name. /// </summary> /// <value>The Continents Name.</value> public string Continent_Name { get { return GetProperty(Continent_NameProperty); } } /// <summary> /// Maintains metadata about child <see cref="C03_Continent_SingleObject"/> property. /// </summary> public static readonly PropertyInfo<C03_Continent_Child> C03_Continent_SingleObjectProperty = RegisterProperty<C03_Continent_Child>(p => p.C03_Continent_SingleObject, "C03 Continent Single Object"); /// <summary> /// Gets the C03 Continent Single Object ("self load" child property). /// </summary> /// <value>The C03 Continent Single Object.</value> public C03_Continent_Child C03_Continent_SingleObject { get { return GetProperty(C03_Continent_SingleObjectProperty); } private set { LoadProperty(C03_Continent_SingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C03_Continent_ASingleObject"/> property. /// </summary> public static readonly PropertyInfo<C03_Continent_ReChild> C03_Continent_ASingleObjectProperty = RegisterProperty<C03_Continent_ReChild>(p => p.C03_Continent_ASingleObject, "C03 Continent ASingle Object"); /// <summary> /// Gets the C03 Continent ASingle Object ("self load" child property). /// </summary> /// <value>The C03 Continent ASingle Object.</value> public C03_Continent_ReChild C03_Continent_ASingleObject { get { return GetProperty(C03_Continent_ASingleObjectProperty); } private set { LoadProperty(C03_Continent_ASingleObjectProperty, value); } } /// <summary> /// Maintains metadata about child <see cref="C03_SubContinentObjects"/> property. /// </summary> public static readonly PropertyInfo<C03_SubContinentColl> C03_SubContinentObjectsProperty = RegisterProperty<C03_SubContinentColl>(p => p.C03_SubContinentObjects, "C03 SubContinent Objects"); /// <summary> /// Gets the C03 Sub Continent Objects ("self load" child property). /// </summary> /// <value>The C03 Sub Continent Objects.</value> public C03_SubContinentColl C03_SubContinentObjects { get { return GetProperty(C03_SubContinentObjectsProperty); } private set { LoadProperty(C03_SubContinentObjectsProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="C02_Continent"/> object, based on given parameters. /// </summary> /// <param name="continent_ID">The Continent_ID parameter of the C02_Continent to fetch.</param> /// <returns>A reference to the fetched <see cref="C02_Continent"/> object.</returns> public static C02_Continent GetC02_Continent(int continent_ID) { return DataPortal.Fetch<C02_Continent>(continent_ID); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="C02_Continent"/> class. /// </summary> /// <remarks> Do not use to create a Csla object. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public C02_Continent() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="C02_Continent"/> object from the database, based on given criteria. /// </summary> /// <param name="continent_ID">The Continent ID.</param> protected void DataPortal_Fetch(int continent_ID) { var args = new DataPortalHookArgs(continent_ID); OnFetchPre(args); using (var dalManager = DalFactorySelfLoadRO.GetManager()) { var dal = dalManager.GetProvider<IC02_ContinentDal>(); var data = dal.Fetch(continent_ID); Fetch(data); } OnFetchPost(args); FetchChildren(); // check all object rules and property rules BusinessRules.CheckRules(); } private void Fetch(IDataReader data) { using (var dr = new SafeDataReader(data)) { if (dr.Read()) { Fetch(dr); } } } /// <summary> /// Loads a <see cref="C02_Continent"/> object from the given SafeDataReader. /// </summary> /// <param name="dr">The SafeDataReader to use.</param> private void Fetch(SafeDataReader dr) { // Value properties LoadProperty(Continent_IDProperty, dr.GetInt32("Continent_ID")); LoadProperty(Continent_NameProperty, dr.GetString("Continent_Name")); var args = new DataPortalHookArgs(dr); OnFetchRead(args); } /// <summary> /// Loads child objects. /// </summary> private void FetchChildren() { LoadProperty(C03_Continent_SingleObjectProperty, C03_Continent_Child.GetC03_Continent_Child(Continent_ID)); LoadProperty(C03_Continent_ASingleObjectProperty, C03_Continent_ReChild.GetC03_Continent_ReChild(Continent_ID)); LoadProperty(C03_SubContinentObjectsProperty, C03_SubContinentColl.GetC03_SubContinentColl(Continent_ID)); } #endregion #region DataPortal Hooks /// <summary> /// Occurs after setting query parameters and before the fetch operation. /// </summary> partial void OnFetchPre(DataPortalHookArgs args); /// <summary> /// Occurs after the fetch operation (object or collection is fully loaded and set up). /// </summary> partial void OnFetchPost(DataPortalHookArgs args); /// <summary> /// Occurs after the low level fetch operation, before the data reader is destroyed. /// </summary> partial void OnFetchRead(DataPortalHookArgs args); #endregion } }
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using SIL.IO; namespace SIL.Reporting { public interface ILogger { /// <summary> /// This is something that should be listed in the source control checkin /// </summary> void WriteConciseHistoricalEvent(string message, params object[] args); } public class MultiLogger: ILogger { private readonly List<ILogger> _loggers= new List<ILogger>(); // this just lead to problems. Better to say "this doesn't own anything", and let the DI container handle the lifetimes // public void Dispose() // { // foreach (ILogger logger in _loggers) // { // // IDisposable d = logger as IDisposable; // if(d!=null) // d.Dispose(); // } // _loggers.Clear(); // } /// <summary> /// NB: you must handle disposal of the logger yourself (easy with a DI container) /// </summary> /// <param name="logger"></param> public void Add(ILogger logger) { _loggers.Add(logger); } public void WriteConciseHistoricalEvent(string message, params object[] args) { foreach (ILogger logger in _loggers) { logger.WriteConciseHistoricalEvent(message,args); } } } public class StringLogger : ILogger { StringBuilder _builder = new StringBuilder(); public void WriteConciseHistoricalEvent(string message, params object[] args) { _builder.Append(Logger.FormatMessage(message, args)); } public string GetLogText() { return _builder.ToString(); } } /// ---------------------------------------------------------------------------------------- /// <summary> /// Logs stuff to a file created in /// c:\Documents and Settings\Username\Local Settings\Temp\Companyname\Productname\Log.txt /// </summary> /// ---------------------------------------------------------------------------------------- public class Logger: IDisposable, ILogger { private static Logger _singleton; private static string _actualLogPath; private static string _logfilePrefix; protected StreamWriter m_out; private StringBuilder m_minorEvents; /// ------------------------------------------------------------------------------------ /// <summary> /// Creates the logger. The logging functions can't be used until this method is /// called. /// </summary> /// ------------------------------------------------------------------------------------ public static void Init() { if(Singleton == null) Init(null); } /// <summary> /// Creates the logger. The logging functions can't be used until this method is called. /// Initializes the logger by creating a new log file, prepending the specified /// <paramref name="logfilePrefix"/>. If Init has been called before, the previous /// Logger gets shutdown first. /// </summary> /// <remarks> /// This method is useful when an application wants to write different logging files /// while it is running. For example, FieldWorks writes to a different log file after /// loading the project. This is also necessary when an application can run multiple /// instances simultaneously. /// </remarks> public static void Init(string logfilePrefix) { Init(logfilePrefix, true); } /// <summary> /// Creates the logger. The logging functions can't be used until this method is called. /// Initializes the logger by creating a new log file, prepending the specified /// <paramref name="logfilePrefix"/>. If Init has been called before, the previous /// Logger gets shutdown first. /// </summary> public static void Init(string logfilePrefix, bool startWithNewFile) { ShutDown(); if (Singleton == null) _singleton = new Logger(logfilePrefix, startWithNewFile); } /// ------------------------------------------------------------------------------------ /// <summary> /// Shut down the logger. The logging functions can't be used after this method is /// called. /// </summary> /// ------------------------------------------------------------------------------------ public static void ShutDown() { if (Singleton != null) { Singleton.Dispose(); _singleton = null; } } public Logger(): this(null, true) { } private Logger(string logfilePrefix, bool startWithNewFile) { if(_singleton != null) { throw new ApplicationException("Sadly, only one instance of Logger is currently allowed, per instance of the application."); } try { _logfilePrefix = logfilePrefix; if (!string.IsNullOrEmpty(logfilePrefix)) _logfilePrefix += "_"; m_out = null; if (startWithNewFile || !File.Exists(LogPath)) { try { m_out = File.CreateText(LogPath); } catch (Exception) { //try again with a different file. We loose the history, but oh well. SetActualLogPath(_logfilePrefix + "Log-"+Path.GetFileNameWithoutExtension(Path.GetTempFileName()) + ".txt"); m_out = File.CreateText(LogPath); } m_out.WriteLine(DateTime.Now.ToLongDateString()); } else StartAppendingToLog(); RestartMinorEvents(); _singleton = this; this.WriteEventCore("App Launched with [" + System.Environment.CommandLine + "]"); } catch { // If the output file can not be created then just disable logging. _singleton = null; } } private void StartAppendingToLog() { m_out = File.AppendText(LogPath); } private void RestartMinorEvents() { m_minorEvents = new StringBuilder(); } #region IDisposable & Co. implementation // Region last reviewed: never /// <summary> /// Check to see if the object has been disposed. /// All public Properties and Methods should call this /// before doing anything else. /// </summary> public void CheckDisposed() { if (IsDisposed) throw new ObjectDisposedException(String.Format("'{0}' in use after being disposed.", GetType().Name)); } /// <summary> /// True, if the object has been disposed. /// </summary> private bool m_isDisposed = false; /// <summary> /// See if the object has been disposed. /// </summary> public bool IsDisposed { get { return m_isDisposed; } } /// <summary> /// Finalizer, in case client doesn't dispose it. /// Force Dispose(false) if not already called (i.e. m_isDisposed is true) /// </summary> /// <remarks> /// In case some clients forget to dispose it directly. /// </remarks> ~Logger() { Dispose(false); // The base class finalizer is called automatically. } /// <summary> /// /// </summary> /// <remarks>Must not be virtual.</remarks> public void Dispose() { Dispose(true); // This object will be cleaned up by the Dispose method. // Therefore, you should call GC.SupressFinalize to // take this object off the finalization queue // and prevent finalization code for this object // from executing a second time. GC.SuppressFinalize(this); } /// <summary> /// Executes in two distinct scenarios. /// /// 1. If disposing is true, the method has been called directly /// or indirectly by a user's code via the Dispose method. /// Both managed and unmanaged resources can be disposed. /// /// 2. If disposing is false, the method has been called by the /// runtime from inside the finalizer and you should not reference (access) /// other managed objects, as they already have been garbage collected. /// Only unmanaged resources can be disposed. /// </summary> /// <param name="disposing"></param> /// <remarks> /// If any exceptions are thrown, that is fine. /// If the method is being done in a finalizer, it will be ignored. /// If it is thrown by client code calling Dispose, /// it needs to be handled by fixing the bug. /// /// If subclasses override this method, they should call the base implementation. /// </remarks> protected virtual void Dispose(bool disposing) { //Debug.WriteLineIf(!disposing, "****************** " + GetType().Name + " 'disposing' is false. ******************"); // Must not be run more than once. if (m_isDisposed) return; if (disposing) { // Dispose managed resources here. if (m_out != null) m_out.Close(); } // Dispose unmanaged resources here, whether disposing is true or false. _actualLogPath = null; m_out = null; m_isDisposed = true; } #endregion IDisposable & Co. implementation /// <summary> /// This is for version-control checkin descriptions. E.g. "Deleted foobar". /// </summary> /// <param name="message"></param> /// <param name="args"></param> public void WriteConciseHistoricalEvent(string message, params object[] args) { WriteEventCore(message, args); } /// ------------------------------------------------------------------------------------ /// <summary> /// Gets the entire text of the log file /// </summary> /// <returns></returns> /// ------------------------------------------------------------------------------------ public static string LogText { get { if (Singleton == null) return "No log available."; string logText = Singleton.GetLogTextAndStartOver(); return logText; } } //enhance: why start over? private string GetLogTextAndStartOver() { lock (_singleton) { CheckDisposed(); m_out.Flush(); m_out.Close(); //get the old StringBuilder contents = new StringBuilder(); if (!File.Exists(LogPath)) { File.Create(LogPath); } using (StreamReader reader = File.OpenText(LogPath)) { contents.Append(reader.ReadToEnd()); contents.AppendLine("Details of most recent events:"); contents.AppendLine(m_minorEvents.ToString()); } StartAppendingToLog(); return contents.ToString(); } } /// <summary> /// added this for a case of a catastrophic error so bad I couldn't get the means of finding out what just happened /// </summary> public static string MinorEventsLog { get { return Singleton.m_minorEvents.ToString(); } } /// <summary> /// the place on disk where we are storing the log /// </summary> public static string LogPath { get { if (string.IsNullOrEmpty(_actualLogPath)) { SetActualLogPath(_logfilePrefix + "Log.txt"); } return _actualLogPath; } } public static Logger Singleton { get { return _singleton; } } private static void SetActualLogPath(string filename) { _actualLogPath = Path.Combine(Path.GetTempPath(), Path.Combine(EntryAssembly.CompanyName, UsageReporter.AppNameToUseInReporting)); Directory.CreateDirectory(_actualLogPath); _actualLogPath = Path.Combine(_actualLogPath, filename); } /// ------------------------------------------------------------------------------------ /// <summary> /// Writes an event to the logger. This method will do nothing if Init() is not called /// first. /// </summary> /// ------------------------------------------------------------------------------------ public static void WriteEvent(string message, params object[] args) { if (Singleton != null) Singleton.WriteEventCore(message,args); } private void WriteEventCore(string message, params object[] args) { lock (_singleton) { #if !DEBUG try { #endif CheckDisposed(); if (m_out != null && m_out.BaseStream.CanWrite) { m_out.Write(DateTime.Now.ToLongTimeString() + "\t"); m_out.WriteLine(FormatMessage(message, args)); m_out.Flush();//in case we crash //want this to show up in the proper order in the minor event list, too WriteMinorEvent(message, args); //Debug.WriteLine("-----"+"\r\n"+m_minorEvents.ToString()); } #if !DEBUG } catch (Exception) { //swallow } #endif } } /// <summary> /// Writes an exception and its stack trace to the log. This method will do nothing if /// Init() is not called first. /// </summary> public static void WriteError(Exception e) { WriteError(null, e); } /// <summary> /// Writes <paramref name="msg"/> and an exception and its stack trace to the log. /// This method will do nothing if Init() is not called first. /// </summary> public static void WriteError(string msg, Exception e) { Exception dummy = null; var bldr = new StringBuilder(msg); if (bldr.Length > 0) bldr.AppendLine(); bldr.Append(ExceptionHelper.GetHiearchicalExceptionInfo(e, ref dummy)); Debug.WriteLine(bldr.ToString()); if (Singleton != null) Singleton.WriteEventCore(bldr.ToString()); } /// <summary> /// only a limitted number of the most recent of these events will show up in the log /// </summary> public static void WriteMinorEvent(string message, params object[] args) { if (Singleton != null) Singleton.WriteMinorEventCore(message,args); } /// <summary> /// Conceptually, returns string.Format(message, args). /// However, if there are no args, it just returns message, so unlike string.Format and friends, /// it won't choke if message contains curly braces as long as there are no args. /// Also, if the attempt to format the args fails, it will replace the usual output with /// a message describing the failure to produce the output (and embedding message). /// </summary> /// <param name="message"></param> /// <param name="args"></param> /// <returns></returns> internal static string FormatMessage(string message, object[] args) { if (args.Any()) { try { return string.Format(message, args); } catch (Exception) { return string.Format("Error formatting message with {0} args: {1}", args.Length, message); } } return message; } private void WriteMinorEventCore(string message, params object[] args) { CheckDisposed(); lock (_singleton) { if (m_minorEvents != null) { #if !DEBUG try { #endif if (m_minorEvents.Length > 5000) { int roughlyHowMuchToCut = 500; int cutoff = m_minorEvents.ToString().IndexOf(System.Environment.NewLine, roughlyHowMuchToCut); m_minorEvents.Remove(0, cutoff); } m_minorEvents.Append(DateTime.Now.ToLongTimeString() + "\t"); m_minorEvents.Append(FormatMessage(message, args)); m_minorEvents.AppendLine(); #if !DEBUG } catch(Exception) { //swallow } #endif } } } public static void ShowUserTheLogFile() { Singleton.m_out.Flush(); Process.Start(LogPath); } /// <summary> /// if you're working with unmanaged code and get a System.AccessViolationException, well you're toast, and anything /// that requires UI is gonna freeze up. So call this instead /// </summary> public static void ShowUserATextFileRelatedToCatastrophicError(Exception reallyBadException) { //did this special because we don't have an event loop to drive the error reporting dialog if Application.Run() dies Debug.WriteLine(Logger.LogText); string tempFileName = TempFile.WithExtension(".txt").Path; using(var writer = File.CreateText(tempFileName)) { writer.WriteLine("Please report to "+ErrorReport.EmailAddress); writer.WriteLine("No really. Please. This kind of error is super hard to track down."); writer.WriteLine(); writer.WriteLine(reallyBadException.Message); writer.WriteLine(reallyBadException.StackTrace); writer.WriteLine(); writer.WriteLine(LogText); writer.WriteLine(); writer.WriteLine("Details of recent events:"); writer.WriteLine(MinorEventsLog); writer.Flush(); writer.Close(); } Process.Start(tempFileName); } } }
// 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 OLEDB.Test.ModuleCore; namespace System.Xml.Tests { ///////////////////////////////////////////////////////////////////////// // TestCase ReadOuterXml // ///////////////////////////////////////////////////////////////////////// [InheritRequired()] public abstract partial class TCReadOuterXml : TCXMLReaderBaseGeneral { // Element names to test ReadOuterXml on private static string s_EMP1 = "EMPTY1"; private static string s_EMP2 = "EMPTY2"; private static string s_EMP3 = "EMPTY3"; private static string s_EMP4 = "EMPTY4"; private static string s_ENT1 = "ENTITY1"; private static string s_NEMP0 = "NONEMPTY0"; private static string s_NEMP1 = "NONEMPTY1"; private static string s_NEMP2 = "NONEMPTY2"; private static string s_ELEM1 = "CHARS2"; private static string s_ELEM2 = "SKIP3"; private static string s_ELEM3 = "CONTENT"; private static string s_ELEM4 = "COMPLEX"; // Element names after the ReadOuterXml call private static string s_NEXT1 = "COMPLEX"; private static string s_NEXT2 = "ACT2"; private static string s_NEXT3 = "CHARS_ELEM1"; private static string s_NEXT4 = "AFTERSKIP3"; private static string s_NEXT5 = "TITLE"; private static string s_NEXT6 = "ENTITY2"; private static string s_NEXT7 = "DUMMY"; // Expected strings returned by ReadOuterXml private static string s_EXP_EMP1 = "<EMPTY1 />"; private static string s_EXP_EMP2 = "<EMPTY2 val=\"abc\" />"; private static string s_EXP_EMP3 = "<EMPTY3></EMPTY3>"; private static string s_EXP_EMP4 = "<EMPTY4 val=\"abc\"></EMPTY4>"; private static string s_EXP_NEMP1 = "<NONEMPTY1>ABCDE</NONEMPTY1>"; private static string s_EXP_NEMP2 = "<NONEMPTY2 val=\"abc\">1234</NONEMPTY2>"; private static string s_EXP_ELEM1 = "<CHARS2>xxx<MARKUP />yyy</CHARS2>"; private static string s_EXP_ELEM2 = "<SKIP3><ELEM1 /><ELEM2>xxx yyy</ELEM2><ELEM3 /></SKIP3>"; private static string s_EXP_ELEM3 = "<CONTENT><e1 a1='a1value' a2='a2value'><e2 a1='a1value' a2='a2value'><e3 a1='a1value' a2='a2value'>leave</e3></e2></e1></CONTENT>"; private static string s_EXP_ELEM4 = "<COMPLEX>Text<!-- comment --><![CDATA[cdata]]></COMPLEX>"; private static string s_EXP_ELEM4_XSLT = "<COMPLEX>Text<!-- comment -->cdata</COMPLEX>"; private static string s_EXP_ENT1_EXPAND_ALL = "<ENTITY1 att1=\"xxx&lt;xxxAxxxCxxxNO_REFERENCEe1;xxx\">xxx&gt;xxxBxxxDxxxNO_REFERENCEe1;xxx</ENTITY1>"; private static string s_EXP_ENT1_EXPAND_CHAR = "<ENTITY1 att1=\"xxx&lt;xxxAxxxCxxx&e1;xxx\">xxx&gt;xxxBxxxDxxx&e1;xxx</ENTITY1>"; private int TestOuterOnElement(string strElem, string strOuterXml, string strNextElemName, bool bWhitespace) { ReloadSource(); DataReader.PositionOnElement(strElem); CError.Compare(DataReader.ReadOuterXml(), strOuterXml, "outer"); if (bWhitespace) { if (!(IsXsltReader() || IsXPathNavigatorReader()))// xslt doesn't return whitespace { if (IsCoreReader()) { CError.Compare(DataReader.VerifyNode(XmlNodeType.Whitespace, String.Empty, "\n"), true, "vn"); } else { CError.Compare(DataReader.VerifyNode(XmlNodeType.Whitespace, String.Empty, "\r\n"), true, "vn"); } DataReader.Read(); } } CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, strNextElemName, String.Empty), true, "vn2"); return TEST_PASS; } private int TestOuterOnAttribute(string strElem, string strName, string strValue) { ReloadSource(); DataReader.PositionOnElement(strElem); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); string strExpected = String.Format("{0}=\"{1}\"", strName, strValue); CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, strName, strValue), true, "vn"); return TEST_PASS; } private int TestOuterOnNodeType(XmlNodeType nt) { ReloadSource(); PositionOnNodeType(nt); DataReader.Read(); XmlNodeType expNt = DataReader.NodeType; string expName = DataReader.Name; string expValue = DataReader.Value; ReloadSource(); PositionOnNodeType(nt); CError.Compare(DataReader.ReadOuterXml(), String.Empty, "outer"); CError.Compare(DataReader.VerifyNode(expNt, expName, expValue), true, "vn"); return TEST_PASS; } //////////////////////////////////////////////////////////////// // Variations //////////////////////////////////////////////////////////////// [Variation("ReadOuterXml on empty element w/o attributes", Pri = 0)] public int ReadOuterXml1() { if (IsBinaryReader()) { return TEST_SKIPPED; } return TestOuterOnElement(s_EMP1, s_EXP_EMP1, s_EMP2, true); } [Variation("ReadOuterXml on empty element w/ attributes", Pri = 0)] public int ReadOuterXml2() { if (IsBinaryReader()) { return TEST_SKIPPED; } return TestOuterOnElement(s_EMP2, s_EXP_EMP2, s_EMP3, true); } [Variation("ReadOuterXml on full empty element w/o attributes")] public int ReadOuterXml3() { return TestOuterOnElement(s_EMP3, s_EXP_EMP3, s_NEMP0, true); } [Variation("ReadOuterXml on full empty element w/ attributes")] public int ReadOuterXml4() { return TestOuterOnElement(s_EMP4, s_EXP_EMP4, s_NEXT1, true); } [Variation("ReadOuterXml on element with text content", Pri = 0)] public int ReadOuterXml5() { return TestOuterOnElement(s_NEMP1, s_EXP_NEMP1, s_NEMP2, true); } [Variation("ReadOuterXml on element with attributes", Pri = 0)] public int ReadOuterXml6() { return TestOuterOnElement(s_NEMP2, s_EXP_NEMP2, s_NEXT2, true); } [Variation("ReadOuterXml on element with text and markup content")] public int ReadOuterXml7() { if (IsBinaryReader()) { return TEST_SKIPPED; } return TestOuterOnElement(s_ELEM1, s_EXP_ELEM1, s_NEXT3, true); } [Variation("ReadOuterXml with multiple level of elements")] public int ReadOuterXml8() { if (IsBinaryReader()) { return TEST_SKIPPED; } return TestOuterOnElement(s_ELEM2, s_EXP_ELEM2, s_NEXT4, false); } [Variation("ReadOuterXml with multiple level of elements, text and attributes", Pri = 0)] public int ReadOuterXml9() { string strExpected = s_EXP_ELEM3; strExpected = strExpected.Replace('\'', '"'); return TestOuterOnElement(s_ELEM3, strExpected, s_NEXT5, true); } [Variation("ReadOuterXml on element with complex content (CDATA, PIs, Comments)", Pri = 0)] public int ReadOuterXml10() { if (IsXsltReader() || IsXPathNavigatorReader()) return TestOuterOnElement(s_ELEM4, s_EXP_ELEM4_XSLT, s_NEXT7, true); else return TestOuterOnElement(s_ELEM4, s_EXP_ELEM4, s_NEXT7, true); } [Variation("ReadOuterXml on element with entities, EntityHandling = ExpandEntities")] public int ReadOuterXml11() { string strExpected; if (IsXsltReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader()) { strExpected = s_EXP_ENT1_EXPAND_ALL; } else { strExpected = s_EXP_ENT1_EXPAND_CHAR; } return TestOuterOnElement(s_ENT1, strExpected, s_NEXT6, false); } [Variation("ReadOuterXml on attribute node of empty element")] public int ReadOuterXml12() { return TestOuterOnAttribute(s_EMP2, "val", "abc"); } [Variation("ReadOuterXml on attribute node of full empty element")] public int ReadOuterXml13() { return TestOuterOnAttribute(s_EMP4, "val", "abc"); } [Variation("ReadOuterXml on attribute node", Pri = 0)] public int ReadOuterXml14() { return TestOuterOnAttribute(s_NEMP2, "val", "abc"); } [Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandEntities", Pri = 0)] public int ReadOuterXml15() { ReloadSource(); DataReader.PositionOnElement(s_ENT1); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); string strExpected; if (IsXsltReader() || IsXmlNodeReader() || IsXmlNodeReaderDataDoc() || IsXmlValidatingReader() || IsCoreReader() || IsXPathNavigatorReader()) strExpected = "att1=\"xxx&lt;xxxAxxxCxxxNO_REFERENCEe1;xxx\""; else { strExpected = "att1=\"xxx&lt;xxxAxxxCxxx&e1;xxx\""; } CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer"); if (IsXmlTextReader()) CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_CHAR_ENTITIES), true, "vn"); else CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn"); return TEST_PASS; } [Variation("ReadOuterXml on Comment")] public int ReadOuterXml16() { return TestOuterOnNodeType(XmlNodeType.Comment); } [Variation("ReadOuterXml on ProcessingInstruction")] public int ReadOuterXml17() { return TestOuterOnNodeType(XmlNodeType.ProcessingInstruction); } [Variation("ReadOuterXml on DocumentType")] public int ReadOuterXml18() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; return TestOuterOnNodeType(XmlNodeType.DocumentType); } [Variation("ReadOuterXml on XmlDeclaration")] public int ReadOuterXml19() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; return TestOuterOnNodeType(XmlNodeType.XmlDeclaration); } [Variation("ReadOuterXml on EndElement")] public int ReadOuterXml20() { return TestOuterOnNodeType(XmlNodeType.EndElement); } [Variation("ReadOuterXml on Text")] public int ReadOuterXml21() { return TestOuterOnNodeType(XmlNodeType.Text); } [Variation("ReadOuterXml on EntityReference")] public int ReadOuterXml22() { if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; return TestOuterOnNodeType(XmlNodeType.EntityReference); } [Variation("ReadOuterXml on EndEntity")] public int ReadOuterXml23() { if (IsXmlTextReader() || IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; return TestOuterOnNodeType(XmlNodeType.EndEntity); } [Variation("ReadOuterXml on CDATA")] public int ReadOuterXml24() { if (IsXsltReader() || IsXPathNavigatorReader()) return TEST_SKIPPED; return TestOuterOnNodeType(XmlNodeType.CDATA); } [Variation("ReadOuterXml on XmlDeclaration attributes")] public int ReadOuterXml25() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; ReloadSource(); DataReader.PositionOnNodeType(XmlNodeType.XmlDeclaration); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); CError.Compare(DataReader.ReadOuterXml().ToLower(), "encoding=\"utf-8\"", "outer"); if (IsBinaryReader()) CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "utf-8"), true, "vn"); else CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "encoding", "UTF-8"), true, "vn"); return TEST_PASS; } [Variation("ReadOuterXml on DocumentType attributes")] public int ReadOuterXml26() { if (IsXsltReader() || IsXPathNavigatorReader() || IsSubtreeReader()) return TEST_SKIPPED; ReloadSource(); DataReader.PositionOnNodeType(XmlNodeType.DocumentType); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); CError.Compare(DataReader.ReadOuterXml(), "SYSTEM=\"AllNodeTypes.dtd\"", "outer"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "SYSTEM", "AllNodeTypes.dtd"), true, "vn"); return TEST_PASS; } [Variation("ReadOuterXml on element with entities, EntityHandling = ExpandCharEntities")] public int TRReadOuterXml27() { string strExpected; if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) strExpected = s_EXP_ENT1_EXPAND_ALL; else { if (IsXmlNodeReader()) { strExpected = s_EXP_ENT1_EXPAND_CHAR; } else { strExpected = s_EXP_ENT1_EXPAND_CHAR; } } ReloadSource(); DataReader.PositionOnElement(s_ENT1); CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer"); CError.Compare(DataReader.VerifyNode(XmlNodeType.Element, s_NEXT6, String.Empty), true, "vn"); return TEST_PASS; } [Variation("ReadOuterXml on attribute with entities, EntityHandling = ExpandCharEntites")] public int TRReadOuterXml28() { string strExpected; if (IsXsltReader() || IsXmlNodeReaderDataDoc() || IsCoreReader() || IsXPathNavigatorReader()) strExpected = "att1=\"xxx&lt;xxxAxxxCxxxNO_REFERENCEe1;xxx\""; else { if (IsXmlNodeReader()) { strExpected = "att1=\"xxx&lt;xxxAxxxCxxxNO_REFERENCEe1;xxx\""; } else { strExpected = "att1=\"xxx&lt;xxxAxxxCxxxNO_REFERENCEe1;xxx\""; } } ReloadSource(); DataReader.PositionOnElement(s_ENT1); DataReader.MoveToAttribute(DataReader.AttributeCount / 2); CError.Compare(DataReader.ReadOuterXml(), strExpected, "outer"); if (IsXmlTextReader()) CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_CHAR_ENTITIES), true, "vn"); else CError.Compare(DataReader.VerifyNode(XmlNodeType.Attribute, "att1", ST_ENT1_ATT_EXPAND_ENTITIES), true, "vn"); return TEST_PASS; } [Variation("One large element")] public int TestTextReadOuterXml29() { String strp = "a "; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; strp += strp; string strxml = "<Name a=\"b\">" + strp + " </Name>"; ReloadSourceStr(strxml); DataReader.Read(); CError.Compare(DataReader.ReadOuterXml(), strxml, "rox"); return TEST_PASS; } [Variation("Read OuterXml when Namespaces=false and has an attribute xmlns")] public int ReadOuterXmlWhenNamespacesIgnoredWorksWithXmlns() { ReloadSourceStr("<?xml version='1.0' encoding='utf-8' ?> <foo xmlns='testing'><bar id='1'/></foo>"); if (IsXmlTextReader() || IsXmlValidatingReader()) DataReader.Namespaces = false; DataReader.MoveToContent(); CError.WriteLine(DataReader.ReadOuterXml()); return TEST_PASS; } [Variation("XmlReader.ReadOuterXml outputs multiple namespace declarations if called within multiple XmlReader.ReadSubtree() calls")] public int SubtreeXmlReaderOutputsSingleNamespaceDeclaration() { string xml = @"<root xmlns = ""http://www.test.com/""> <device> <thing>1</thing> </device></root>"; ReloadSourceStr(xml); DataReader.ReadToFollowing("device"); Foo(DataReader.ReadSubtree()); return TEST_PASS; } private void Foo(XmlReader reader) { reader.Read(); Bar(reader.ReadSubtree()); } private void Bar(XmlReader reader) { reader.Read(); string foo = reader.ReadOuterXml(); CError.Compare(foo, "<device xmlns=\"http://www.test.com/\"> <thing>1</thing> </device>", "<device xmlns=\"http://www.test.com/\"><thing>1</thing></device>", "mismatch"); } } }
// Copyright 2008 Adrian Akison // Distributed under license terms of CPOL http://www.codeproject.com/info/cpol10.aspx using System.Collections.Generic; namespace Facet.Combinatorics { /// <summary> /// Combinations defines a meta-collection, typically a list of lists, of all possible /// subsets of a particular size from the set of values. This list is enumerable and /// allows the scanning of all possible combinations using a simple foreach() loop. /// Within the returned set, there is no prescribed order. This follows the mathematical /// concept of choose. For example, put 10 dominoes in a hat and pick 5. The number of possible /// combinations is defined as "10 choose 5", which is calculated as (10!) / ((10 - 5)! * 5!). /// </summary> /// <remarks> /// The MetaCollectionType parameter of the constructor allows for the creation of /// two types of sets, those with and without repetition in the output set when /// presented with repetition in the input set. /// /// When given a input collect {A B C} and lower index of 2, the following sets are generated: /// MetaCollectionType.WithRepetition => /// {A A}, {A B}, {A C}, {B B}, {B C}, {C C} /// MetaCollectionType.WithoutRepetition => /// {A B}, {A C}, {B C} /// /// Input sets with multiple equal values will generate redundant combinations in proprotion /// to the likelyhood of outcome. For example, {A A B B} and a lower index of 3 will generate: /// {A A B} {A A B} {A B B} {A B B} /// </remarks> /// <typeparam name="T">The type of the values within the list.</typeparam> public class Combinations<T> : IMetaCollection<T> { #region Constructors /// <summary> /// No default constructor, must provided a list of values and size. /// </summary> protected Combinations() { ; } /// <summary> /// Create a combination set from the provided list of values. /// The upper index is calculated as values.Count, the lower index is specified. /// Collection type defaults to MetaCollectionType.WithoutRepetition /// </summary> /// <param name="values">List of values to select combinations from.</param> /// <param name="lowerIndex">The size of each combination set to return.</param> public Combinations(IList<T> values, int lowerIndex) { Initialize(values, lowerIndex, GenerateOption.WithoutRepetition); } /// <summary> /// Create a combination set from the provided list of values. /// The upper index is calculated as values.Count, the lower index is specified. /// </summary> /// <param name="values">List of values to select combinations from.</param> /// <param name="lowerIndex">The size of each combination set to return.</param> /// <param name="type">The type of Combinations set to generate.</param> public Combinations(IList<T> values, int lowerIndex, GenerateOption type) { Initialize(values, lowerIndex, type); } #endregion #region IEnumerable Interface /// <summary> /// Gets an enumerator for collecting the list of combinations. /// </summary> /// <returns>The enumerator.</returns> public IEnumerator<IList<T>> GetEnumerator() { return new Enumerator(this); } /// <summary> /// Gets an enumerator for collecting the list of combinations. /// </summary> /// <returns>The enumerator.returns> System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return new Enumerator(this); } #endregion #region Enumerator Inner Class /// <summary> /// The enumerator that enumerates each meta-collection of the enclosing Combinations class. /// </summary> public class Enumerator : IEnumerator<IList<T>> { #region Constructors /// <summary> /// Construct a enumerator with the parent object. /// </summary> /// <param name="source">The source combinations object.</param> public Enumerator(Combinations<T> source) { myParent = source; myPermutationsEnumerator = (Permutations<bool>.Enumerator)myParent.myPermutations.GetEnumerator(); } #endregion #region IEnumerator interface /// <summary> /// Resets the combinations enumerator to the first combination. /// </summary> public void Reset() { myPermutationsEnumerator.Reset(); } /// <summary> /// Advances to the next combination of items from the set. /// </summary> /// <returns>True if successfully moved to next combination, False if no more unique combinations exist.</returns> /// <remarks> /// The heavy lifting is done by the permutations object, the combination is generated /// by creating a new list of those items that have a true in the permutation parrellel array. /// </remarks> public bool MoveNext() { bool ret = myPermutationsEnumerator.MoveNext(); myCurrentList = null; return ret; } /// <summary> /// The current combination /// </summary> public IList<T> Current { get { ComputeCurrent(); return myCurrentList; } } /// <summary> /// The current combination /// </summary> object System.Collections.IEnumerator.Current { get { ComputeCurrent(); return myCurrentList; } } /// <summary> /// Cleans up non-managed resources, of which there are none used here. /// </summary> public void Dispose() { ; } #endregion #region Heavy Lifting Members /// <summary> /// The only complex function of this entire wrapper, ComputeCurrent() creates /// a list of original values from the bool permutation provided. /// The exception for accessing current (InvalidOperationException) is generated /// by the call to .Current on the underlying enumeration. /// </summary> /// <remarks> /// To compute the current list of values, the underlying permutation object /// which moves with this enumerator, is scanned differently based on the type. /// The items have only two values, true and false, which have different meanings: /// /// For type WithoutRepetition, the output is a straightforward subset of the input array. /// E.g. 6 choose 3 without repetition /// Input array: {A B C D E F} /// Permutations: {0 1 0 0 1 1} /// Generates set: {A C D } /// Note: size of permutation is equal to upper index. /// /// For type WithRepetition, the output is defined by runs of characters and when to /// move to the next element. /// E.g. 6 choose 5 with repetition /// Input array: {A B C D E F} /// Permutations: {0 1 0 0 1 1 0 0 1 1} /// Generates set: {A B B D D } /// Note: size of permutation is equal to upper index - 1 + lower index. /// </remarks> private void ComputeCurrent() { if(myCurrentList == null) { myCurrentList = new List<T>(); int index = 0; IList<bool> currentPermutation = (IList<bool>)myPermutationsEnumerator.Current; for(int i = 0; i < currentPermutation.Count; ++i) { if(currentPermutation[i] == false) { myCurrentList.Add(myParent.myValues[index]); if(myParent.Type == GenerateOption.WithoutRepetition) { ++index; } } else { ++index; } } } } #endregion #region Data /// <summary> /// Parent object this is an enumerator for. /// </summary> private Combinations<T> myParent; /// <summary> /// The current list of values, this is lazy evaluated by the Current property. /// </summary> private List<T> myCurrentList; /// <summary> /// An enumertor of the parents list of lexicographic orderings. /// </summary> private Permutations<bool>.Enumerator myPermutationsEnumerator; #endregion } #endregion #region IMetaList Interface /// <summary> /// The number of unique combinations that are defined in this meta-collection. /// This value is mathematically defined as Choose(M, N) where M is the set size /// and N is the subset size. This is M! / (N! * (M-N)!). /// </summary> public long Count { get { return myPermutations.Count; } } /// <summary> /// The type of Combinations set that is generated. /// </summary> public GenerateOption Type { get { return myMetaCollectionType; } } /// <summary> /// The upper index of the meta-collection, equal to the number of items in the initial set. /// </summary> public int UpperIndex { get { return myValues.Count; } } /// <summary> /// The lower index of the meta-collection, equal to the number of items returned each iteration. /// </summary> public int LowerIndex { get { return myLowerIndex; } } #endregion #region Heavy Lifting Members /// <summary> /// Initialize the combinations by settings a copy of the values from the /// </summary> /// <param name="values">List of values to select combinations from.</param> /// <param name="lowerIndex">The size of each combination set to return.</param> /// <param name="type">The type of Combinations set to generate.</param> /// <remarks> /// Copies the array and parameters and then creates a map of booleans that will /// be used by a permutations object to refence the subset. This map is slightly /// different based on whether the type is with or without repetition. /// /// When the type is WithoutRepetition, then a map of upper index elements is /// created with lower index false's. /// E.g. 8 choose 3 generates: /// Map: {1 1 1 1 1 0 0 0} /// Note: For sorting reasons, false denotes inclusion in output. /// /// When the type is WithRepetition, then a map of upper index - 1 + lower index /// elements is created with the falses indicating that the 'current' element should /// be included and the trues meaning to advance the 'current' element by one. /// E.g. 8 choose 3 generates: /// Map: {1 1 1 1 1 1 1 1 0 0 0} (7 trues, 3 falses). /// </remarks> private void Initialize(IList<T> values, int lowerIndex, GenerateOption type) { myMetaCollectionType = type; myLowerIndex = lowerIndex; myValues = new List<T>(); myValues.AddRange(values); List<bool> myMap = new List<bool>(); if(type == GenerateOption.WithoutRepetition) { for(int i = 0; i < myValues.Count; ++i) { if(i >= myValues.Count - myLowerIndex) { myMap.Add(false); } else { myMap.Add(true); } } } else { for(int i = 0; i < values.Count - 1; ++i) { myMap.Add(true); } for(int i = 0; i < myLowerIndex; ++i) { myMap.Add(false); } } myPermutations = new Permutations<bool>(myMap); } #endregion #region Data /// <summary> /// Copy of values object is intialized with, required for enumerator reset. /// </summary> private List<T> myValues; /// <summary> /// Permutations object that handles permutations on booleans for combination inclusion. /// </summary> private Permutations<bool> myPermutations; /// <summary> /// The type of the combination collection. /// </summary> private GenerateOption myMetaCollectionType; /// <summary> /// The lower index defined in the constructor. /// </summary> private int myLowerIndex; #endregion } }
using log4net; using Mono.Addins; using Nini.Config; using Nwc.XmlRpc; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Interfaces; using OpenSim.Region.Framework.Scenes; using System; using System.Collections; using System.Collections.Generic; using System.Net; using System.Net.Sockets; using System.Reflection; using System.Threading; using System.Xml; using DirFindFlags = OpenMetaverse.DirectoryManager.DirFindFlags; [assembly: Addin("OpenSimSearch", "0.3")] [assembly: AddinDependency("OpenSim", "0.5")] namespace OpenSimSearch.Modules.OpenSearch { [Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")] public class OpenSearchModule : ISearchModule, ISharedRegionModule { // // Log module // private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); // // Module vars // private ThreadedClasses.RwLockedList<Scene> m_Scenes = new ThreadedClasses.RwLockedList<Scene>(); private string m_SearchServer = ""; private bool m_Enabled = true; #region IRegionModuleBase implementation public void Initialise(IConfigSource config) { IConfig searchConfig = config.Configs["Search"]; if (searchConfig == null) { m_Enabled = false; return; } if (searchConfig.GetString("Module", "OpenSimSearch") != "OpenSimSearch") { m_Enabled = false; return; } m_SearchServer = searchConfig.GetString("SearchURL", ""); if (m_SearchServer == "") { m_log.Error("[SEARCH] No search server, disabling search"); m_Enabled = false; return; } m_log.Info("[SEARCH] OpenSimSearch module is active"); m_Enabled = true; } public void AddRegion(Scene scene) { if (!m_Enabled) return; // Hook up events scene.EventManager.OnNewClient += OnNewClient; // Take ownership of the ISearchModule service scene.RegisterModuleInterface<ISearchModule>(this); // Add our scene to our list... m_Scenes.Add(scene); } public void RemoveRegion(Scene scene) { if (!m_Enabled) return; scene.UnregisterModuleInterface<ISearchModule>(this); m_Scenes.Remove(scene); } public void RegionLoaded(Scene scene) { } public Type ReplaceableInterface { get { return null; } } public void PostInitialise() { } public void Close() { } public string Name { get { return "SearchModule"; } } public bool IsSharedModule { get { return true; } } #endregion /// New Client Event Handler private void OnNewClient(IClientAPI client) { // Subscribe to messages client.OnDirPlacesQuery += DirPlacesQuery; client.OnDirFindQuery += DirFindQuery; client.OnDirPopularQuery += DirPopularQuery; client.OnDirLandQuery += DirLandQuery; client.OnDirClassifiedQuery += DirClassifiedQuery; // Response after Directory Queries client.OnEventInfoRequest += EventInfoRequest; client.OnClassifiedInfoRequest += ClassifiedInfoRequest; client.OnMapItemRequest += HandleMapItemRequest; } // // Make external XMLRPC request // private Hashtable GenericXMLRPCRequest(Hashtable ReqParams, string method) { ArrayList SendParams = new ArrayList(); SendParams.Add(ReqParams); // Send Request XmlRpcResponse Resp; try { XmlRpcRequest Req = new XmlRpcRequest(method, SendParams); Resp = Req.Send(m_SearchServer, 30000); } catch (WebException ex) { m_log.ErrorFormat("[SEARCH]: Unable to connect to Search " + "Server {0}. Exception {1}", m_SearchServer, ex); Hashtable ErrorHash = new Hashtable(); ErrorHash["success"] = false; ErrorHash["errorMessage"] = "Unable to search at this time. "; ErrorHash["errorURI"] = ""; return ErrorHash; } catch (SocketException ex) { m_log.ErrorFormat( "[SEARCH]: Unable to connect to Search Server {0}. " + "Exception {1}", m_SearchServer, ex); Hashtable ErrorHash = new Hashtable(); ErrorHash["success"] = false; ErrorHash["errorMessage"] = "Unable to search at this time. "; ErrorHash["errorURI"] = ""; return ErrorHash; } catch (XmlException ex) { m_log.ErrorFormat( "[SEARCH]: Unable to connect to Search Server {0}. " + "Exception {1}", m_SearchServer, ex); Hashtable ErrorHash = new Hashtable(); ErrorHash["success"] = false; ErrorHash["errorMessage"] = "Unable to search at this time. "; ErrorHash["errorURI"] = ""; return ErrorHash; } if (Resp.IsFault) { Hashtable ErrorHash = new Hashtable(); ErrorHash["success"] = false; ErrorHash["errorMessage"] = "Unable to search at this time. "; ErrorHash["errorURI"] = ""; return ErrorHash; } Hashtable RespData = (Hashtable)Resp.Value; return RespData; } protected void DirPlacesQuery(IClientAPI remoteClient, UUID queryID, string queryText, int queryFlags, int category, string simName, int queryStart) { Hashtable ReqHash = new Hashtable(); ReqHash["text"] = queryText; ReqHash["flags"] = queryFlags.ToString(); ReqHash["category"] = category.ToString(); ReqHash["sim_name"] = simName; ReqHash["query_start"] = queryStart.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_places_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; DirPlacesReplyData[] data = new DirPlacesReplyData[count]; int i = 0; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; data[i] = new DirPlacesReplyData(); data[i].parcelID = new UUID(d["parcel_id"].ToString()); data[i].name = d["name"].ToString(); data[i].forSale = Convert.ToBoolean(d["for_sale"]); data[i].auction = Convert.ToBoolean(d["auction"]); data[i].dwell = Convert.ToSingle(d["dwell"]); if (++i >= count) break; } remoteClient.SendDirPlacesReply(queryID, data); } public void DirPopularQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags) { Hashtable ReqHash = new Hashtable(); ReqHash["flags"] = queryFlags.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_popular_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; DirPopularReplyData[] data = new DirPopularReplyData[count]; int i = 0; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; data[i] = new DirPopularReplyData(); data[i].parcelID = new UUID(d["parcel_id"].ToString()); data[i].name = d["name"].ToString(); data[i].dwell = Convert.ToSingle(d["dwell"]); if (++i >= count) break; } remoteClient.SendDirPopularReply(queryID, data); } public void DirLandQuery(IClientAPI remoteClient, UUID queryID, uint queryFlags, uint searchType, int price, int area, int queryStart) { Hashtable ReqHash = new Hashtable(); ReqHash["flags"] = queryFlags.ToString(); ReqHash["type"] = searchType.ToString(); ReqHash["price"] = price.ToString(); ReqHash["area"] = area.ToString(); ReqHash["query_start"] = queryStart.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_land_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = 0; /* Count entries in dataArray with valid region name to */ /* prevent allocating data array with too many entries. */ foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; if (d["name"] != null) ++count; } if (count > 100) count = 101; DirLandReplyData[] data = new DirLandReplyData[count]; int i = 0; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; if (d["name"] == null) continue; data[i] = new DirLandReplyData(); data[i].parcelID = new UUID(d["parcel_id"].ToString()); data[i].name = d["name"].ToString(); data[i].auction = Convert.ToBoolean(d["auction"]); data[i].forSale = Convert.ToBoolean(d["for_sale"]); data[i].salePrice = Convert.ToInt32(d["sale_price"]); data[i].actualArea = Convert.ToInt32(d["area"]); if (++i >= count) break; } remoteClient.SendDirLandReply(queryID, data); } public void DirFindQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { if (((DirFindFlags)queryFlags & DirFindFlags.DateEvents) == DirFindFlags.DateEvents) { DirEventsQuery(remoteClient, queryID, queryText, queryFlags, queryStart); return; } } public void DirEventsQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, int queryStart) { Hashtable ReqHash = new Hashtable(); ReqHash["text"] = queryText; ReqHash["flags"] = queryFlags.ToString(); ReqHash["query_start"] = queryStart.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_events_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; DirEventsReplyData[] data = new DirEventsReplyData[count]; int i = 0; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; data[i] = new DirEventsReplyData(); data[i].ownerID = new UUID(d["owner_id"].ToString()); data[i].name = d["name"].ToString(); data[i].eventID = Convert.ToUInt32(d["event_id"]); data[i].date = d["date"].ToString(); data[i].unixTime = Convert.ToUInt32(d["unix_time"]); data[i].eventFlags = Convert.ToUInt32(d["event_flags"]); if (++i >= count) break; } remoteClient.SendDirEventsReply(queryID, data); } public void DirClassifiedQuery(IClientAPI remoteClient, UUID queryID, string queryText, uint queryFlags, uint category, int queryStart) { Hashtable ReqHash = new Hashtable(); ReqHash["text"] = queryText; ReqHash["flags"] = queryFlags.ToString(); ReqHash["category"] = category.ToString(); ReqHash["query_start"] = queryStart.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_classified_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; DirClassifiedReplyData[] data = new DirClassifiedReplyData[count]; int i = 0; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; data[i] = new DirClassifiedReplyData(); data[i].classifiedID = new UUID(d["classifiedid"].ToString()); data[i].name = d["name"].ToString(); data[i].classifiedFlags = Convert.ToByte(d["classifiedflags"]); data[i].creationDate = Convert.ToUInt32(d["creation_date"]); data[i].expirationDate = Convert.ToUInt32(d["expiration_date"]); data[i].price = Convert.ToInt32(d["priceforlisting"]); if (++i >= count) break; } remoteClient.SendDirClassifiedReply(queryID, data); } public void EventInfoRequest(IClientAPI remoteClient, uint queryEventID) { Hashtable ReqHash = new Hashtable(); ReqHash["eventID"] = queryEventID.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "event_info_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; if (dataArray.Count == 0) { // something bad happened here, if we could return an // event after the search, // we should be able to find it here // TODO do some (more) sensible error-handling here remoteClient.SendAgentAlertMessage("Couldn't find this event.", false); return; } Hashtable d = (Hashtable)dataArray[0]; EventData data = new EventData(); data.eventID = Convert.ToUInt32(d["event_id"]); data.creator = d["creator"].ToString(); data.name = d["name"].ToString(); data.category = d["category"].ToString(); data.description = d["description"].ToString(); data.date = d["date"].ToString(); data.dateUTC = Convert.ToUInt32(d["dateUTC"]); data.duration = Convert.ToUInt32(d["duration"]); data.cover = Convert.ToUInt32(d["covercharge"]); data.amount = Convert.ToUInt32(d["coveramount"]); data.simName = d["simname"].ToString(); Vector3.TryParse(d["globalposition"].ToString(), out data.globalPos); data.eventFlags = Convert.ToUInt32(d["eventflags"]); remoteClient.SendEventInfoReply(data); } public void ClassifiedInfoRequest(UUID queryClassifiedID, IClientAPI remoteClient) { Hashtable ReqHash = new Hashtable(); ReqHash["classifiedID"] = queryClassifiedID.ToString(); Hashtable result = GenericXMLRPCRequest(ReqHash, "classifieds_info_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } //The viewer seems to issue an info request even when it is //creating a new classified which means the data hasn't been //saved to the database yet so there is no info to find. ArrayList dataArray = (ArrayList)result["data"]; if (dataArray.Count == 0) { // Something bad happened here if we could not return an // event after the search. We should be able to find it here. // TODO do some (more) sensible error-handling here // remoteClient.SendAgentAlertMessage("Couldn't find data for classified ad.", // false); return; } Hashtable d = (Hashtable)dataArray[0]; Vector3 globalPos = new Vector3(); Vector3.TryParse(d["posglobal"].ToString(), out globalPos); remoteClient.SendClassifiedInfoReply( new UUID(d["classifieduuid"].ToString()), new UUID(d["creatoruuid"].ToString()), Convert.ToUInt32(d["creationdate"]), Convert.ToUInt32(d["expirationdate"]), Convert.ToUInt32(d["category"]), d["name"].ToString(), d["description"].ToString(), new UUID(d["parceluuid"].ToString()), Convert.ToUInt32(d["parentestate"]), new UUID(d["snapshotuuid"].ToString()), d["simname"].ToString(), globalPos, d["parcelname"].ToString(), Convert.ToByte(d["classifiedflags"]), Convert.ToInt32(d["priceforlisting"])); } public void HandleMapItemRequest(IClientAPI remoteClient, uint flags, uint EstateID, bool godlike, uint itemtype, ulong regionhandle) { //The following constant appears to be from GridLayerType enum //defined in OpenMetaverse/GridManager.cs of libopenmetaverse. if (itemtype == (uint)OpenMetaverse.GridItemType.LandForSale) { Hashtable ReqHash = new Hashtable(); //The flags are: SortAsc (1 << 15), PerMeterSort (1 << 17) ReqHash["flags"] = "163840"; ReqHash["type"] = "4294967295"; //This is -1 in 32 bits ReqHash["price"] = "0"; ReqHash["area"] = "0"; ReqHash["query_start"] = "0"; Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_land_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; int count = dataArray.Count; if (count > 100) count = 101; List<mapItemReply> mapitems = new List<mapItemReply>(); string ParcelRegionUUID; string[] landingpoint; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; if (d["name"] == null) continue; mapItemReply mapitem = new mapItemReply(); ParcelRegionUUID = d["region_UUID"].ToString(); foreach (Scene scene in m_Scenes) { if (scene.RegionInfo.RegionID.ToString() == ParcelRegionUUID) { landingpoint = d["landing_point"].ToString().Split('/'); mapitem.x = (uint)((scene.RegionInfo.RegionLocX * 256) + Convert.ToDecimal(landingpoint[0])); mapitem.y = (uint)((scene.RegionInfo.RegionLocY * 256) + Convert.ToDecimal(landingpoint[1])); break; } } mapitem.id = new UUID(d["parcel_id"].ToString()); mapitem.Extra = Convert.ToInt32(d["area"]); mapitem.Extra2 = Convert.ToInt32(d["sale_price"]); mapitem.name = d["name"].ToString(); mapitems.Add(mapitem); } remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } if (itemtype == (uint)OpenMetaverse.GridItemType.PgEvent || itemtype == (uint)OpenMetaverse.GridItemType.MatureEvent || itemtype == (uint)OpenMetaverse.GridItemType.AdultEvent) { Hashtable ReqHash = new Hashtable(); //Find the maturity level int maturity = (1 << 24); //Find the maturity level if (itemtype == (uint)OpenMetaverse.GridItemType.MatureEvent) maturity = (1 << 25); else { if (itemtype == (uint)OpenMetaverse.GridItemType.AdultEvent) maturity = (1 << 26); } //The flags are: SortAsc (1 << 15), PerMeterSort (1 << 17) maturity |= 163840; //Character before | is number of days before/after current date //Characters after | is the number for a category ReqHash["text"] = "0|0"; ReqHash["flags"] = maturity.ToString(); ReqHash["query_start"] = "0"; Hashtable result = GenericXMLRPCRequest(ReqHash, "dir_events_query"); if (!Convert.ToBoolean(result["success"])) { remoteClient.SendAgentAlertMessage( result["errorMessage"].ToString(), false); return; } ArrayList dataArray = (ArrayList)result["data"]; List<mapItemReply> mapitems = new List<mapItemReply>(); int event_id; string[] landingpoint; foreach (Object o in dataArray) { Hashtable d = (Hashtable)o; if (d["name"] == null) continue; mapItemReply mapitem = new mapItemReply(); //Events use a comma separator in the landing point landingpoint = d["landing_point"].ToString().Split(','); mapitem.x = Convert.ToUInt32(landingpoint[0]); mapitem.y = Convert.ToUInt32(landingpoint[1]); //This is a crazy way to pass the event ID back to the //viewer but that is the way it wants the information. event_id = Convert.ToInt32(d["event_id"]); mapitem.id = new UUID("00000000-0000-0000-0000-0000" + event_id.ToString("X8")); mapitem.Extra = Convert.ToInt32(d["unix_time"]); mapitem.Extra2 = 0; //FIXME: No idea what to do here mapitem.name = d["name"].ToString(); mapitems.Add(mapitem); } remoteClient.SendMapItemReply(mapitems.ToArray(), itemtype, flags); mapitems.Clear(); } } public void Refresh() { } } }
namespace Factotum { partial class MaterialTypeView { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MaterialTypeView)); this.btnEdit = new System.Windows.Forms.Button(); this.label1 = new System.Windows.Forms.Label(); this.btnAdd = new System.Windows.Forms.Button(); this.btnDelete = new System.Windows.Forms.Button(); this.cboStatusFilter = new System.Windows.Forms.ComboBox(); this.label2 = new System.Windows.Forms.Label(); this.dgvMaterialTypeList = new Factotum.DataGridViewStd(); this.label3 = new System.Windows.Forms.Label(); this.txtNameFilter = new System.Windows.Forms.TextBox(); this.label4 = new System.Windows.Forms.Label(); this.cboSiteFilter = new System.Windows.Forms.ComboBox(); this.panel1 = new System.Windows.Forms.Panel(); this.label5 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dgvMaterialTypeList)).BeginInit(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // btnEdit // this.btnEdit.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnEdit.Location = new System.Drawing.Point(11, 234); this.btnEdit.Name = "btnEdit"; this.btnEdit.Size = new System.Drawing.Size(64, 22); this.btnEdit.TabIndex = 2; this.btnEdit.Text = "Edit"; this.btnEdit.UseVisualStyleBackColor = true; this.btnEdit.Click += new System.EventHandler(this.btnEdit_Click); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 105); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(95, 13); this.label1.TabIndex = 5; this.label1.Text = "Material Types List"; // // btnAdd // this.btnAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnAdd.Location = new System.Drawing.Point(81, 234); this.btnAdd.Name = "btnAdd"; this.btnAdd.Size = new System.Drawing.Size(64, 22); this.btnAdd.TabIndex = 3; this.btnAdd.Text = "Add"; this.btnAdd.UseVisualStyleBackColor = true; this.btnAdd.Click += new System.EventHandler(this.btnAdd_Click); // // btnDelete // this.btnDelete.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.btnDelete.Location = new System.Drawing.Point(151, 234); this.btnDelete.Name = "btnDelete"; this.btnDelete.Size = new System.Drawing.Size(64, 22); this.btnDelete.TabIndex = 4; this.btnDelete.Text = "Delete"; this.btnDelete.UseVisualStyleBackColor = true; this.btnDelete.Click += new System.EventHandler(this.btnDelete_Click); // // cboStatusFilter // this.cboStatusFilter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboStatusFilter.FormattingEnabled = true; this.cboStatusFilter.Items.AddRange(new object[] { "Active", "Inactive"}); this.cboStatusFilter.Location = new System.Drawing.Point(228, 40); this.cboStatusFilter.Name = "cboStatusFilter"; this.cboStatusFilter.Size = new System.Drawing.Size(85, 21); this.cboStatusFilter.TabIndex = 5; this.cboStatusFilter.SelectedIndexChanged += new System.EventHandler(this.cboStatus_SelectedIndexChanged); // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(185, 43); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(37, 13); this.label2.TabIndex = 4; this.label2.Text = "Status"; // // dgvMaterialTypeList // this.dgvMaterialTypeList.AllowUserToAddRows = false; this.dgvMaterialTypeList.AllowUserToDeleteRows = false; this.dgvMaterialTypeList.AllowUserToOrderColumns = true; this.dgvMaterialTypeList.AllowUserToResizeRows = false; this.dgvMaterialTypeList.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.dgvMaterialTypeList.Location = new System.Drawing.Point(12, 121); this.dgvMaterialTypeList.MultiSelect = false; this.dgvMaterialTypeList.Name = "dgvMaterialTypeList"; this.dgvMaterialTypeList.ReadOnly = true; this.dgvMaterialTypeList.RowHeadersVisible = false; this.dgvMaterialTypeList.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dgvMaterialTypeList.Size = new System.Drawing.Size(331, 107); this.dgvMaterialTypeList.StandardTab = true; this.dgvMaterialTypeList.TabIndex = 6; this.dgvMaterialTypeList.DoubleClick += new System.EventHandler(this.btnEdit_Click); this.dgvMaterialTypeList.KeyDown += new System.Windows.Forms.KeyEventHandler(this.dgvMaterialTypeList_KeyDown); // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(7, 44); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(71, 13); this.label3.TabIndex = 2; this.label3.Text = "Material Type"; // // txtNameFilter // this.txtNameFilter.Location = new System.Drawing.Point(84, 41); this.txtNameFilter.Name = "txtNameFilter"; this.txtNameFilter.Size = new System.Drawing.Size(81, 20); this.txtNameFilter.TabIndex = 3; this.txtNameFilter.TextChanged += new System.EventHandler(this.txtNameFilter_TextChanged); // // label4 // this.label4.AutoSize = true; this.label4.Location = new System.Drawing.Point(7, 17); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(25, 13); this.label4.TabIndex = 0; this.label4.Text = "Site"; // // cboSiteFilter // this.cboSiteFilter.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.cboSiteFilter.FormattingEnabled = true; this.cboSiteFilter.Items.AddRange(new object[] { "Active", "Inactive"}); this.cboSiteFilter.Location = new System.Drawing.Point(38, 14); this.cboSiteFilter.Name = "cboSiteFilter"; this.cboSiteFilter.Size = new System.Drawing.Size(127, 21); this.cboSiteFilter.TabIndex = 1; // // panel1 // this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle; this.panel1.Controls.Add(this.txtNameFilter); this.panel1.Controls.Add(this.label4); this.panel1.Controls.Add(this.cboStatusFilter); this.panel1.Controls.Add(this.cboSiteFilter); this.panel1.Controls.Add(this.label2); this.panel1.Controls.Add(this.label3); this.panel1.ForeColor = System.Drawing.SystemColors.ControlText; this.panel1.Location = new System.Drawing.Point(15, 18); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(324, 75); this.panel1.TabIndex = 1; // // label5 // this.label5.AutoSize = true; this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label5.ForeColor = System.Drawing.SystemColors.ControlText; this.label5.Location = new System.Drawing.Point(22, 9); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(53, 13); this.label5.TabIndex = 0; this.label5.Text = "List Filters"; // // MaterialTypeView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(355, 268); this.Controls.Add(this.label5); this.Controls.Add(this.panel1); this.Controls.Add(this.dgvMaterialTypeList); this.Controls.Add(this.btnDelete); this.Controls.Add(this.btnAdd); this.Controls.Add(this.label1); this.Controls.Add(this.btnEdit); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MinimumSize = new System.Drawing.Size(363, 302); this.Name = "MaterialTypeView"; this.Text = " View Component Material Types"; this.Load += new System.EventHandler(this.MaterialTypeView_Load); this.FormClosed += new System.Windows.Forms.FormClosedEventHandler(this.MaterialTypeView_FormClosed); ((System.ComponentModel.ISupportInitialize)(this.dgvMaterialTypeList)).EndInit(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Button btnEdit; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button btnAdd; private System.Windows.Forms.Button btnDelete; private System.Windows.Forms.ComboBox cboStatusFilter; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.TextBox txtNameFilter; private System.Windows.Forms.Label label4; private System.Windows.Forms.ComboBox cboSiteFilter; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.Label label5; private DataGridViewStd dgvMaterialTypeList; } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. namespace System.Globalization { using System; using System.Text; using System.Diagnostics.Contracts; //////////////////////////////////////////////////////////////////////////// // // Used in HebrewNumber.ParseByChar to maintain the context information ( // the state in the state machine and current Hebrew number values, etc.) // when parsing Hebrew number character by character. // //////////////////////////////////////////////////////////////////////////// internal struct HebrewNumberParsingContext { // The current state of the state machine for parsing Hebrew numbers. internal HebrewNumber.HS state; // The current value of the Hebrew number. // The final value is determined when state is FoundEndOfHebrewNumber. internal int result; public HebrewNumberParsingContext(int result) { // Set the start state of the state machine for parsing Hebrew numbers. state = HebrewNumber.HS.Start; this.result = result; } } //////////////////////////////////////////////////////////////////////////// // // Please see ParseByChar() for comments about different states defined here. // //////////////////////////////////////////////////////////////////////////// internal enum HebrewNumberParsingState { InvalidHebrewNumber, NotHebrewDigit, FoundEndOfHebrewNumber, ContinueParsing, } //////////////////////////////////////////////////////////////////////////// // // class HebrewNumber // // Provides static methods for formatting integer values into // Hebrew text and parsing Hebrew number text. // // Limitations: // Parse can only handles value 1 ~ 999. // ToString() can only handles 1 ~ 999. If value is greater than 5000, // 5000 will be subtracted from the value. // //////////////////////////////////////////////////////////////////////////// internal class HebrewNumber { // This class contains only static methods. Add a private ctor so that // compiler won't generate a default one for us. private HebrewNumber() { } //////////////////////////////////////////////////////////////////////////// // // ToString // // Converts the given number to Hebrew letters according to the numeric // value of each Hebrew letter. Basically, this converts the lunar year // and the lunar month to letters. // // The character of a year is described by three letters of the Hebrew // alphabet, the first and third giving, respectively, the days of the // weeks on which the New Year occurs and Passover begins, while the // second is the initial of the Hebrew word for defective, normal, or // complete. // // Defective Year : Both Heshvan and Kislev are defective (353 or 383 days) // Normal Year : Heshvan is defective, Kislev is full (354 or 384 days) // Complete Year : Both Heshvan and Kislev are full (355 or 385 days) // //////////////////////////////////////////////////////////////////////////// internal static String ToString(int Number) { char cTens = '\x0'; char cUnits; // tens and units chars int Hundreds, Tens; // hundreds and tens values StringBuilder szHebrew = new StringBuilder(); // // Adjust the number if greater than 5000. // if (Number > 5000) { Number -= 5000; } Contract.Assert(Number > 0 && Number <= 999, "Number is out of range.");; // // Get the Hundreds. // Hundreds = Number / 100; if (Hundreds > 0) { Number -= Hundreds * 100; // \x05e7 = 100 // \x05e8 = 200 // \x05e9 = 300 // \x05ea = 400 // If the number is greater than 400, use the multiples of 400. for (int i = 0; i < (Hundreds / 4) ; i++) { szHebrew.Append('\x05ea'); } int remains = Hundreds % 4; if (remains > 0) { szHebrew.Append((char)((int)'\x05e6' + remains)); } } // // Get the Tens. // Tens = Number / 10; Number %= 10; switch (Tens) { case ( 0 ) : cTens = '\x0'; break; case ( 1 ) : cTens = '\x05d9'; // Hebrew Letter Yod break; case ( 2 ) : cTens = '\x05db'; // Hebrew Letter Kaf break; case ( 3 ) : cTens = '\x05dc'; // Hebrew Letter Lamed break; case ( 4 ) : cTens = '\x05de'; // Hebrew Letter Mem break; case ( 5 ) : cTens = '\x05e0'; // Hebrew Letter Nun break; case ( 6 ) : cTens = '\x05e1'; // Hebrew Letter Samekh break; case ( 7 ) : cTens = '\x05e2'; // Hebrew Letter Ayin break; case ( 8 ) : cTens = '\x05e4'; // Hebrew Letter Pe break; case ( 9 ) : cTens = '\x05e6'; // Hebrew Letter Tsadi break; } // // Get the Units. // cUnits = (char)(Number > 0 ? ((int)'\x05d0' + Number - 1) : 0); if ((cUnits == '\x05d4') && // Hebrew Letter He (5) (cTens == '\x05d9')) { // Hebrew Letter Yod (10) cUnits = '\x05d5'; // Hebrew Letter Vav (6) cTens = '\x05d8'; // Hebrew Letter Tet (9) } if ((cUnits == '\x05d5') && // Hebrew Letter Vav (6) (cTens == '\x05d9')) { // Hebrew Letter Yod (10) cUnits = '\x05d6'; // Hebrew Letter Zayin (7) cTens = '\x05d8'; // Hebrew Letter Tet (9) } // // Copy the appropriate info to the given buffer. // if (cTens != '\x0') { szHebrew.Append(cTens); } if (cUnits != '\x0') { szHebrew.Append(cUnits); } if (szHebrew.Length > 1) { szHebrew.Insert(szHebrew.Length - 1, '"'); } else { szHebrew.Append('\''); } // // Return success. // return (szHebrew.ToString()); } //////////////////////////////////////////////////////////////////////////// // // Token used to tokenize a Hebrew word into tokens so that we can use in the // state machine. // //////////////////////////////////////////////////////////////////////////// enum HebrewToken { Invalid = -1, Digit400 = 0, Digit200_300 = 1, Digit100 = 2, Digit10 = 3, // 10 ~ 90 Digit1 = 4, // 1, 2, 3, 4, 5, 8, Digit6_7 = 5, Digit7 = 6, Digit9 = 7, SingleQuote = 8, DoubleQuote = 9, }; //////////////////////////////////////////////////////////////////////////// // // This class is used to map a token into its Hebrew digit value. // //////////////////////////////////////////////////////////////////////////// class HebrewValue { internal HebrewToken token; internal int value; internal HebrewValue(HebrewToken token, int value) { this.token = token; this.value = value; } } // // Map a Hebrew character from U+05D0 ~ U+05EA to its digit value. // The value is -1 if the Hebrew character does not have a associated value. // static HebrewValue[] HebrewValues = { new HebrewValue(HebrewToken.Digit1, 1) , // '\x05d0 new HebrewValue(HebrewToken.Digit1, 2) , // '\x05d1 new HebrewValue(HebrewToken.Digit1, 3) , // '\x05d2 new HebrewValue(HebrewToken.Digit1, 4) , // '\x05d3 new HebrewValue(HebrewToken.Digit1, 5) , // '\x05d4 new HebrewValue(HebrewToken.Digit6_7,6) , // '\x05d5 new HebrewValue(HebrewToken.Digit6_7,7) , // '\x05d6 new HebrewValue(HebrewToken.Digit1, 8) , // '\x05d7 new HebrewValue(HebrewToken.Digit9, 9) , // '\x05d8 new HebrewValue(HebrewToken.Digit10, 10) , // '\x05d9; // Hebrew Letter Yod new HebrewValue(HebrewToken.Invalid, -1) , // '\x05da; new HebrewValue(HebrewToken.Digit10, 20) , // '\x05db; // Hebrew Letter Kaf new HebrewValue(HebrewToken.Digit10, 30) , // '\x05dc; // Hebrew Letter Lamed new HebrewValue(HebrewToken.Invalid, -1) , // '\x05dd; new HebrewValue(HebrewToken.Digit10, 40) , // '\x05de; // Hebrew Letter Mem new HebrewValue(HebrewToken.Invalid, -1) , // '\x05df; new HebrewValue(HebrewToken.Digit10, 50) , // '\x05e0; // Hebrew Letter Nun new HebrewValue(HebrewToken.Digit10, 60) , // '\x05e1; // Hebrew Letter Samekh new HebrewValue(HebrewToken.Digit10, 70) , // '\x05e2; // Hebrew Letter Ayin new HebrewValue(HebrewToken.Invalid, -1) , // '\x05e3; new HebrewValue(HebrewToken.Digit10, 80) , // '\x05e4; // Hebrew Letter Pe new HebrewValue(HebrewToken.Invalid, -1) , // '\x05e5; new HebrewValue(HebrewToken.Digit10, 90) , // '\x05e6; // Hebrew Letter Tsadi new HebrewValue(HebrewToken.Digit100, 100) , // '\x05e7; new HebrewValue(HebrewToken.Digit200_300, 200) , // '\x05e8; new HebrewValue(HebrewToken.Digit200_300, 300) , // '\x05e9; new HebrewValue(HebrewToken.Digit400, 400) , // '\x05ea; }; const int minHebrewNumberCh = 0x05d0; static char maxHebrewNumberCh = (char)(minHebrewNumberCh + HebrewValues.Length - 1); //////////////////////////////////////////////////////////////////////////// // // Hebrew number parsing State // The current state and the next token will lead to the next state in the state machine. // DQ = Double Quote // //////////////////////////////////////////////////////////////////////////// internal enum HS { _err = -1, // an error state Start = 0, S400 = 1, // a Hebrew digit 400 S400_400 = 2, // Two Hebrew digit 400 S400_X00 = 3, // Two Hebrew digit 400 and followed by 100 S400_X0 = 4, // Hebrew digit 400 and followed by 10 ~ 90 X00_DQ = 5, // A hundred number and followed by a double quote. S400_X00_X0 = 6, X0_DQ = 7, // A two-digit number and followed by a double quote. X = 8, // A single digit Hebrew number. X0 = 9, // A two-digit Hebrew number X00 = 10, // A three-digit Hebrew number S400_DQ = 11, // A Hebrew digit 400 and followed by a double quote. S400_400_DQ = 12, S400_400_100 = 13, S9 = 14, // Hebrew digit 9 X00_S9 = 15, // A hundered number and followed by a digit 9 S9_DQ = 16, // Hebrew digit 9 and followed by a double quote END = 100, // A terminial state is reached. } // // The state machine for Hebrew number pasing. // readonly static HS[][] NumberPasingState = { // 400 300/200 100 90~10 8~1 6, 7, 9, ' " /* 0 */ new HS[] {HS.S400, HS.X00, HS.X00, HS.X0, HS.X, HS.X, HS.X, HS.S9, HS._err, HS._err}, /* 1: S400 */ new HS[] {HS.S400_400, HS.S400_X00, HS.S400_X00, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS.END, HS.S400_DQ}, /* 2: S400_400 */ new HS[] {HS._err, HS._err, HS.S400_400_100,HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS._err, HS.S400_400_DQ}, /* 3: S400_X00 */ new HS[] {HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9 ,HS._err, HS.X00_DQ}, /* 4: S400_X0 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ}, /* 5: X00_DQ */ new HS[] {HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err}, /* 6: S400_X00_X0 */new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.X0_DQ}, /* 7: X0_DQ */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err}, /* 8: X */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS._err}, /* 9: X0 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.X0_DQ}, /* 10: X00 */ new HS[] {HS._err, HS._err, HS._err, HS.S400_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS.END, HS.X00_DQ}, /* 11: S400_DQ */ new HS[] {HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err}, /* 12: S400_400_DQ*/new HS[] {HS._err, HS._err, HS.END, HS.END, HS.END, HS.END, HS.END, HS.END, HS._err, HS._err}, /* 13: S400_400_100*/new HS[]{HS._err, HS._err, HS._err, HS.S400_X00_X0, HS._err, HS._err, HS._err, HS.X00_S9, HS._err, HS.X00_DQ}, /* 14: S9 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err,HS.END, HS.S9_DQ}, /* 15: X00_S9 */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS._err, HS.S9_DQ}, /* 16: S9_DQ */ new HS[] {HS._err, HS._err, HS._err, HS._err, HS._err, HS.END, HS.END, HS._err, HS._err, HS._err}, }; //////////////////////////////////////////////////////////////////////// // // Actions: // Parse the Hebrew number by passing one character at a time. // The state between characters are maintained at HebrewNumberPasingContext. // Returns: // Return a enum of HebrewNumberParsingState. // NotHebrewDigit: The specified ch is not a valid Hebrew digit. // InvalidHebrewNumber: After parsing the specified ch, it will lead into // an invalid Hebrew number text. // FoundEndOfHebrewNumber: A terminal state is reached. This means that // we find a valid Hebrew number text after the specified ch is parsed. // ContinueParsing: The specified ch is a valid Hebrew digit, and // it will lead into a valid state in the state machine, we should // continue to parse incoming characters. // //////////////////////////////////////////////////////////////////////// internal static HebrewNumberParsingState ParseByChar(char ch, ref HebrewNumberParsingContext context) { HebrewToken token; if (ch == '\'') { token = HebrewToken.SingleQuote; } else if (ch == '\"') { token = HebrewToken.DoubleQuote; } else { int index = (int)ch - minHebrewNumberCh; if (index >= 0 && index < HebrewValues.Length ) { token = HebrewValues[index].token; if (token == HebrewToken.Invalid) { return (HebrewNumberParsingState.NotHebrewDigit); } context.result += HebrewValues[index].value; } else { // Not in valid Hebrew digit range. return (HebrewNumberParsingState.NotHebrewDigit); } } context.state = NumberPasingState[(int)context.state][(int)token]; if (context.state == HS._err) { // Invalid Hebrew state. This indicates an incorrect Hebrew number. return (HebrewNumberParsingState.InvalidHebrewNumber); } if (context.state == HS.END) { // Reach a terminal state. return (HebrewNumberParsingState.FoundEndOfHebrewNumber); } // We should continue to parse. return (HebrewNumberParsingState.ContinueParsing); } //////////////////////////////////////////////////////////////////////// // // Actions: // Check if the ch is a valid Hebrew number digit. // This function will return true if the specified char is a legal Hebrew // digit character, single quote, or double quote. // Returns: // true if the specified character is a valid Hebrew number character. // //////////////////////////////////////////////////////////////////////// internal static bool IsDigit(char ch) { if (ch >= minHebrewNumberCh && ch <= maxHebrewNumberCh) { return (HebrewValues[ch - minHebrewNumberCh].value >= 0); } return (ch == '\'' || ch == '\"'); } } }
// Copyright 2007-2008 The Apache Software Foundation. // // Licensed under the Apache License, Version 2.0 (the "License"); you may not use // this file except in compliance with the License. You may obtain a copy of the // License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed // under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR // CONDITIONS OF ANY KIND, either express or implied. See the License for the // specific language governing permissions and limitations under the License. namespace MassTransit.Tests.Serialization { using System; using System.Linq; using System.Threading.Tasks; using Builders; using BusConfigurators; using MassTransit.Pipeline; 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 { public Deserializing_an_interface(Type serializerType) : base(serializerType) { } [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() { IConsumePipe 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 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) { DateTime 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).IsAssignableFrom(obj.GetType())) return false; return Equals((ComplaintAdded)obj); } public override int GetHashCode() { unchecked { int 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; } } } }
/****************************************************************************** * Spine Runtimes Software License * Version 2.3 * * Copyright (c) 2013-2015, Esoteric Software * All rights reserved. * * You are granted a perpetual, non-exclusive, non-sublicensable and * non-transferable license to use, install, execute and perform the Spine * Runtimes Software (the "Software") and derivative works solely for personal * or internal use. Without the written permission of Esoteric Software (see * Section 2 of the Spine Software License Agreement), you may not (a) modify, * translate, adapt or otherwise create derivative works, improvements of the * Software or develop new applications using the Software or (b) remove, * delete, alter or obscure any trademarks or any copyright, trademark, patent * or other intellectual property or proprietary rights notices on or in the * Software, including any copy thereof. Redistributions in binary or source * form must include this license and terms. * * THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "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 ESOTERIC SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, * PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; * OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR * OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. *****************************************************************************/ using System; namespace Spine { public class IkConstraint : IUpdatable { internal IkConstraintData data; internal ExposedList<Bone> bones = new ExposedList<Bone>(); internal Bone target; internal float mix; internal int bendDirection; internal int level; public IkConstraintData Data { get { return data; } } public ExposedList<Bone> Bones { get { return bones; } } public Bone Target { get { return target; } set { target = value; } } public int BendDirection { get { return bendDirection; } set { bendDirection = value; } } public float Mix { get { return mix; } set { mix = value; } } public IkConstraint (IkConstraintData data, Skeleton skeleton) { if (data == null) throw new ArgumentNullException("data", "data cannot be null."); if (skeleton == null) throw new ArgumentNullException("skeleton", "skeleton cannot be null."); this.data = data; mix = data.mix; bendDirection = data.bendDirection; bones = new ExposedList<Bone>(data.bones.Count); foreach (BoneData boneData in data.bones) bones.Add(skeleton.FindBone(boneData.name)); target = skeleton.FindBone(data.target.name); } public void Update () { Apply(); } public void Apply () { Bone target = this.target; ExposedList<Bone> bones = this.bones; switch (bones.Count) { case 1: Apply(bones.Items[0], target.worldX, target.worldY, mix); break; case 2: Apply(bones.Items[0], bones.Items[1], target.worldX, target.worldY, bendDirection, mix); break; } } override public String ToString () { return data.name; } /// <summary>Adjusts the bone rotation so the tip is as close to the target position as possible. The target is specified /// in the world coordinate system.</summary> static public void Apply (Bone bone, float targetX, float targetY, float alpha) { Bone pp = bone.parent; float id = 1 / (pp.a * pp.d - pp.b * pp.c); float x = targetX - pp.worldX, y = targetY - pp.worldY; float tx = (x * pp.d - y * pp.b) * id - bone.x, ty = (y * pp.a - x * pp.c) * id - bone.y; float rotationIK = MathUtils.Atan2(ty, tx) * MathUtils.radDeg - bone.shearX - bone.rotation; if (bone.scaleX < 0) rotationIK += 180; if (rotationIK > 180) rotationIK -= 360; else if (rotationIK < -180) rotationIK += 360; bone.UpdateWorldTransform(bone.x, bone.y, bone.rotation + rotationIK * alpha, bone.scaleX, bone.scaleY, bone.shearX, bone.shearY); } /// <summary>Adjusts the parent and child bone rotations so the tip of the child is as close to the target position as /// possible. The target is specified in the world coordinate system.</summary> /// <param name="child">A direct descendant of the parent bone.</param> static public void Apply (Bone parent, Bone child, float targetX, float targetY, int bendDir, float alpha) { if (alpha == 0) { child.UpdateWorldTransform (); return; } float px = parent.x, py = parent.y, psx = parent.scaleX, psy = parent.scaleY, csx = child.scaleX; int os1, os2, s2; if (psx < 0) { psx = -psx; os1 = 180; s2 = -1; } else { os1 = 0; s2 = 1; } if (psy < 0) { psy = -psy; s2 = -s2; } if (csx < 0) { csx = -csx; os2 = 180; } else os2 = 0; float cx = child.x, cy, cwx, cwy, a = parent.a, b = parent.b, c = parent.c, d = parent.d; bool u = Math.Abs(psx - psy) <= 0.0001f; if (!u) { cy = 0; cwx = a * cx + parent.worldX; cwy = c * cx + parent.worldY; } else { cy = child.y; cwx = a * cx + b * cy + parent.worldX; cwy = c * cx + d * cy + parent.worldY; } Bone pp = parent.parent; a = pp.a; b = pp.b; c = pp.c; d = pp.d; float id = 1 / (a * d - b * c), x = targetX - pp.worldX, y = targetY - pp.worldY; float tx = (x * d - y * b) * id - px, ty = (y * a - x * c) * id - py; x = cwx - pp.worldX; y = cwy - pp.worldY; float dx = (x * d - y * b) * id - px, dy = (y * a - x * c) * id - py; float l1 = (float)Math.Sqrt(dx * dx + dy * dy), l2 = child.data.length * csx, a1, a2; if (u) { l2 *= psx; float cos = (tx * tx + ty * ty - l1 * l1 - l2 * l2) / (2 * l1 * l2); if (cos < -1) cos = -1; else if (cos > 1) cos = 1; a2 = (float)Math.Acos(cos) * bendDir; a = l1 + l2 * cos; b = l2 * MathUtils.Sin(a2); a1 = MathUtils.Atan2(ty * a - tx * b, tx * a + ty * b); } else { a = psx * l2; b = psy * l2; float aa = a * a, bb = b * b, dd = tx * tx + ty * ty, ta = MathUtils.Atan2(ty, tx); c = bb * l1 * l1 + aa * dd - aa * bb; float c1 = -2 * bb * l1, c2 = bb - aa; d = c1 * c1 - 4 * c2 * c; if (d >= 0) { float q = (float)Math.Sqrt(d); if (c1 < 0) q = -q; q = -(c1 + q) / 2; float r0 = q / c2, r1 = c / q; float r = Math.Abs(r0) < Math.Abs(r1) ? r0 : r1; if (r * r <= dd) { y = (float)Math.Sqrt(dd - r * r) * bendDir; a1 = ta - MathUtils.Atan2(y, r); a2 = MathUtils.Atan2(y / psy, (r - l1) / psx); goto outer; } } float minAngle = 0, minDist = float.MaxValue, minX = 0, minY = 0; float maxAngle = 0, maxDist = 0, maxX = 0, maxY = 0; x = l1 + a; d = x * x; if (d > maxDist) { maxAngle = 0; maxDist = d; maxX = x; } x = l1 - a; d = x * x; if (d < minDist) { minAngle = MathUtils.PI; minDist = d; minX = x; } float angle = (float)Math.Acos(-a * l1 / (aa - bb)); x = a * MathUtils.Cos(angle) + l1; y = b * MathUtils.Sin(angle); d = x * x + y * y; if (d < minDist) { minAngle = angle; minDist = d; minX = x; minY = y; } if (d > maxDist) { maxAngle = angle; maxDist = d; maxX = x; maxY = y; } if (dd <= (minDist + maxDist) / 2) { a1 = ta - MathUtils.Atan2(minY * bendDir, minX); a2 = minAngle * bendDir; } else { a1 = ta - MathUtils.Atan2(maxY * bendDir, maxX); a2 = maxAngle * bendDir; } } outer: float os = MathUtils.Atan2(cy, cx) * s2; float rotation = parent.rotation; a1 = (a1 - os) * MathUtils.radDeg + os1 - rotation; if (a1 > 180) a1 -= 360; else if (a1 < -180) a1 += 360; parent.UpdateWorldTransform(px, py, rotation + a1 * alpha, parent.scaleX, parent.scaleY, 0, 0); rotation = child.rotation; a2 = ((a2 + os) * MathUtils.radDeg - child.shearX) * s2 + os2 - rotation; if (a2 > 180) a2 -= 360; else if (a2 < -180) a2 += 360; child.UpdateWorldTransform(cx, cy, rotation + a2 * alpha, child.scaleX, child.scaleY, child.shearX, child.shearY); } } }
// 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.Specialized; using System.Diagnostics; using System.Globalization; using System.IO; using System.Net.WebSockets; using System.Runtime.InteropServices; using System.Security; using System.Security.Authentication.ExtendedProtection; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Security.Principal; using System.Text; using System.Threading.Tasks; namespace System.Net { public sealed unsafe partial class HttpListenerRequest { private ulong _requestId; internal ulong _connectionId; private SslStatus _sslStatus; private string _cookedUrlHost; private string _cookedUrlPath; private string _cookedUrlQuery; private long _contentLength; private Stream _requestStream; private string _httpMethod; private bool? _keepAlive; private WebHeaderCollection _webHeaders; private IPEndPoint _localEndPoint; private IPEndPoint _remoteEndPoint; private BoundaryType _boundaryType; private ListenerClientCertState _clientCertState; private X509Certificate2 _clientCertificate; private int _clientCertificateError; private RequestContextBase _memoryBlob; private HttpListenerContext _httpContext; private bool _isDisposed = false; internal const uint CertBoblSize = 1500; private string _serviceName; private object _lock = new object(); private enum SslStatus : byte { Insecure, NoClientCert, ClientCert } internal HttpListenerRequest(HttpListenerContext httpContext, RequestContextBase memoryBlob) { if (NetEventSource.IsEnabled) { NetEventSource.Info(this, $"httpContext:${httpContext} memoryBlob {((IntPtr)memoryBlob.RequestBlob)}"); NetEventSource.Associate(this, httpContext); } _httpContext = httpContext; _memoryBlob = memoryBlob; _boundaryType = BoundaryType.None; // Set up some of these now to avoid refcounting on memory blob later. _requestId = memoryBlob.RequestBlob->RequestId; _connectionId = memoryBlob.RequestBlob->ConnectionId; _sslStatus = memoryBlob.RequestBlob->pSslInfo == null ? SslStatus.Insecure : memoryBlob.RequestBlob->pSslInfo->SslClientCertNegotiated == 0 ? SslStatus.NoClientCert : SslStatus.ClientCert; if (memoryBlob.RequestBlob->pRawUrl != null && memoryBlob.RequestBlob->RawUrlLength > 0) { _rawUrl = Marshal.PtrToStringAnsi((IntPtr)memoryBlob.RequestBlob->pRawUrl, memoryBlob.RequestBlob->RawUrlLength); } Interop.HttpApi.HTTP_COOKED_URL cookedUrl = memoryBlob.RequestBlob->CookedUrl; if (cookedUrl.pHost != null && cookedUrl.HostLength > 0) { _cookedUrlHost = Marshal.PtrToStringUni((IntPtr)cookedUrl.pHost, cookedUrl.HostLength / 2); } if (cookedUrl.pAbsPath != null && cookedUrl.AbsPathLength > 0) { _cookedUrlPath = Marshal.PtrToStringUni((IntPtr)cookedUrl.pAbsPath, cookedUrl.AbsPathLength / 2); } if (cookedUrl.pQueryString != null && cookedUrl.QueryStringLength > 0) { _cookedUrlQuery = Marshal.PtrToStringUni((IntPtr)cookedUrl.pQueryString, cookedUrl.QueryStringLength / 2); } _version = new Version(memoryBlob.RequestBlob->Version.MajorVersion, memoryBlob.RequestBlob->Version.MinorVersion); _clientCertState = ListenerClientCertState.NotInitialized; _keepAlive = null; if (NetEventSource.IsEnabled) { NetEventSource.Info(this, $"RequestId:{RequestId} ConnectionId:{_connectionId} RawConnectionId:{memoryBlob.RequestBlob->RawConnectionId} UrlContext:{memoryBlob.RequestBlob->UrlContext} RawUrl:{_rawUrl} Version:{_version} Secure:{_sslStatus}"); NetEventSource.Info(this, $"httpContext:${httpContext} RequestUri:{RequestUri} Content-Length:{ContentLength64} HTTP Method:{HttpMethod}"); } // Log headers if (NetEventSource.IsEnabled) { StringBuilder sb = new StringBuilder("HttpListenerRequest Headers:\n"); for (int i = 0; i < Headers.Count; i++) { sb.Append("\t"); sb.Append(Headers.GetKey(i)); sb.Append(" : "); sb.Append(Headers.Get(i)); sb.Append("\n"); } NetEventSource.Info(this, sb.ToString()); } } internal HttpListenerContext HttpListenerContext => _httpContext; // Note: RequestBuffer may get moved in memory. If you dereference a pointer from inside the RequestBuffer, // you must use 'OriginalBlobAddress' below to adjust the location of the pointer to match the location of // RequestBuffer. internal byte[] RequestBuffer { get { CheckDisposed(); return _memoryBlob.RequestBuffer; } } internal IntPtr OriginalBlobAddress { get { CheckDisposed(); return _memoryBlob.OriginalBlobAddress; } } // Use this to save the blob from dispose if this object was never used (never given to a user) and is about to be // disposed. internal void DetachBlob(RequestContextBase memoryBlob) { if (memoryBlob != null && (object)memoryBlob == (object)_memoryBlob) { _memoryBlob = null; } } // Finalizes ownership of the memory blob. DetachBlob can't be called after this. internal void ReleasePins() { _memoryBlob.ReleasePins(); } internal ulong RequestId => _requestId; public Guid RequestTraceIdentifier { get { Guid guid = new Guid(); *(1 + (ulong*)&guid) = RequestId; return guid; } } public long ContentLength64 { get { if (_boundaryType == BoundaryType.None) { string transferEncodingHeader = GetKnownHeader(HttpRequestHeader.TransferEncoding); if (transferEncodingHeader != null && transferEncodingHeader.Equals("chunked", StringComparison.OrdinalIgnoreCase)) { _boundaryType = BoundaryType.Chunked; _contentLength = -1; } else { _contentLength = 0; _boundaryType = BoundaryType.ContentLength; string length = GetKnownHeader(HttpRequestHeader.ContentLength); if (length != null) { bool success = long.TryParse(length, NumberStyles.None, CultureInfo.InvariantCulture.NumberFormat, out _contentLength); if (!success) { _contentLength = 0; _boundaryType = BoundaryType.Invalid; } } } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_contentLength:{_contentLength} _boundaryType:{_boundaryType}"); return _contentLength; } } public NameValueCollection Headers { get { if (_webHeaders == null) { _webHeaders = Interop.HttpApi.GetHeaders(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"webHeaders:{_webHeaders}"); return _webHeaders; } } public string HttpMethod { get { if (_httpMethod == null) { _httpMethod = Interop.HttpApi.GetVerb(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_httpMethod:{_httpMethod}"); return _httpMethod; } } public Stream InputStream { get { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); if (_requestStream == null) { _requestStream = HasEntityBody ? new HttpRequestStream(HttpListenerContext) : Stream.Null; } if (NetEventSource.IsEnabled) NetEventSource.Exit(this); return _requestStream; } } public bool IsAuthenticated { get { IPrincipal user = HttpListenerContext.User; return user != null && user.Identity != null && user.Identity.IsAuthenticated; } } public bool IsSecureConnection => _sslStatus != SslStatus.Insecure; public string ServiceName { get => _serviceName; internal set => _serviceName = value; } public int ClientCertificateError { get { if (_clientCertState == ListenerClientCertState.NotInitialized) throw new InvalidOperationException(SR.Format(SR.net_listener_mustcall, "GetClientCertificate()/BeginGetClientCertificate()")); else if (_clientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_mustcompletecall, "GetClientCertificate()/BeginGetClientCertificate()")); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"ClientCertificateError:{_clientCertificateError}"); return _clientCertificateError; } } internal X509Certificate2 ClientCertificate { set => _clientCertificate = value; } internal ListenerClientCertState ClientCertState { set => _clientCertState = value; } internal void SetClientCertificateError(int clientCertificateError) { _clientCertificateError = clientCertificateError; } public X509Certificate2 GetClientCertificate() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); try { ProcessClientCertificate(); if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_clientCertificate:{_clientCertificate}"); } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return _clientCertificate; } public IAsyncResult BeginGetClientCertificate(AsyncCallback requestCallback, object state) { if (NetEventSource.IsEnabled) NetEventSource.Info(this); return AsyncProcessClientCertificate(requestCallback, state); } public X509Certificate2 EndGetClientCertificate(IAsyncResult asyncResult) { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); X509Certificate2 clientCertificate = null; try { if (asyncResult == null) { throw new ArgumentNullException(nameof(asyncResult)); } ListenerClientCertAsyncResult clientCertAsyncResult = asyncResult as ListenerClientCertAsyncResult; if (clientCertAsyncResult == null || clientCertAsyncResult.AsyncObject != this) { throw new ArgumentException(SR.net_io_invalidasyncresult, nameof(asyncResult)); } if (clientCertAsyncResult.EndCalled) { throw new InvalidOperationException(SR.Format(SR.net_io_invalidendcall, nameof(EndGetClientCertificate))); } clientCertAsyncResult.EndCalled = true; clientCertificate = clientCertAsyncResult.InternalWaitForCompletion() as X509Certificate2; if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_clientCertificate:{_clientCertificate}"); } finally { if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } return clientCertificate; } public Task<X509Certificate2> GetClientCertificateAsync() { return Task.Factory.FromAsync( (callback, state) => ((HttpListenerRequest)state).BeginGetClientCertificate(callback, state), iar => ((HttpListenerRequest)iar.AsyncState).EndGetClientCertificate(iar), this); } public TransportContext TransportContext => new HttpListenerRequestContext(this); public bool HasEntityBody { get { // accessing the ContentLength property delay creates m_BoundaryType return (ContentLength64 > 0 && _boundaryType == BoundaryType.ContentLength) || _boundaryType == BoundaryType.Chunked || _boundaryType == BoundaryType.Multipart; } } public bool KeepAlive { get { if (!_keepAlive.HasValue) { string header = Headers[HttpKnownHeaderNames.ProxyConnection]; if (string.IsNullOrEmpty(header)) { header = GetKnownHeader(HttpRequestHeader.Connection); } if (string.IsNullOrEmpty(header)) { if (ProtocolVersion >= HttpVersion.Version11) { _keepAlive = true; } else { header = GetKnownHeader(HttpRequestHeader.KeepAlive); _keepAlive = !string.IsNullOrEmpty(header); } } else { header = header.ToLower(CultureInfo.InvariantCulture); _keepAlive = header.IndexOf("close", StringComparison.InvariantCultureIgnoreCase) < 0 || header.IndexOf("keep-alive", StringComparison.InvariantCultureIgnoreCase) >= 0; } } if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_keepAlive=" + _keepAlive); return _keepAlive.Value; } } public IPEndPoint RemoteEndPoint { get { if (_remoteEndPoint == null) { _remoteEndPoint = Interop.HttpApi.GetRemoteEndPoint(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, "_remoteEndPoint" + _remoteEndPoint); return _remoteEndPoint; } } public IPEndPoint LocalEndPoint { get { if (_localEndPoint == null) { _localEndPoint = Interop.HttpApi.GetLocalEndPoint(RequestBuffer, OriginalBlobAddress); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_localEndPoint={_localEndPoint}"); return _localEndPoint; } } //should only be called from httplistenercontext internal void Close() { if (NetEventSource.IsEnabled) NetEventSource.Enter(this); RequestContextBase memoryBlob = _memoryBlob; if (memoryBlob != null) { memoryBlob.Close(); _memoryBlob = null; } _isDisposed = true; if (NetEventSource.IsEnabled) NetEventSource.Exit(this); } private ListenerClientCertAsyncResult AsyncProcessClientCertificate(AsyncCallback requestCallback, object state) { if (_clientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()")); _clientCertState = ListenerClientCertState.InProgress; ListenerClientCertAsyncResult asyncResult = null; //-------------------------------------------------------------------- //When you configure the HTTP.SYS with a flag value 2 //which means require client certificates, when the client makes the //initial SSL connection, server (HTTP.SYS) demands the client certificate // //Some apps may not want to demand the client cert at the beginning //perhaps server the default.htm. In this case the HTTP.SYS is configured //with a flag value other than 2, whcih means that the client certificate is //optional.So initially when SSL is established HTTP.SYS won't ask for client //certificate. This works fine for the default.htm in the case above //However, if the app wants to demand a client certficate at a later time //perhaps showing "YOUR ORDERS" page, then the server wans to demand //Client certs. this will inturn makes HTTP.SYS to do the //SEC_I_RENOGOTIATE through which the client cert demand is made // //THE BUG HERE IS THAT PRIOR TO QFE 4796, we call //GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with //flag = 2. Which means that apps using HTTPListener will not be able to //demand a client cert at a later point // //The fix here is to demand the client cert when the channel is NOT INSECURE //which means whether the client certs are requried at the beginning or not, //if this is an SSL connection, Call HttpReceiveClientCertificate, thus //starting the cert negotiation at that point // //NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get //ERROR_NOT_FOUND - which means the client did not provide the cert //If this is important, the server should respond with 403 forbidden //HTTP.SYS will not do this for you automatically *** //-------------------------------------------------------------------- if (_sslStatus != SslStatus.Insecure) { // at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate) // the cert, though might or might not be there. try to retrieve it // this number is the same that IIS decided to use uint size = CertBoblSize; asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, size); try { while (true) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size); uint bytesReceived = 0; uint statusCode = Interop.HttpApi.HttpReceiveClientCertificate( HttpListenerContext.RequestQueueHandle, _connectionId, (uint)Interop.HttpApi.HTTP_FLAGS.NONE, asyncResult.RequestBlob, size, &bytesReceived, asyncResult.NativeOverlapped); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived); if (statusCode == Interop.HttpApi.ERROR_MORE_DATA) { Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = asyncResult.RequestBlob; size = bytesReceived + pClientCertInfo->CertEncodedSize; asyncResult.Reset(size); continue; } if (statusCode != Interop.HttpApi.ERROR_SUCCESS && statusCode != Interop.HttpApi.ERROR_IO_PENDING) { // someother bad error, possible return values are: // ERROR_INVALID_HANDLE, ERROR_INSUFFICIENT_BUFFER, ERROR_OPERATION_ABORTED // Also ERROR_BAD_DATA if we got it twice or it reported smaller size buffer required. throw new HttpListenerException((int)statusCode); } if (statusCode == Interop.HttpApi.ERROR_SUCCESS && HttpListener.SkipIOCPCallbackOnSuccess) { asyncResult.IOCompleted(statusCode, bytesReceived); } break; } } catch { asyncResult?.InternalCleanup(); throw; } } else { asyncResult = new ListenerClientCertAsyncResult(HttpListenerContext.RequestQueueBoundHandle, this, state, requestCallback, 0); asyncResult.InvokeCallback(); } return asyncResult; } private void ProcessClientCertificate() { if (_clientCertState == ListenerClientCertState.InProgress) throw new InvalidOperationException(SR.Format(SR.net_listener_callinprogress, "GetClientCertificate()/BeginGetClientCertificate()")); _clientCertState = ListenerClientCertState.InProgress; if (NetEventSource.IsEnabled) NetEventSource.Info(this); //-------------------------------------------------------------------- //When you configure the HTTP.SYS with a flag value 2 //which means require client certificates, when the client makes the //initial SSL connection, server (HTTP.SYS) demands the client certificate // //Some apps may not want to demand the client cert at the beginning //perhaps server the default.htm. In this case the HTTP.SYS is configured //with a flag value other than 2, whcih means that the client certificate is //optional.So initially when SSL is established HTTP.SYS won't ask for client //certificate. This works fine for the default.htm in the case above //However, if the app wants to demand a client certficate at a later time //perhaps showing "YOUR ORDERS" page, then the server wans to demand //Client certs. this will inturn makes HTTP.SYS to do the //SEC_I_RENOGOTIATE through which the client cert demand is made // //THE BUG HERE IS THAT PRIOR TO QFE 4796, we call //GET Client certificate native API ONLY WHEN THE HTTP.SYS is configured with //flag = 2. Which means that apps using HTTPListener will not be able to //demand a client cert at a later point // //The fix here is to demand the client cert when the channel is NOT INSECURE //which means whether the client certs are requried at the beginning or not, //if this is an SSL connection, Call HttpReceiveClientCertificate, thus //starting the cert negotiation at that point // //NOTE: WHEN CALLING THE HttpReceiveClientCertificate, you can get //ERROR_NOT_FOUND - which means the client did not provide the cert //If this is important, the server should respond with 403 forbidden //HTTP.SYS will not do this for you automatically *** //-------------------------------------------------------------------- if (_sslStatus != SslStatus.Insecure) { // at this point we know that DefaultFlags has the 2 bit set (Negotiate Client certificate) // the cert, though might or might not be there. try to retrieve it // this number is the same that IIS decided to use uint size = CertBoblSize; while (true) { byte[] clientCertInfoBlob = new byte[checked((int)size)]; fixed (byte* pClientCertInfoBlob = &clientCertInfoBlob[0]) { Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO* pClientCertInfo = (Interop.HttpApi.HTTP_SSL_CLIENT_CERT_INFO*)pClientCertInfoBlob; if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Calling Interop.HttpApi.HttpReceiveClientCertificate size:" + size); uint bytesReceived = 0; uint statusCode = Interop.HttpApi.HttpReceiveClientCertificate( HttpListenerContext.RequestQueueHandle, _connectionId, (uint)Interop.HttpApi.HTTP_FLAGS.NONE, pClientCertInfo, size, &bytesReceived, null); if (NetEventSource.IsEnabled) NetEventSource.Info(this, "Call to Interop.HttpApi.HttpReceiveClientCertificate returned:" + statusCode + " bytesReceived:" + bytesReceived); if (statusCode == Interop.HttpApi.ERROR_MORE_DATA) { size = bytesReceived + pClientCertInfo->CertEncodedSize; continue; } else if (statusCode == Interop.HttpApi.ERROR_SUCCESS) { if (pClientCertInfo != null) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"pClientCertInfo:{(IntPtr)pClientCertInfo} pClientCertInfo->CertFlags: {pClientCertInfo->CertFlags} pClientCertInfo->CertEncodedSize: {pClientCertInfo->CertEncodedSize} pClientCertInfo->pCertEncoded: {(IntPtr)pClientCertInfo->pCertEncoded} pClientCertInfo->Token: {(IntPtr)pClientCertInfo->Token} pClientCertInfo->CertDeniedByMapper: {pClientCertInfo->CertDeniedByMapper}"); if (pClientCertInfo->pCertEncoded != null) { try { byte[] certEncoded = new byte[pClientCertInfo->CertEncodedSize]; Marshal.Copy((IntPtr)pClientCertInfo->pCertEncoded, certEncoded, 0, certEncoded.Length); _clientCertificate = new X509Certificate2(certEncoded); } catch (CryptographicException exception) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"CryptographicException={exception}"); } catch (SecurityException exception) { if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"SecurityException={exception}"); } } _clientCertificateError = (int)pClientCertInfo->CertFlags; } } else { Debug.Assert(statusCode == Interop.HttpApi.ERROR_NOT_FOUND, $"Call to Interop.HttpApi.HttpReceiveClientCertificate() failed with statusCode {statusCode}."); } } break; } } _clientCertState = ListenerClientCertState.Completed; } private Uri RequestUri { get { if (_requestUri == null) { _requestUri = HttpListenerRequestUriBuilder.GetRequestUri( _rawUrl, RequestScheme, _cookedUrlHost, _cookedUrlPath, _cookedUrlQuery); } if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"_requestUri:{_requestUri}"); return _requestUri; } } private string GetKnownHeader(HttpRequestHeader header) { return Interop.HttpApi.GetKnownHeader(RequestBuffer, OriginalBlobAddress, (int)header); } internal ChannelBinding GetChannelBinding() { return HttpListenerContext.Listener.GetChannelBindingFromTls(_connectionId); } internal void CheckDisposed() { if (_isDisposed) { throw new ObjectDisposedException(this.GetType().FullName); } } private bool SupportsWebSockets => WebSocketProtocolComponent.IsSupported; } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 1.0.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Logic { using Azure; using Management; using Rest; using Rest.Azure; using Rest.Azure.OData; using Models; using System.Threading; using System.Threading.Tasks; /// <summary> /// Extension methods for WorkflowTriggersOperations. /// </summary> public static partial class WorkflowTriggersOperationsExtensions { /// <summary> /// Gets a list of workflow triggers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> public static IPage<WorkflowTrigger> List(this IWorkflowTriggersOperations operations, string resourceGroupName, string workflowName, ODataQuery<WorkflowTriggerFilter> odataQuery = default(ODataQuery<WorkflowTriggerFilter>)) { return operations.ListAsync(resourceGroupName, workflowName, odataQuery).GetAwaiter().GetResult(); } /// <summary> /// Gets a list of workflow triggers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='odataQuery'> /// OData parameters to apply to the operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<WorkflowTrigger>> ListAsync(this IWorkflowTriggersOperations operations, string resourceGroupName, string workflowName, ODataQuery<WorkflowTriggerFilter> odataQuery = default(ODataQuery<WorkflowTriggerFilter>), CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, workflowName, odataQuery, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a workflow trigger. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='triggerName'> /// The workflow trigger name. /// </param> public static WorkflowTrigger Get(this IWorkflowTriggersOperations operations, string resourceGroupName, string workflowName, string triggerName) { return operations.GetAsync(resourceGroupName, workflowName, triggerName).GetAwaiter().GetResult(); } /// <summary> /// Gets a workflow trigger. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='triggerName'> /// The workflow trigger name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<WorkflowTrigger> GetAsync(this IWorkflowTriggersOperations operations, string resourceGroupName, string workflowName, string triggerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, workflowName, triggerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Runs a workflow trigger. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='triggerName'> /// The workflow trigger name. /// </param> public static object Run(this IWorkflowTriggersOperations operations, string resourceGroupName, string workflowName, string triggerName) { return operations.RunAsync(resourceGroupName, workflowName, triggerName).GetAwaiter().GetResult(); } /// <summary> /// Runs a workflow trigger. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='triggerName'> /// The workflow trigger name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<object> RunAsync(this IWorkflowTriggersOperations operations, string resourceGroupName, string workflowName, string triggerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.RunWithHttpMessagesAsync(resourceGroupName, workflowName, triggerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets the callback URL for a workflow trigger. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='triggerName'> /// The workflow trigger name. /// </param> public static WorkflowTriggerCallbackUrl ListCallbackUrl(this IWorkflowTriggersOperations operations, string resourceGroupName, string workflowName, string triggerName) { return operations.ListCallbackUrlAsync(resourceGroupName, workflowName, triggerName).GetAwaiter().GetResult(); } /// <summary> /// Gets the callback URL for a workflow trigger. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='resourceGroupName'> /// The resource group name. /// </param> /// <param name='workflowName'> /// The workflow name. /// </param> /// <param name='triggerName'> /// The workflow trigger name. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<WorkflowTriggerCallbackUrl> ListCallbackUrlAsync(this IWorkflowTriggersOperations operations, string resourceGroupName, string workflowName, string triggerName, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListCallbackUrlWithHttpMessagesAsync(resourceGroupName, workflowName, triggerName, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } /// <summary> /// Gets a list of workflow triggers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> public static IPage<WorkflowTrigger> ListNext(this IWorkflowTriggersOperations operations, string nextPageLink) { return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult(); } /// <summary> /// Gets a list of workflow triggers. /// </summary> /// <param name='operations'> /// The operations group for this extension method. /// </param> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> public static async Task<IPage<WorkflowTrigger>> ListNextAsync(this IWorkflowTriggersOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken)) { using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false)) { return _result.Body; } } } }
using System.Diagnostics; namespace Community.CsharpSqlite { using u8 = System.Byte; public partial class Sqlite3 { /* ** 2001 September 15 ** ** The author disclaims copyright to this source code. In place of ** a legal notice, here is a blessing: ** ** May you do good and not evil. ** May you find forgiveness for yourself and forgive others. ** May you share freely, never taking more than you give. ** ************************************************************************* ** An tokenizer for SQL ** ** This file contains C code that implements the sqlite3_complete() API. ** This code used to be part of the tokenizer.c source file. But by ** separating it out, the code will be automatically omitted from ** static links that do not use it. ************************************************************************* ** Included in SQLite3 port to C#-SQLite; 2008 Noah B Hart ** C#-SQLite is an independent reimplementation of the SQLite software library ** ** SQLITE_SOURCE_ID: 2010-03-09 19:31:43 4ae453ea7be69018d8c16eb8dabe05617397dc4d ** ** $Header$ ************************************************************************* */ //#include "sqliteInt.h" #if !SQLITE_OMIT_COMPLETE /* ** This is defined in tokenize.c. We just have to import the definition. */ #if !SQLITE_AMALGAMATION #if SQLITE_ASCII //#define IdChar(C) ((sqlite3CtypeMap[(unsigned char)C]&0x46)!=0) static bool IdChar( u8 C ) { return ( sqlite3CtypeMap[(char)C] & 0x46 ) != 0; } #endif #if SQLITE_EBCDIC //extern const char sqlite3IsEbcdicIdChar[]; //#define IdChar(C) (((c=C)>=0x42 && sqlite3IsEbcdicIdChar[c-0x40])) #endif #endif // * SQLITE_AMALGAMATION */ /* ** Token types used by the sqlite3_complete() routine. See the header ** comments on that procedure for additional information. */ const int tkSEMI = 0; const int tkWS = 1; const int tkOTHER = 2; #if !SQLITE_OMIT_TRIGGER const int tkEXPLAIN = 3; const int tkCREATE = 4; const int tkTEMP = 5; const int tkTRIGGER = 6; const int tkEND = 7; #endif /* ** Return TRUE if the given SQL string ends in a semicolon. ** ** Special handling is require for CREATE TRIGGER statements. ** Whenever the CREATE TRIGGER keywords are seen, the statement ** must end with ";END;". ** ** This implementation uses a state machine with 8 states: ** ** (0) INVALID We have not yet seen a non-whitespace character. ** ** (1) START At the beginning or end of an SQL statement. This routine ** returns 1 if it ends in the START state and 0 if it ends ** in any other state. ** ** (2) NORMAL We are in the middle of statement which ends with a single ** semicolon. ** ** (3) EXPLAIN The keyword EXPLAIN has been seen at the beginning of ** a statement. ** ** (4) CREATE The keyword CREATE has been seen at the beginning of a ** statement, possibly preceeded by EXPLAIN and/or followed by ** TEMP or TEMPORARY ** ** (5) TRIGGER We are in the middle of a trigger definition that must be ** ended by a semicolon, the keyword END, and another semicolon. ** ** (6) SEMI We've seen the first semicolon in the ";END;" that occurs at ** the end of a trigger definition. ** ** (7) END We've seen the ";END" of the ";END;" that occurs at the end ** of a trigger difinition. ** ** Transitions between states above are determined by tokens extracted ** from the input. The following tokens are significant: ** ** (0) tkSEMI A semicolon. ** (1) tkWS Whitespace. ** (2) tkOTHER Any other SQL token. ** (3) tkEXPLAIN The "explain" keyword. ** (4) tkCREATE The "create" keyword. ** (5) tkTEMP The "temp" or "temporary" keyword. ** (6) tkTRIGGER The "trigger" keyword. ** (7) tkEND The "end" keyword. ** ** Whitespace never causes a state transition and is always ignored. ** This means that a SQL string of all whitespace is invalid. ** ** If we compile with SQLITE_OMIT_TRIGGER, all of the computation needed ** to recognize the end of a trigger can be omitted. All we have to do ** is look for a semicolon that is not part of an string or comment. */ static public int sqlite3_complete( string zSql ) { int state = 0; /* Current state, using numbers defined in header comment */ int token; /* Value of the next token */ #if !SQLITE_OMIT_TRIGGER /* A complex statement machine used to detect the end of a CREATE TRIGGER ** statement. This is the normal case. */ u8[][] trans = new u8[][] { /* Token: */ /* State: ** SEMI WS OTHER EXPLAIN CREATE TEMP TRIGGER END */ /* 0 INVALID: */ new u8[]{ 1, 0, 2, 3, 4, 2, 2, 2, }, /* 1 START: */ new u8[]{ 1, 1, 2, 3, 4, 2, 2, 2, }, /* 2 NORMAL: */ new u8[]{ 1, 2, 2, 2, 2, 2, 2, 2, }, /* 3 EXPLAIN: */ new u8[]{ 1, 3, 3, 2, 4, 2, 2, 2, }, /* 4 CREATE: */ new u8[]{ 1, 4, 2, 2, 2, 4, 5, 2, }, /* 5 TRIGGER: */ new u8[]{ 6, 5, 5, 5, 5, 5, 5, 5, }, /* 6 SEMI: */ new u8[]{ 6, 6, 5, 5, 5, 5, 5, 7, }, /* 7 END: */ new u8[]{ 1, 7, 5, 5, 5, 5, 5, 5, }, }; #else /* If triggers are not supported by this compile then the statement machine ** used to detect the end of a statement is much simplier */ u8[][] trans = new u8[][] { /* Token: */ /* State: ** SEMI WS OTHER */ /* 0 INVALID: */new u8[] { 1, 0, 2, }, /* 1 START: */new u8[] { 1, 1, 2, }, /* 2 NORMAL: */new u8[] { 1, 2, 2, }, }; #endif // * SQLITE_OMIT_TRIGGER */ int zIdx = 0; while ( zIdx < zSql.Length ) { switch ( zSql[zIdx] ) { case ';': { /* A semicolon */ token = tkSEMI; break; } case ' ': case '\r': case '\t': case '\n': case '\f': { /* White space is ignored */ token = tkWS; break; } case '/': { /* C-style comments */ if ( zSql[zIdx + 1] != '*' ) { token = tkOTHER; break; } zIdx += 2; while ( zIdx < zSql.Length && zSql[zIdx] != '*' || zIdx < zSql.Length - 1 && zSql[zIdx + 1] != '/' ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; zIdx++; token = tkWS; break; } case '-': { /* SQL-style comments from "--" to end of line */ if ( zSql[zIdx + 1] != '-' ) { token = tkOTHER; break; } while ( zIdx < zSql.Length && zSql[zIdx] != '\n' ) { zIdx++; } if ( zIdx == zSql.Length ) return state == 1 ? 1 : 0;//if( *zSql==0 ) return state==1; token = tkWS; break; } case '[': { /* Microsoft-style identifiers in [...] */ zIdx++; while ( zIdx < zSql.Length && zSql[zIdx] != ']' ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; token = tkOTHER; break; } case '`': /* Grave-accent quoted symbols used by MySQL */ case '"': /* single- and double-quoted strings */ case '\'': { int c = zSql[zIdx]; zIdx++; while ( zIdx < zSql.Length && zSql[zIdx] != c ) { zIdx++; } if ( zIdx == zSql.Length ) return 0; token = tkOTHER; break; } default: { #if SQLITE_EBCDIC unsigned char c; #endif if ( IdChar( (u8)zSql[zIdx] ) ) { /* Keywords and unquoted identifiers */ int nId; for ( nId = 1; ( zIdx + nId ) < zSql.Length && IdChar( (u8)zSql[zIdx + nId] ); nId++ ) { } #if SQLITE_OMIT_TRIGGER token = tkOTHER; #else switch ( zSql[zIdx] ) { case 'c': case 'C': { if ( nId == 6 && sqlite3StrNICmp( zSql, zIdx, "create", 6 ) == 0 ) { token = tkCREATE; } else { token = tkOTHER; } break; } case 't': case 'T': { if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "trigger", 7 ) == 0 ) { token = tkTRIGGER; } else if ( nId == 4 && sqlite3StrNICmp( zSql, zIdx, "temp", 4 ) == 0 ) { token = tkTEMP; } else if ( nId == 9 && sqlite3StrNICmp( zSql, zIdx, "temporary", 9 ) == 0 ) { token = tkTEMP; } else { token = tkOTHER; } break; } case 'e': case 'E': { if ( nId == 3 && sqlite3StrNICmp( zSql, zIdx, "end", 3 ) == 0 ) { token = tkEND; } else #if ! SQLITE_OMIT_EXPLAIN if ( nId == 7 && sqlite3StrNICmp( zSql, zIdx, "explain", 7 ) == 0 ) { token = tkEXPLAIN; } else #endif { token = tkOTHER; } break; } default: { token = tkOTHER; break; } } #endif // * SQLITE_OMIT_TRIGGER */ zIdx += nId - 1; } else { /* Operators and special symbols */ token = tkOTHER; } break; } } state = trans[state][token]; zIdx++; } return ( state == 1 ) ? 1 : 0;//return state==1; } #if ! SQLITE_OMIT_UTF16 /* ** This routine is the same as the sqlite3_complete() routine described ** above, except that the parameter is required to be UTF-16 encoded, not ** UTF-8. */ int sqlite3_complete16(const void *zSql){ sqlite3_value pVal; char const *zSql8; int rc = SQLITE_NOMEM; #if !SQLITE_OMIT_AUTOINIT rc = sqlite3_initialize(); if( rc !=0) return rc; #endif pVal = sqlite3ValueNew(0); sqlite3ValueSetStr(pVal, -1, zSql, SQLITE_UTF16NATIVE, SQLITE_STATIC); zSql8 = sqlite3ValueText(pVal, SQLITE_UTF8); if( zSql8 ){ rc = sqlite3_complete(zSql8); }else{ rc = SQLITE_NOMEM; } sqlite3ValueFree(pVal); return sqlite3ApiExit(0, rc); } #endif // * SQLITE_OMIT_UTF16 */ #endif // * SQLITE_OMIT_COMPLETE */ } }
using System; using System.IO; using UnityEngine; using System.Collections.Generic; namespace uGIF { public class GIFEncoder { public bool useGlobalColorTable = false; public Color32? transparent = null; public int repeat = -1; public int dispose = -1; // disposal code (-1 = use default) public int quality = 10; // default sample interval for quantizer public float FPS { set { delay = Mathf.RoundToInt (100f / value); } } public void AddFrame (Image im) { if (im == null) throw new ArgumentNullException ("im"); if (!started) throw new InvalidOperationException ("Start() must be called before AddFrame()"); if (firstFrame) { width = im.width; height = im.height; } pixels = im.pixels; RemapPixels (); // build color table & map pixels pixels = null; if (firstFrame) { WriteLSD (); // logical screen descriptior WritePalette (); // global color table if (repeat >= 0) { // use NS app extension to indicate reps WriteNetscapeExt (); } } WriteGraphicCtrlExt (); // write graphic control extension WriteImageDesc (); // image descriptor if (!firstFrame && !useGlobalColorTable) { WritePalette (); // local color table } WritePixels (); // encode and write pixel data firstFrame = false; } public void Finish () { if (!started) throw new InvalidOperationException ("Start() must be called before Finish()"); started = false; ms.WriteByte (0x3b); // gif trailer ms.Flush (); // reset for subsequent use transIndex = 0; pixels = null; indexedPixels = null; prevIndexedPixels = null; colorTab = null; firstFrame = true; nq = null; } public void Start (MemoryStream os) { if (os == null) throw new ArgumentNullException ("os"); ms = os; started = true; WriteString ("GIF89a"); // header } void RemapPixels () { int len = pixels.Length; indexedPixels = new byte[len]; if (firstFrame || !useGlobalColorTable) { // initialize quantizer nq = new NeuQuant (pixels, len, quality); colorTab = nq.Process (); // create reduced palette } for (int i = 0; i < len; i++) { int index = nq.Map (pixels [i].r & 0xff, pixels [i].g & 0xff, pixels [i].b & 0xff); usedEntry [index] = true; indexedPixels [i] = (byte)index; if (dispose == 1 && prevIndexedPixels != null) { if (indexedPixels [i] == prevIndexedPixels [i]) { indexedPixels [i] = (byte)transIndex; } else { prevIndexedPixels [i] = (byte)index; } } } colorDepth = 8; palSize = 7; // get closest match to transparent color if specified if (transparent.HasValue) { var c = transparent.Value; //transIndex = FindClosest(transparent); transIndex = nq.Map (c.b, c.g, c.r); } if (dispose == 1 && prevIndexedPixels == null) prevIndexedPixels = indexedPixels.Clone () as byte[]; } int FindClosest (Color32 c) { if (colorTab == null) return -1; int r = c.r; int g = c.g; int b = c.b; int minpos = 0; int dmin = 256 * 256 * 256; int len = colorTab.Length; for (int i = 0; i < len;) { int dr = r - (colorTab [i++] & 0xff); int dg = g - (colorTab [i++] & 0xff); int db = b - (colorTab [i] & 0xff); int d = dr * dr + dg * dg + db * db; int index = i / 3; if (usedEntry [index] && (d < dmin)) { dmin = d; minpos = index; } i++; } return minpos; } void WriteGraphicCtrlExt () { ms.WriteByte (0x21); // extension introducer ms.WriteByte (0xf9); // GCE label ms.WriteByte (4); // data block size int transp, disp; if (transparent == null) { transp = 0; disp = 0; // dispose = no action } else { transp = 1; disp = 2; // force clear if using transparent color } if (dispose >= 0) { disp = dispose & 7; // user override } disp <<= 2; // packed fields ms.WriteByte (Convert.ToByte (0 | // 1:3 reserved disp | // 4:6 disposal 0 | // 7 user input - 0 = none transp)); // 8 transparency flag WriteShort (delay); // delay x 1/100 sec ms.WriteByte (Convert.ToByte (transIndex)); // transparent color index ms.WriteByte (0); // block terminator } void WriteImageDesc () { ms.WriteByte (0x2c); // image separator WriteShort (0); // image position x,y = 0,0 WriteShort (0); WriteShort (width); // image size WriteShort (height); // no LCT - GCT is used for first (or only) frame ms.WriteByte (0); } void WriteLSD () { // logical screen size WriteShort (width); WriteShort (height); // packed fields ms.WriteByte (Convert.ToByte (0x80 | // 1 : global color table flag = 1 (gct used) 0x70 | // 2-4 : color resolution = 7 0x00 | // 5 : gct sort flag = 0 palSize)); // 6-8 : gct size ms.WriteByte (0); // background color index ms.WriteByte (0); // pixel aspect ratio - assume 1:1 } void WriteNetscapeExt () { ms.WriteByte (0x21); // extension introducer ms.WriteByte (0xff); // app extension label ms.WriteByte (11); // block size WriteString ("NETSCAPE" + "2.0"); // app id + auth code ms.WriteByte (3); // sub-block size ms.WriteByte (1); // loop sub-block id WriteShort (repeat); // loop count (extra iterations, 0=repeat forever) ms.WriteByte (0); // block terminator } void WritePalette () { ms.Write (colorTab, 0, colorTab.Length); int n = (3 * 256) - colorTab.Length; for (int i = 0; i < n; i++) { ms.WriteByte (0); } } void WritePixels () { LZWEncoder encoder = new LZWEncoder (width, height, indexedPixels, colorDepth); encoder.Encode (ms); } void WriteShort (int value) { ms.WriteByte (Convert.ToByte (value & 0xff)); ms.WriteByte (Convert.ToByte ((value >> 8) & 0xff)); } void WriteString (String s) { char[] chars = s.ToCharArray (); for (int i = 0; i < chars.Length; i++) { ms.WriteByte ((byte)chars [i]); } } int delay = 0; int width; int height; int transIndex; bool started = false; MemoryStream ms; Color32[] pixels; byte[] indexedPixels; byte[] prevIndexedPixels; int colorDepth; byte[] colorTab; bool[] usedEntry = new bool[256]; // active palette entries int palSize = 7; // color table size (bits-1) bool firstFrame = true; NeuQuant nq; } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using Sparrow.Api.Areas.HelpPage.ModelDescriptions; using Sparrow.Api.Areas.HelpPage.Models; namespace Sparrow.Api.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } if (complexTypeDescription != null) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
/******************************************************************** The Multiverse Platform is made available under the MIT License. Copyright (c) 2012 The Multiverse Foundation 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.Text; namespace Microsoft.MultiverseInterfaceStudio.FrameXml.Serialization { internal class SerializationMap<TKey, TValue> : IDictionary<TKey, TValue> { internal SerializationMap() { this.Reset(); } private bool keysSet = true; private bool valuesSet = true; private IList<KeyValuePair<TKey, TValue>> keyValuePairs; private void Reset() { this.keysSet = true; this.valuesSet = true; this.keyValuePairs = new List<KeyValuePair<TKey, TValue>>(); } private void NewFromValues(TValue[] values) { this.keyValuePairs = new List<KeyValuePair<TKey, TValue>>(values.Length); foreach (TValue value in values) { this.keyValuePairs.Add(new KeyValuePair<TKey, TValue>(default(TKey), value)); } this.keysSet = false; this.valuesSet = true; } private void UpdateWithValues(TValue[] values) { int count = this.keyValuePairs.Count; for (int index = 0; index < count; index++) { this.keyValuePairs[index] = new KeyValuePair<TKey, TValue>(this.keyValuePairs[index].Key, values[index]); } this.keysSet = true; this.valuesSet = true; } private void NewFromKeys(TKey[] keys) { this.keyValuePairs = new List<KeyValuePair<TKey, TValue>>(keys.Length); foreach (TKey key in keys) { this.keyValuePairs.Add(new KeyValuePair<TKey, TValue>(key, default(TValue))); } this.keysSet = true; this.valuesSet = false; } private void UpdateWithKeys(TKey[] keys) { int count = this.keyValuePairs.Count; for (int index = 0; index < count; index++) { this.keyValuePairs[index] = new KeyValuePair<TKey, TValue>(keys[index], this.keyValuePairs[index].Value); } this.keysSet = true; this.valuesSet = true; } private TKey[] GetKeys() { if ((!this.keysSet) || (this.keyValuePairs == null)) { return null; } int count = this.keyValuePairs.Count; TKey[] keys = new TKey[count]; for (int index = 0; index < count; index++) { keys[index] = this.keyValuePairs[index].Key; } return keys; } private TValue[] GetValues() { if ((!this.valuesSet) || (this.keyValuePairs == null)) { return null; } int count = this.keyValuePairs.Count; TValue[] values = new TValue[count]; for (int index = 0; index < count; index++) { values[index] = this.keyValuePairs[index].Value; } return values; } private KeyValuePair<TKey, TValue>? FindByKey(TKey key) { if ((!this.keysSet) || (this.keyValuePairs == null)) { return null; } foreach (KeyValuePair<TKey, TValue> keyValuePair in this.keyValuePairs) { if (keyValuePair.Key.Equals(key)) { return keyValuePair; } } return null; } public TKey[] KeysArray { get { return this.GetKeys(); } set { if (value == null) { this.Reset(); } else if ((!this.keysSet) && this.valuesSet) { this.UpdateWithKeys(value); } else { this.NewFromKeys(value); } } } public TValue[] ValuesArray { get { return this.GetValues(); } set { if (value == null) { this.Reset(); } else if ((!this.valuesSet) && this.keysSet) { this.UpdateWithValues(value); } else { this.NewFromValues(value); } } } #region IDictionary<TKey,TValue> Members void IDictionary<TKey,TValue>.Add(TKey key, TValue value) { this.keyValuePairs.Add(new KeyValuePair<TKey,TValue>(key, value)); } bool IDictionary<TKey,TValue>.ContainsKey(TKey key) { KeyValuePair<TKey, TValue>? keyValuePair = this.FindByKey(key); return keyValuePair.HasValue; } ICollection<TKey> IDictionary<TKey, TValue>.Keys { get { IList<TKey> keys = new List<TKey>(); if ((!this.keysSet) || (this.keyValuePairs == null)) { return keys; } foreach (KeyValuePair<TKey, TValue> keyValuePair in this.keyValuePairs) { keys.Add(keyValuePair.Key); } return keys; } } bool IDictionary<TKey, TValue>.Remove(TKey key) { KeyValuePair<TKey, TValue>? keyValuePair = this.FindByKey(key); bool found = keyValuePair.HasValue; if (found) { this.keyValuePairs.Remove(keyValuePair.Value); } return found; } bool IDictionary<TKey, TValue>.TryGetValue(TKey key, out TValue value) { try { KeyValuePair<TKey, TValue>? keyValuePair = this.FindByKey(key); value = keyValuePair.Value.Value; return true; } catch { value = default(TValue); return false; } } ICollection<TValue> IDictionary<TKey, TValue>.Values { get { TValue[] values = this.ValuesArray; return (values == null) ? new List<TValue>() : new List<TValue>(values); } } TValue IDictionary<TKey, TValue>.this[TKey key] { get { KeyValuePair<TKey, TValue>? keyValuePair = this.FindByKey(key); if (!keyValuePair.HasValue) { throw new KeyNotFoundException("The given key was not present."); } return keyValuePair.Value.Value; } set { KeyValuePair<TKey, TValue>? keyValuePair = this.FindByKey(key); if (keyValuePair.HasValue) { if (!keyValuePair.Value.Value.Equals(value)) { this.keyValuePairs.Remove(keyValuePair.Value); this.keyValuePairs.Add(new KeyValuePair<TKey, TValue>(key, value)); } } else { this.keyValuePairs.Add(new KeyValuePair<TKey, TValue>(key, value)); } } } #endregion #region ICollection<KeyValuePair<TKey,TValue>> Members void ICollection<KeyValuePair<TKey,TValue>>.Add(KeyValuePair<TKey, TValue> item) { this.keyValuePairs.Add(item); } void ICollection<KeyValuePair<TKey, TValue>>.Clear() { this.keyValuePairs.Clear(); } bool ICollection<KeyValuePair<TKey, TValue>>.Contains(KeyValuePair<TKey, TValue> item) { KeyValuePair<TKey, TValue>? keyValuePair = this.FindByKey(item.Key); return ((keyValuePair.HasValue) && (keyValuePair.Value.Value.Equals(item.Value))); } void ICollection<KeyValuePair<TKey, TValue>>.CopyTo(KeyValuePair<TKey, TValue>[] array, int arrayIndex) { this.keyValuePairs.CopyTo(array, arrayIndex); } int ICollection<KeyValuePair<TKey, TValue>>.Count { get { return this.keyValuePairs.Count; } } bool ICollection<KeyValuePair<TKey, TValue>>.IsReadOnly { get { return false; } } bool ICollection<KeyValuePair<TKey, TValue>>.Remove(KeyValuePair<TKey, TValue> item) { KeyValuePair<TKey, TValue>? keyValuePair = this.FindByKey(item.Key); bool found = ((keyValuePair.HasValue) && (keyValuePair.Value.Value.Equals(item.Value))); if (found) { this.keyValuePairs.Remove(keyValuePair.Value); } return found; } #endregion #region IEnumerable<KeyValuePair<TKey,TValue>> Members IEnumerator<KeyValuePair<TKey, TValue>> IEnumerable<KeyValuePair<TKey,TValue>>.GetEnumerator() { return this.keyValuePairs.GetEnumerator(); } #endregion #region IEnumerable Members System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator() { return this.keyValuePairs.GetEnumerator(); } #endregion } }
// // Copyright (C) DataStax Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Cassandra.Tasks; namespace Cassandra.Serialization { /// <summary> /// A class containing methods for Cql types name parsing. /// </summary> internal static class DataTypeParser { private const string ListTypeName = "org.apache.cassandra.db.marshal.ListType"; private const string SetTypeName = "org.apache.cassandra.db.marshal.SetType"; private const string MapTypeName = "org.apache.cassandra.db.marshal.MapType"; public const string UdtTypeName = "org.apache.cassandra.db.marshal.UserType"; private const string TupleTypeName = "org.apache.cassandra.db.marshal.TupleType"; private const string FrozenTypeName = "org.apache.cassandra.db.marshal.FrozenType"; public const string ReversedTypeName = "org.apache.cassandra.db.marshal.ReversedType"; public const string CompositeTypeName = "org.apache.cassandra.db.marshal.CompositeType"; private const string EmptyTypeName = "org.apache.cassandra.db.marshal.EmptyType"; /// <summary> /// Contains the cql literals of certain types /// </summary> private static class CqlNames { public const string Frozen = "frozen"; public const string List = "list"; public const string Set = "set"; public const string Map = "map"; public const string Tuple = "tuple"; public const string Empty = "empty"; } private static readonly Dictionary<string, ColumnTypeCode> SingleFqTypeNames = new Dictionary<string, ColumnTypeCode>() { {"org.apache.cassandra.db.marshal.UTF8Type", ColumnTypeCode.Varchar}, {"org.apache.cassandra.db.marshal.AsciiType", ColumnTypeCode.Ascii}, {"org.apache.cassandra.db.marshal.UUIDType", ColumnTypeCode.Uuid}, {"org.apache.cassandra.db.marshal.TimeUUIDType", ColumnTypeCode.Timeuuid}, {"org.apache.cassandra.db.marshal.Int32Type", ColumnTypeCode.Int}, {"org.apache.cassandra.db.marshal.BytesType", ColumnTypeCode.Blob}, {"org.apache.cassandra.db.marshal.FloatType", ColumnTypeCode.Float}, {"org.apache.cassandra.db.marshal.DoubleType", ColumnTypeCode.Double}, {"org.apache.cassandra.db.marshal.BooleanType", ColumnTypeCode.Boolean}, {"org.apache.cassandra.db.marshal.InetAddressType", ColumnTypeCode.Inet}, {"org.apache.cassandra.db.marshal.SimpleDateType", ColumnTypeCode.Date}, {"org.apache.cassandra.db.marshal.TimeType", ColumnTypeCode.Time}, {"org.apache.cassandra.db.marshal.ShortType", ColumnTypeCode.SmallInt}, {"org.apache.cassandra.db.marshal.ByteType", ColumnTypeCode.TinyInt}, {"org.apache.cassandra.db.marshal.DateType", ColumnTypeCode.Timestamp}, {"org.apache.cassandra.db.marshal.TimestampType", ColumnTypeCode.Timestamp}, {"org.apache.cassandra.db.marshal.LongType", ColumnTypeCode.Bigint}, {"org.apache.cassandra.db.marshal.DecimalType", ColumnTypeCode.Decimal}, {"org.apache.cassandra.db.marshal.IntegerType", ColumnTypeCode.Varint}, {"org.apache.cassandra.db.marshal.CounterColumnType", ColumnTypeCode.Counter} }; private static readonly Dictionary<string, ColumnTypeCode> SingleCqlNames = new Dictionary<string, ColumnTypeCode>() { {"varchar", ColumnTypeCode.Varchar}, {"text", ColumnTypeCode.Text}, {"ascii", ColumnTypeCode.Ascii}, {"uuid", ColumnTypeCode.Uuid}, {"timeuuid", ColumnTypeCode.Timeuuid}, {"int", ColumnTypeCode.Int}, {"blob", ColumnTypeCode.Blob}, {"float", ColumnTypeCode.Float}, {"double", ColumnTypeCode.Double}, {"boolean", ColumnTypeCode.Boolean}, {"inet", ColumnTypeCode.Inet}, {"date", ColumnTypeCode.Date}, {"time", ColumnTypeCode.Time}, {"smallint", ColumnTypeCode.SmallInt}, {"tinyint", ColumnTypeCode.TinyInt}, {"duration", ColumnTypeCode.Duration}, {"timestamp", ColumnTypeCode.Timestamp}, {"bigint", ColumnTypeCode.Bigint}, {"decimal", ColumnTypeCode.Decimal}, {"varint", ColumnTypeCode.Varint}, {"counter", ColumnTypeCode.Counter} }; private static readonly int SingleFqTypeNamesLength = SingleFqTypeNames.Keys.OrderByDescending(k => k.Length).First().Length; /// <summary> /// Parses a given fully-qualified class type name to get the data type information /// </summary> /// <exception cref="ArgumentException" /> internal static ColumnDesc ParseFqTypeName(string typeName, int startIndex = 0, int length = 0) { const StringComparison comparison = StringComparison.Ordinal; var dataType = new ColumnDesc { TypeCode = ColumnTypeCode.Custom }; if (length == 0) { length = typeName.Length; } if (length > ReversedTypeName.Length && typeName.IndexOf(ReversedTypeName, startIndex, comparison) == startIndex) { //move the start index and subtract the length plus parenthesis startIndex += ReversedTypeName.Length + 1; length -= ReversedTypeName.Length + 2; dataType.IsReversed = true; } if (length > FrozenTypeName.Length && typeName.IndexOf(FrozenTypeName, startIndex, comparison) == startIndex) { //Remove the frozen startIndex += FrozenTypeName.Length + 1; length -= FrozenTypeName.Length + 2; dataType.IsFrozen = true; } if (typeName == EmptyTypeName) { // Set it as custom without type info return dataType; } //Quick check if its a single type if (length <= SingleFqTypeNamesLength) { if (startIndex > 0) { typeName = typeName.Substring(startIndex, length); } if (SingleFqTypeNames.TryGetValue(typeName, out ColumnTypeCode typeCode)) { dataType.TypeCode = typeCode; return dataType; } } if (typeName.IndexOf(ListTypeName, startIndex, comparison) == startIndex) { //Its a list //org.apache.cassandra.db.marshal.ListType(innerType) //move cursor across the name and bypass the parenthesis startIndex += ListTypeName.Length + 1; length -= ListTypeName.Length + 2; var innerTypes = ParseParams(typeName, startIndex, length); if (innerTypes.Count != 1) { throw GetTypeException(typeName); } dataType.TypeCode = ColumnTypeCode.List; var subType = ParseFqTypeName(innerTypes[0]); dataType.TypeInfo = new ListColumnInfo() { ValueTypeCode = subType.TypeCode, ValueTypeInfo = subType.TypeInfo }; return dataType; } if (typeName.IndexOf(SetTypeName, startIndex, comparison) == startIndex) { //Its a set //org.apache.cassandra.db.marshal.SetType(innerType) //move cursor across the name and bypass the parenthesis startIndex += SetTypeName.Length + 1; length -= SetTypeName.Length + 2; var innerTypes = ParseParams(typeName, startIndex, length); if (innerTypes.Count != 1) { throw GetTypeException(typeName); } dataType.TypeCode = ColumnTypeCode.Set; var subType = ParseFqTypeName(innerTypes[0]); dataType.TypeInfo = new SetColumnInfo() { KeyTypeCode = subType.TypeCode, KeyTypeInfo = subType.TypeInfo }; return dataType; } if (typeName.IndexOf(MapTypeName, startIndex, comparison) == startIndex) { //org.apache.cassandra.db.marshal.MapType(keyType,valueType) //move cursor across the name and bypass the parenthesis startIndex += MapTypeName.Length + 1; length -= MapTypeName.Length + 2; var innerTypes = ParseParams(typeName, startIndex, length); //It should contain the key and value types if (innerTypes.Count != 2) { throw GetTypeException(typeName); } dataType.TypeCode = ColumnTypeCode.Map; var keyType = ParseFqTypeName(innerTypes[0]); var valueType = ParseFqTypeName(innerTypes[1]); dataType.TypeInfo = new MapColumnInfo() { KeyTypeCode = keyType.TypeCode, KeyTypeInfo = keyType.TypeInfo, ValueTypeCode = valueType.TypeCode, ValueTypeInfo = valueType.TypeInfo }; return dataType; } if (typeName.IndexOf(UdtTypeName, startIndex, comparison) == startIndex) { //move cursor across the name and bypass the parenthesis startIndex += UdtTypeName.Length + 1; length -= UdtTypeName.Length + 2; var udtParams = ParseParams(typeName, startIndex, length); if (udtParams.Count < 2) { //It should contain at least the keyspace, name of the udt and a type throw GetTypeException(typeName); } dataType.TypeCode = ColumnTypeCode.Udt; dataType.Keyspace = udtParams[0]; dataType.Name = HexToUtf8(udtParams[1]); var udtInfo = new UdtColumnInfo(dataType.Keyspace + "." + dataType.Name); for (var i = 2; i < udtParams.Count; i++) { var p = udtParams[i]; var separatorIndex = p.IndexOf(':'); var c = ParseFqTypeName(p, separatorIndex + 1, p.Length - (separatorIndex + 1)); c.Name = HexToUtf8(p.Substring(0, separatorIndex)); udtInfo.Fields.Add(c); } dataType.TypeInfo = udtInfo; return dataType; } if (typeName.IndexOf(TupleTypeName, startIndex, comparison) == startIndex) { //move cursor across the name and bypass the parenthesis startIndex += TupleTypeName.Length + 1; length -= TupleTypeName.Length + 2; var tupleParams = ParseParams(typeName, startIndex, length); if (tupleParams.Count < 1) { //It should contain at least the keyspace, name of the udt and a type throw GetTypeException(typeName); } dataType.TypeCode = ColumnTypeCode.Tuple; var tupleInfo = new TupleColumnInfo(); foreach (var subTypeName in tupleParams) { tupleInfo.Elements.Add(ParseFqTypeName(subTypeName)); } dataType.TypeInfo = tupleInfo; return dataType; } // Assume custom type if cannot be parsed up to this point. dataType.TypeInfo = new CustomColumnInfo(typeName.Substring(startIndex, length)); return dataType; } /// <summary> /// Parses a given CQL type name to get the data type information /// </summary> /// <exception cref="ArgumentException" /> internal static Task<ColumnDesc> ParseTypeName(Func<string, string, Task<UdtColumnInfo>> udtResolver, string keyspace, string typeName, int startIndex = 0, int length = 0) { const StringComparison comparison = StringComparison.Ordinal; var dataType = new ColumnDesc { TypeCode = ColumnTypeCode.Custom }; if (length == 0) { length = typeName.Length; } if (typeName.IndexOf(CqlNames.Frozen, startIndex, comparison) == startIndex) { //Remove the frozen startIndex += CqlNames.Frozen.Length + 1; length -= CqlNames.Frozen.Length + 2; dataType.IsFrozen = true; } if (typeName.IndexOf("'", startIndex, comparison) == startIndex) { // When quoted, this is a custom type. dataType.TypeInfo = new CustomColumnInfo(typeName.Substring(startIndex + 1, length - 2)); return TaskHelper.ToTask(dataType); } if (typeName == CqlNames.Empty) { // A custom without type info return TaskHelper.ToTask(dataType); } if (typeName.IndexOf(CqlNames.List, startIndex, comparison) == startIndex) { //Its a list: move cursor across the name and bypass the angle brackets startIndex += CqlNames.List.Length + 1; length -= CqlNames.List.Length + 2; var innerTypes = ParseParams(typeName, startIndex, length, '<', '>'); if (innerTypes.Count != 1) { return TaskHelper.FromException<ColumnDesc>(GetTypeException(typeName)); } dataType.TypeCode = ColumnTypeCode.List; return ParseTypeName(udtResolver, keyspace, innerTypes[0].Trim()) .ContinueSync(subType => { dataType.TypeInfo = new ListColumnInfo { ValueTypeCode = subType.TypeCode, ValueTypeInfo = subType.TypeInfo }; return dataType; }); } if (typeName.IndexOf(CqlNames.Set, startIndex, comparison) == startIndex) { //Its a set: move cursor across the name and bypass the angle brackets startIndex += CqlNames.Set.Length + 1; length -= CqlNames.Set.Length + 2; var innerTypes = ParseParams(typeName, startIndex, length, '<', '>'); if (innerTypes.Count != 1) { return TaskHelper.FromException<ColumnDesc>(GetTypeException(typeName)); } dataType.TypeCode = ColumnTypeCode.Set; return ParseTypeName(udtResolver, keyspace, innerTypes[0].Trim()) .ContinueSync(subType => { dataType.TypeInfo = new SetColumnInfo { KeyTypeCode = subType.TypeCode, KeyTypeInfo = subType.TypeInfo }; return dataType; }); } if (typeName.IndexOf(CqlNames.Map, startIndex, comparison) == startIndex) { //move cursor across the name and bypass the parenthesis startIndex += CqlNames.Map.Length + 1; length -= CqlNames.Map.Length + 2; var innerTypes = ParseParams(typeName, startIndex, length, '<', '>'); //It should contain the key and value types if (innerTypes.Count != 2) { return TaskHelper.FromException<ColumnDesc>(GetTypeException(typeName)); } dataType.TypeCode = ColumnTypeCode.Map; var keyTypeTask = ParseTypeName(udtResolver, keyspace, innerTypes[0].Trim()); var valueTypeTask = ParseTypeName(udtResolver, keyspace, innerTypes[1].Trim()); return Task.Factory.ContinueWhenAll(new[] { keyTypeTask, valueTypeTask }, tasks => { dataType.TypeInfo = new MapColumnInfo { KeyTypeCode = tasks[0].Result.TypeCode, KeyTypeInfo = tasks[0].Result.TypeInfo, ValueTypeCode = tasks[1].Result.TypeCode, ValueTypeInfo = tasks[1].Result.TypeInfo }; return dataType; }); } if (typeName.IndexOf(CqlNames.Tuple, startIndex, comparison) == startIndex) { //move cursor across the name and bypass the parenthesis startIndex += CqlNames.Tuple.Length + 1; length -= CqlNames.Tuple.Length + 2; var tupleParams = ParseParams(typeName, startIndex, length, '<', '>'); if (tupleParams.Count < 1) { //It should contain at least the keyspace, name of the udt and a type return TaskHelper.FromException<ColumnDesc>(GetTypeException(typeName)); } dataType.TypeCode = ColumnTypeCode.Tuple; var elementTasks = tupleParams .Select(subTypeName => ParseTypeName(udtResolver, keyspace, subTypeName.Trim())) .ToArray(); return Task.Factory.ContinueWhenAll(elementTasks, tasks => { dataType.TypeInfo = new TupleColumnInfo(tasks.Select(t => t.Result)); return dataType; }); } if (startIndex > 0) { typeName = typeName.Substring(startIndex, length); } if (SingleCqlNames.TryGetValue(typeName, out ColumnTypeCode typeCode)) { dataType.TypeCode = typeCode; return TaskHelper.ToTask(dataType); } typeName = typeName.Replace("\"", ""); return udtResolver(keyspace, typeName).ContinueSync(typeInfo => { dataType.TypeCode = ColumnTypeCode.Udt; dataType.TypeInfo = typeInfo ?? throw GetTypeException(typeName); return dataType; }); } /// <summary> /// Converts a hex string to utf8 string /// </summary> private static string HexToUtf8(string hexString) { var bytes = Enumerable.Range(0, hexString.Length) .Where(x => x % 2 == 0) .Select(x => Convert.ToByte(hexString.Substring(x, 2), 16)) .ToArray(); return Encoding.UTF8.GetString(bytes); } /// <summary> /// Parses comma delimited type parameters /// </summary> /// <returns></returns> private static List<string> ParseParams(string value, int startIndex, int length, char open = '(', char close = ')') { var types = new List<string>(); var paramStart = startIndex; var level = 0; for (var i = startIndex; i < startIndex + length; i++) { var c = value[i]; if (c == open) { level++; } if (c == close) { level--; } if (level == 0 && c == ',') { types.Add(value.Substring(paramStart, i - paramStart)); paramStart = i + 1; } } //Add the last one types.Add(value.Substring(paramStart, length - (paramStart - startIndex))); return types; } private static Exception GetTypeException(string typeName) { return new ArgumentException(string.Format("Not a valid type {0}", typeName)); } } }
using Bridge.Test.NUnit; using System; #pragma warning disable 162 // CS0162: Unreachable code detected. Disable because we want to assert that code does not reach unreachable parts namespace Bridge.ClientTest.BasicCSharp { // Tests try and catch blocks [Category(Constants.MODULE_BASIC_CSHARP)] [TestFixture(TestNameFormat = "Try/Catch - {0}")] public class TestTryCatchBlocks { #region Tests // [#84] Does not compile [Test(ExpectedCount = 1)] public static void SimpleTryCatch() { var result = TryCatch("Good"); Assert.AreEqual("Good", result, "TryCatch() executes"); } [Test(ExpectedCount = 3)] public static void CaughtExceptions() { TryCatchWithCaughtException(); Assert.True(true, "Exception catch"); TryCatchWithCaughtTypedException(); Assert.True(true, "Typed exception catch"); var exceptionMessage = TryCatchWithCaughtArgumentException(); Assert.AreEqual("catch me", exceptionMessage, "Typed exception catch with exception message"); } [Test(ExpectedCount = 12)] public static void ThrownExceptions() { // #230 Assert.Throws<Exception>(TryCatchWithNotCaughtTypedException, "A.Typed exception is not Caught"); Assert.True(IsATry, "A. exception not caught - try section called"); Assert.True(!IsACatch, "A. exception not caught - catch section not called"); // #229 Assert.Throws<Exception>(TryCatchWithNotCaughtTypedExceptionAndArgument, "[#229] B. Typed exception is not Caught; and argument"); Assert.True(IsBTry, "[#229] B. exception not caught - try section called"); Assert.True(!IsBCatch, "B. exception not caught - catch section not called"); // #231 Assert.Throws<InvalidOperationException>(TryCatchWithRethrow, "[#231] C. Rethrow"); Assert.True(IsCTry, "C. exception caught and re-thrown - try section called"); Assert.True(IsCCatch, "C. exception caught and re-thrown - catch section called"); Assert.Throws(TryCatchWithRethrowEx, new Func<object, bool>((error) => { return ((Exception)error).Message == "catch me"; }), "D. Rethrow with parameter"); Assert.True(IsDTry, "D. exception caught and re-thrown - try section called"); Assert.True(IsDCatch, "D. exception caught and re-thrown - catch section called"); } [Test(ExpectedCount = 1)] public static void Bridge320() { string exceptionMessage = string.Empty; try { Script.Write("\"someString\".SomeNotExistingMethod();"); } catch (Exception ex) { exceptionMessage = ex.Message; } // var expectedMessage = Utilities.BrowserHelper.IsPhantomJs() // ? "undefined is not a constructor (evaluating '\"someString\".SomeNotExistingMethod()')" // : "\"someString\".SomeNotExistingMethod is not a function"; Assert.True(exceptionMessage.Contains("SomeNotExistingMethod"), "ex.Message works on built-in JavaScript type"); } [Test(ExpectedCount = 1)] public static void Bridge343() { string exceptionMessage = string.Empty; var i = 0; try { var r = 10 / i; } catch (ArgumentException) { } catch (Exception ex) { exceptionMessage = ex.Message; } Assert.True(!string.IsNullOrEmpty(exceptionMessage), "Double catch block with general Exception works"); } #endregion Tests private static string TryCatch(string s) { try { return s; } catch { return string.Empty; } } #region CaughtExceptions private static void TryCatchWithCaughtException() { try { throw new Exception(); } catch { } } private static void TryCatchWithCaughtTypedException() { try { throw new Exception(); } catch (Exception) { } } private static string TryCatchWithCaughtArgumentException() { try { throw new ArgumentException("catch me"); } catch (ArgumentException ex) { return ex.Message; } } #endregion CaughtExceptions #region ThrownExceptions public static bool IsATry { get; set; } public static bool IsACatch { get; set; } private static void TryCatchWithNotCaughtTypedException() { IsATry = false; IsACatch = false; try { IsATry = true; throw new Exception("catch me"); } catch (ArgumentException) { IsATry = true; } IsATry = false; } public static bool IsBTry { get; set; } public static bool IsBCatch { get; set; } private static void TryCatchWithNotCaughtTypedExceptionAndArgument() { IsBTry = false; IsBCatch = false; try { IsBTry = true; throw new Exception("catch me"); IsBTry = false; } catch (InvalidCastException ex) { IsBCatch = true; var s = ex.Message; } IsBTry = false; } public static bool IsCTry { get; set; } public static bool IsCCatch { get; set; } private static void TryCatchWithRethrow() { IsCTry = false; IsCCatch = false; try { IsCTry = true; throw new InvalidOperationException("catch me"); IsCTry = false; } catch (Exception) { IsCCatch = true; throw; } IsCTry = false; } public static bool IsDTry { get; set; } public static bool IsDCatch { get; set; } private static void TryCatchWithRethrowEx() { IsDTry = false; IsDCatch = false; try { IsDTry = true; throw new ArgumentException("catch me"); IsDTry = false; } catch (Exception ex) { IsDCatch = true; throw ex; } IsDTry = false; } #endregion ThrownExceptions } }
using System; using System.Threading; using System.IO; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Storage; using Microsoft.Xna.Framework.Input; using OpenTK; using OpenTK.Audio; using OpenTK.Audio.OpenAL; using System.Diagnostics; namespace MicTest { /// <summary> /// This is the main type for your game /// </summary> public class Game1 : Game { GraphicsDeviceManager graphics; SpriteBatch spriteBatch; #region Audio Out //Create the audio out component AudioOUT.PlayAudio playAudio; #endregion #region Audio In //Create the audio in component AudioIN.Microphone microphone; //Thread used to poll microphone for data Thread MicrophoneCapturedDataThread = null; //Used to export incoming voice data to wav format MemoryStream memoryStreamAudioSaveBuffer = new MemoryStream(); #endregion object lockThis = new object(); public delegate void InvokeDelegate(); public Game1() { graphics = new GraphicsDeviceManager(this); Content.RootDirectory = "Content"; graphics.IsFullScreen = true; } /// <summary> /// Allows the game to perform any initialization it needs to before starting to run. /// This is where it can query for any required services and load any non-graphic /// related content. Calling base.Initialize will enumerate through any components /// and initialize them as well. /// </summary> protected override void Initialize() { // TODO: Add your initialization logic here base.Initialize(); } /// <summary> /// LoadContent will be called once per game and is the place to load /// all of your content. /// </summary> protected override void LoadContent() { // Create a new SpriteBatch, which can be used to draw textures. spriteBatch = new SpriteBatch(GraphicsDevice); //TODO: use this.Content to load your game content here } /// <summary> /// Allows the game to run logic such as updating the world, /// checking for collisions, gathering input, and playing audio. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Update(GameTime gameTime) { // For Mobile devices, this logic will close the Game when the Back button is pressed if (GamePad.GetState(PlayerIndex.One).Buttons.Back == ButtonState.Pressed) { Exit(); } // TODO: Add your update logic here base.Update(gameTime); } /// <summary> /// This is called when the game should draw itself. /// </summary> /// <param name="gameTime">Provides a snapshot of timing values.</param> protected override void Draw(GameTime gameTime) { graphics.GraphicsDevice.Clear(Color.CornflowerBlue); //TODO: Add your drawing code here base.Draw(gameTime); } #region Methods private void InitializeRadioCommunications() { //Can be used to find out all of the capture devices on the system. //IList<string> audioCaptureDevices = AudioCapture.AvailableDevices; //foreach (var item in audioCaptureDevices) //{ // string availableCaptureDevices = item.ToString(); //} //Initialize the Microphone using the default microphone StartMicrophone(audioSamplingRate, microphoneGain, AudioCapture.DefaultDevice, ALFormat.Mono16, numberOfSamples * 2); //Start the process to send out microphone data through the socket StartThreadSendingMicrophoneSoundToSignalPDU(); //Initialize the audio player playAudio = new AudioOUT.PlayAudio(); } /// <summary> /// Used to ensure that all started threads and processes are shut down correctly /// </summary> private void CompleteTest_FormClosing() { if (microphone != null) { microphone.StopRecording(); } if (playAudio != null) { playAudio.StopPlayBack(); playAudio = null; } } /// <summary> /// Intializes the microphone /// </summary> /// <param name="samplingRate">Sample rate of recording</param> /// <param name="microphoneGain">Software gain of microphone</param> /// <param name="deviceCaptureName">System name of device used to capture audio</param> /// <param name="format">Format of recorded data</param> /// <param name="bufferSize">Size of buffer</param> private void StartMicrophone(int samplingRate, float microphoneGain, string deviceCaptureName, ALFormat format, int bufferSize) { microphone = new AudioIN.Microphone(samplingRate, microphoneGain, deviceCaptureName, format, bufferSize); if (microphone.isMicrophoneValid == false) { Debug.WriteLine("ERROR SETTING UP MICROPHONE"); } else { //Start accepting input from the microphone microphone.StartRecording(); } } /// <summary> /// Threaded method that will continue to poll socket for data /// </summary> private void RetreiveDataFromSocket() { byte pdu_type; byte pdu_version; //Continue to process data received until false while (continueReceivingSocketData == true) { //Using queued collection to determine if data has arrived if (receiveBroadCast.pduQueue.Count > 0) { //Process any PDUs (note that a collection was used as multiple pdu's can be sent in one packet) List<byte[]> pdus = pduReceive.ProcessRawPDU(receiveBroadCast.pduQueue.Dequeue(), endianType); int countPDU = 0; int pduCount = pdus.Count; while (countPDU < pduCount && continueReceivingSocketData == true) { byte[] objPdu = pdus[countPDU]; pdu_type = objPdu[PDU_TYPE_POSITION]; //get pdu type pdu_version = objPdu[PDU_VERSION_POSITION];//what version (currently not processing anything but DIS 1998) //Cast as radio pdu, as receive socket method will throw out all other types of PDUs DIS1998net.RadioCommunicationsFamilyPdu pduReceived = pduReceive.ConvertByteArrayToPDU1998(pdu_type, objPdu, endianType) as DIS1998net.RadioCommunicationsFamilyPdu; SiteHostEntityRadioFrequency siteHostEntityRadioFrequency = new SiteHostEntityRadioFrequency(pduReceived.EntityId.Site, pduReceived.EntityId.Application, pduReceived.EntityId.Entity, pduReceived.RadioId, 0); if (pduReceived.EntityId != entityID || (pduReceived.EntityId == entityID && this.isLoopBackAudioEnabled == true)) { //Transmitter which contains the frequency of the signal pdu if (pdu_type == 25) { //Update transmitter packets received UpdatedTransmitterPacketsReceived(); DIS1998net.TransmitterPdu transmitterPDU_Received = (DIS1998net.TransmitterPdu)pduReceived; //Assign the frequency from the Transmitter PDU just received. siteHostEntityRadioFrequency.frequency = transmitterPDU_Received.Frequency; //Remove the frequency from the collection as it will be added back later if it is transmitting siteHostEntityRadioFrequencyCollection.Remove(siteHostEntityRadioFrequencyCollection.Find(i => i.application == siteHostEntityRadioFrequency.application && i.entity == siteHostEntityRadioFrequency.entity && i.radioID == siteHostEntityRadioFrequency.radioID && i.site == siteHostEntityRadioFrequency.site)); //If transmitter is transmitting then add to collection if (transmitterPDU_Received.TransmitStateEnumeration == DIS1998net.TransmitterPdu.TransmitStateEnum.TransmitterOnTransmitting) { siteHostEntityRadioFrequencyCollection.Add(siteHostEntityRadioFrequency); } foreach (FrequencySpeakerLocationTransmitterReceiverActiveClass item in FrequencySpeakerLocationTransmitterReceiverActive) { if (siteHostEntityRadioFrequencyCollection.Exists(i => i.frequency == item.Frequency) == true) { ChangeRadioRecievingColorIndicator(item.UniqueID,true); } else ChangeRadioRecievingColorIndicator(item.UniqueID, false); } } //is it a signal PDU? if (pdu_type == 26) { //Update signal packets received UpdatedSignalPacketsReceived(); DIS1998net.SignalPdu signalPDU = (DIS1998net.SignalPdu)pduReceived; //Does the current signal pdu match one in the transmitter collection if (siteHostEntityRadioFrequencyCollection.Exists(i => i.application == siteHostEntityRadioFrequency.application && i.entity == siteHostEntityRadioFrequency.entity && i.radioID == siteHostEntityRadioFrequency.radioID && i.site == siteHostEntityRadioFrequency.site) == true) { //Retrieve the saved frequency SiteHostEntityRadioFrequency storedSitehostEntityRadioFrequency = siteHostEntityRadioFrequencyCollection.Find(i => i.application == siteHostEntityRadioFrequency.application && i.entity == siteHostEntityRadioFrequency.entity && i.radioID == siteHostEntityRadioFrequency.radioID && i.site == siteHostEntityRadioFrequency.site); //Transmitter was transmitting at this frequency, need to check to see if it is one that we will playback siteHostEntityRadioFrequency.frequency = storedSitehostEntityRadioFrequency.frequency; if (FrequencyOnPlayBackList(storedSitehostEntityRadioFrequency.frequency) == true) { //Need to retrieve the speaker location that matches the frequency FrequencySpeakerLocationTransmitterReceiverActiveClass retrievedFreqSpeakerTransmitterReceiver = FrequencySpeakerLocationTransmitterReceiverActive.Find(i => i.Frequency == storedSitehostEntityRadioFrequency.frequency); //Decode the data, only implemented uLaw byte[] unEncodedData = uLaw.Decode(((DIS1998net.SignalPdu)pduReceived).Data, 0, ((DIS1998net.SignalPdu)pduReceived).Data.Length); //Used to save to a stream //ms.Seek(ms.Length, SeekOrigin.Begin); //ms.Write(encodedData, 0, encodedData.Length); //Play back unencoded data playAudio.PlayBackAudio(unEncodedData, ALFormat.Mono16, (int)signalPDU.SampleRate, retrievedFreqSpeakerTransmitterReceiver.SpeakerLocation); } } } } countPDU++; //Give GUI time to do things Thread.Sleep(1); } } //Give GUI time to do things Thread.Sleep(1); } } #endregion Methods } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Runtime.InteropServices; internal static partial class Interop { internal static partial class libproc { // Constants from sys\param.h private const int MAXCOMLEN = 16; private const int MAXPATHLEN = 1024; // Constants from proc_info.h private const int MAXTHREADNAMESIZE = 64; private const int PROC_PIDLISTFDS = 1; private const int PROC_PIDTASKALLINFO = 2; private const int PROC_PIDTHREADINFO = 5; private const int PROC_PIDLISTTHREADS = 6; private const int PROC_PIDPATHINFO_MAXSIZE = 4 * MAXPATHLEN; private static int PROC_PIDLISTFD_SIZE = Marshal.SizeOf<proc_fdinfo>(); private static int PROC_PIDLISTTHREADS_SIZE = (Marshal.SizeOf<uint>() * 2); // Constants from sys\resource.h private const int RUSAGE_SELF = 0; // Defines from proc_info.h internal enum ThreadRunState { TH_STATE_RUNNING = 1, TH_STATE_STOPPED = 2, TH_STATE_WAITING = 3, TH_STATE_UNINTERRUPTIBLE = 4, TH_STATE_HALTED = 5 } // Defines in proc_info.h [Flags] internal enum ThreadFlags { TH_FLAGS_SWAPPED = 0x1, TH_FLAGS_IDLE = 0x2 } // From proc_info.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct proc_bsdinfo { internal uint pbi_flags; internal uint pbi_status; internal uint pbi_xstatus; internal uint pbi_pid; internal uint pbi_ppid; internal uint pbi_uid; internal uint pbi_gid; internal uint pbi_ruid; internal uint pbi_rgid; internal uint pbi_svuid; internal uint pbi_svgid; internal uint reserved; internal fixed byte pbi_comm[MAXCOMLEN]; internal fixed byte pbi_name[MAXCOMLEN * 2]; internal uint pbi_nfiles; internal uint pbi_pgid; internal uint pbi_pjobc; internal uint e_tdev; internal uint e_tpgid; internal int pbi_nice; internal ulong pbi_start_tvsec; internal ulong pbi_start_tvusec; } // From proc_info.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct proc_taskinfo { internal ulong pti_virtual_size; internal ulong pti_resident_size; internal ulong pti_total_user; internal ulong pti_total_system; internal ulong pti_threads_user; internal ulong pti_threads_system; internal int pti_policy; internal int pti_faults; internal int pti_pageins; internal int pti_cow_faults; internal int pti_messages_sent; internal int pti_messages_received; internal int pti_syscalls_mach; internal int pti_syscalls_unix; internal int pti_csw; internal int pti_threadnum; internal int pti_numrunning; internal int pti_priority; }; // from sys\resource.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct rusage_info_v3 { internal fixed byte ri_uuid[16]; internal ulong ri_user_time; internal ulong ri_system_time; internal ulong ri_pkg_idle_wkups; internal ulong ri_interrupt_wkups; internal ulong ri_pageins; internal ulong ri_wired_size; internal ulong ri_resident_size; internal ulong ri_phys_footprint; internal ulong ri_proc_start_abstime; internal ulong ri_proc_exit_abstime; internal ulong ri_child_user_time; internal ulong ri_child_system_time; internal ulong ri_child_pkg_idle_wkups; internal ulong ri_child_interrupt_wkups; internal ulong ri_child_pageins; internal ulong ri_child_elapsed_abstime; internal ulong ri_diskio_bytesread; internal ulong ri_diskio_byteswritten; internal ulong ri_cpu_time_qos_default; internal ulong ri_cpu_time_qos_maintenance; internal ulong ri_cpu_time_qos_background; internal ulong ri_cpu_time_qos_utility; internal ulong ri_cpu_time_qos_legacy; internal ulong ri_cpu_time_qos_user_initiated; internal ulong ri_cpu_time_qos_user_interactive; internal ulong ri_billed_system_time; internal ulong ri_serviced_system_time; } // From proc_info.h [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Ansi)] internal unsafe struct proc_taskallinfo { internal proc_bsdinfo pbsd; internal proc_taskinfo ptinfo; } // From proc_info.h [StructLayout(LayoutKind.Sequential)] internal unsafe struct proc_threadinfo { internal ulong pth_user_time; internal ulong pth_system_time; internal int pth_cpu_usage; internal int pth_policy; internal int pth_run_state; internal int pth_flags; internal int pth_sleep_time; internal int pth_curpri; internal int pth_priority; internal int pth_maxpriority; internal fixed byte pth_name[MAXTHREADNAMESIZE]; } [StructLayout(LayoutKind.Sequential)] internal struct proc_fdinfo { internal int proc_fd; internal uint proc_fdtype; } /// <summary> /// Queries the OS for the PIDs for all running processes /// </summary> /// <param name="buffer">A pointer to the memory block where the PID array will start</param> /// <param name="buffersize">The length of the block of memory allocated for the PID array</param> /// <returns>Returns the number of elements (PIDs) in the buffer</returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_listallpids( int* pBuffer, int buffersize); /// <summary> /// Queries the OS for the list of all running processes and returns the PID for each /// </summary> /// <returns>Returns a list of PIDs corresponding to all running processes</returns> internal static unsafe int[] proc_listallpids() { // Get the number of processes currently running to know how much data to allocate int numProcesses = proc_listallpids(null, 0); if (numProcesses <= 0) { throw new Win32Exception(SR.CantGetAllPids); } int[] processes; do { // Create a new array for the processes (plus a 10% buffer in case new processes have spawned) // Since we don't know how many threads there could be, if result == size, that could mean two things // 1) We guessed exactly how many processes there are // 2) There are more processes that we didn't get since our buffer is too small // To make sure it isn't #2, when the result == size, increase the buffer and try again processes = new int[(int)(numProcesses * 1.10)]; fixed (int* pBuffer = processes) { numProcesses = proc_listallpids(pBuffer, processes.Length * Marshal.SizeOf<int>()); if (numProcesses <= 0) { throw new Win32Exception(SR.CantGetAllPids); } } } while (numProcesses == processes.Length); // Remove extra elements Array.Resize<int>(ref processes, numProcesses); return processes; } /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDTASKALLINFO</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size proc_taskallinfo) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, proc_taskallinfo* buffer, int bufferSize); /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDTHREADINFO</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size proc_threadinfo) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, proc_threadinfo* buffer, int bufferSize); /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDLISTFDS</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size proc_fdinfo) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, proc_fdinfo* buffer, int bufferSize); /// <summary> /// Gets information about a process given it's PID /// </summary> /// <param name="pid">The PID of the process</param> /// <param name="flavor">Should be PROC_PIDTASKALLINFO</param> /// <param name="arg">Flavor dependent value</param> /// <param name="buffer">A pointer to a block of memory (of size ulong[]) allocated that will contain the data</param> /// <param name="bufferSize">The size of the allocated block above</param> /// <returns> /// The amount of data actually returned. If this size matches the bufferSize parameter then /// the data is valid. If the sizes do not match then the data is invalid, most likely due /// to not having enough permissions to query for the data of that specific process /// </returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidinfo( int pid, int flavor, ulong arg, ulong* buffer, int bufferSize); /// <summary> /// Gets the process information for a given process /// </summary> /// <param name="pid">The PID (process ID) of the process</param> /// <returns> /// Returns a valid proc_taskallinfo struct for valid processes that the caller /// has permission to access; otherwise, returns null /// </returns> internal static unsafe proc_taskallinfo? GetProcessInfoById(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid"); } // Get the process information for the specified pid int size = Marshal.SizeOf<proc_taskallinfo>(); proc_taskallinfo info = default(proc_taskallinfo); int result = proc_pidinfo(pid, PROC_PIDTASKALLINFO, 0, &info, size); return (result == size ? new proc_taskallinfo?(info) : null); } /// <summary> /// Gets the thread information for the given thread /// </summary> /// <param name="thread">The ID of the thread to query for information</param> /// <returns> /// Returns a valid proc_threadinfo struct for valid threads that the caller /// has permissions to access; otherwise, returns null /// </returns> internal static unsafe proc_threadinfo? GetThreadInfoById(int pid, ulong thread) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid"); } // Negative TIDs are invalid if (thread < 0) { throw new ArgumentOutOfRangeException("thread"); } // Get the thread information for the specified thread in the specified process int size = Marshal.SizeOf<proc_threadinfo>(); proc_threadinfo info = default(proc_threadinfo); int result = proc_pidinfo(pid, PROC_PIDTHREADINFO, (ulong)thread, &info, size); return (result == size ? new proc_threadinfo?(info) : null); } internal static unsafe List<KeyValuePair<ulong, proc_threadinfo?>> GetAllThreadsInProcess(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid"); } int result = 0; int size = 20; // start assuming 20 threads is enough ulong[] threadIds = null; var threads = new List<KeyValuePair<ulong, proc_threadinfo?>>(); // We have no way of knowning how many threads the process has (and therefore how big our buffer should be) // so while the return value of the function is the same as our buffer size (meaning it completely filled // our buffer), double our buffer size and try again. This ensures that we don't miss any threads do { threadIds = new ulong[size]; fixed (ulong* pBuffer = threadIds) { result = proc_pidinfo(pid, PROC_PIDLISTTHREADS, 0, pBuffer, Marshal.SizeOf<ulong>() * threadIds.Length); } if (result <= 0) { // If we were unable to access the information, just return the empty list. // This is likely to happen for privileged processes, if the process went away // by the time we tried to query it, etc. return threads; } else { checked { size *= 2; } } } while (result == Marshal.SizeOf<ulong>() * threadIds.Length); Debug.Assert((result % Marshal.SizeOf<ulong>()) == 0); // Loop over each thread and get the thread info int count = (int)(result / Marshal.SizeOf<ulong>()); threads.Capacity = count; for (int i = 0; i < count; i++) { threads.Add(new KeyValuePair<ulong, proc_threadinfo?>(threadIds[i], GetThreadInfoById(pid, threadIds[i]))); } return threads; } /// <summary> /// Retrieves the number of open file descriptors for the specified pid /// </summary> /// <returns>A count of file descriptors for this process.</returns> /// <remarks> /// This function doesn't use the helper since it seems to allow passing NULL /// values in to the buffer and length parameters to get back an estimation /// of how much data we will need to allocate; the other flavors don't seem /// to support doing that. /// </remarks> internal static unsafe int GetFileDescriptorCountForPid(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid"); } // Query for an estimation about the size of the buffer we will need. This seems // to add some padding from the real number, so we don't need to do that int result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, (proc_fdinfo*)null, 0); if (result <= 0) { // If we were unable to access the information, just return the empty list. // This is likely to happen for privileged processes, if the process went away // by the time we tried to query it, etc. return 0; } proc_fdinfo[] fds; int size = (int)(result / Marshal.SizeOf<proc_fdinfo>()) + 1; // Just in case the app opened a ton of handles between when we asked and now, // make sure we retry if our buffer is filled do { fds = new proc_fdinfo[size]; fixed (proc_fdinfo* pFds = fds) { result = proc_pidinfo(pid, PROC_PIDLISTFDS, 0, pFds, Marshal.SizeOf<proc_fdinfo>() * fds.Length); } if (result <= 0) { // If we were unable to access the information, just return the empty list. // This is likely to happen for privileged processes, if the process went away // by the time we tried to query it, etc. return 0; } else { checked { size *= 2; } } } while (result == (fds.Length * Marshal.SizeOf<proc_fdinfo>())); Debug.Assert((result % Marshal.SizeOf<proc_fdinfo>()) == 0); return (int)(result / Marshal.SizeOf<proc_fdinfo>()); } /// <summary> /// Gets the full path to the executable file identified by the specified PID /// </summary> /// <param name="pid">The PID of the running process</param> /// <param name="buffer">A pointer to an allocated block of memory that will be filled with the process path</param> /// <param name="bufferSize">The size of the buffer, should be PROC_PIDPATHINFO_MAXSIZE</param> /// <returns>Returns the length of the path returned on success</returns> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pidpath( int pid, byte* buffer, uint bufferSize); /// <summary> /// Gets the full path to the executable file identified by the specified PID /// </summary> /// <param name="pid">The PID of the running process</param> /// <returns>Returns the full path to the process executable</returns> internal static unsafe string proc_pidpath(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid", SR.NegativePidNotSupported); } // The path is a fixed buffer size, so use that and trim it after int result = 0; byte* pBuffer = stackalloc byte[PROC_PIDPATHINFO_MAXSIZE]; result = proc_pidpath(pid, pBuffer, (uint)(PROC_PIDPATHINFO_MAXSIZE * Marshal.SizeOf<byte>())); if (result <= 0) { throw new Win32Exception(); } // OS X uses UTF-8. The conversion may not strip off all trailing \0s so remove them here return System.Text.Encoding.UTF8.GetString(pBuffer, result); } /// <summary> /// Gets the rusage information for the process identified by the PID /// </summary> /// <param name="pid">The process to retrieve the rusage for</param> /// <param name="flavor">Should be RUSAGE_SELF to specify getting the info for the specified process</param> /// <param name="rusage_info_t">A buffer to be filled with rusage_info data</param> /// <returns>Returns 0 on success; on fail, -1 and errno is set with the error code</returns> /// <remarks> /// We need to use IntPtr here for the buffer since the function signature uses /// void* and not a strong type even though it returns a rusage_info struct /// </remarks> [DllImport(Interop.Libraries.libproc, SetLastError = true)] private static unsafe extern int proc_pid_rusage( int pid, int flavor, rusage_info_v3* rusage_info_t); /// <summary> /// Gets the rusage information for the process identified by the PID /// </summary> /// <param name="pid">The process to retrieve the rusage for</param> /// <returns>On success, returns a struct containing info about the process; on /// failure or when the caller doesn't have permissions to the process, throws a Win32Exception /// </returns> internal static unsafe rusage_info_v3 proc_pid_rusage(int pid) { // Negative PIDs are invalid if (pid < 0) { throw new ArgumentOutOfRangeException("pid", SR.NegativePidNotSupported); } rusage_info_v3 info = new rusage_info_v3(); // Get the PIDs rusage info int result = proc_pid_rusage(pid, RUSAGE_SELF, &info); if (result < 0) { throw new Win32Exception(SR.RUsageFailure); } return info; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Linq; using System.Security.Cryptography; using Microsoft.AspNetCore.Razor.Language.Intermediate; namespace Microsoft.AspNetCore.Razor.Language.CodeGeneration { internal class DefaultDocumentWriter : DocumentWriter { private readonly CodeTarget _codeTarget; private readonly RazorCodeGenerationOptions _options; public DefaultDocumentWriter(CodeTarget codeTarget, RazorCodeGenerationOptions options) { _codeTarget = codeTarget; _options = options; } public override RazorCSharpDocument WriteDocument(RazorCodeDocument codeDocument, DocumentIntermediateNode documentNode) { if (codeDocument == null) { throw new ArgumentNullException(nameof(codeDocument)); } if (documentNode == null) { throw new ArgumentNullException(nameof(documentNode)); } var context = new DefaultCodeRenderingContext( new CodeWriter(Environment.NewLine, _options), _codeTarget.CreateNodeWriter(), codeDocument, documentNode, _options); context.Visitor = new Visitor(_codeTarget, context); context.Visitor.VisitDocument(documentNode); var cSharp = context.CodeWriter.GenerateCode(); var allOrderedDiagnostics = context.Diagnostics.OrderBy(diagnostic => diagnostic.Span.AbsoluteIndex); return new DefaultRazorCSharpDocument( cSharp, _options, allOrderedDiagnostics.ToArray(), context.SourceMappings.ToArray(), context.LinePragmas.ToArray()); } private class Visitor : IntermediateNodeVisitor { private readonly DefaultCodeRenderingContext _context; private readonly CodeTarget _target; public Visitor(CodeTarget target, DefaultCodeRenderingContext context) { _target = target; _context = context; } private DefaultCodeRenderingContext Context => _context; public override void VisitDocument(DocumentIntermediateNode node) { if (!Context.Options.SuppressChecksum) { // See http://msdn.microsoft.com/en-us/library/system.codedom.codechecksumpragma.checksumalgorithmid.aspx // And https://github.com/dotnet/roslyn/blob/614299ff83da9959fa07131c6d0ffbc58873b6ae/src/Compilers/Core/Portable/PEWriter/DebugSourceDocument.cs#L67 // // We only support algorithms that the debugger understands, which is currently SHA1 and SHA256. string algorithmId; var algorithm = Context.SourceDocument.GetChecksumAlgorithm(); if (string.Equals(algorithm, HashAlgorithmName.SHA256.Name, StringComparison.Ordinal)) { algorithmId = "{8829d00f-11b8-4213-878b-770e8597ac16}"; } else if (string.Equals(algorithm, HashAlgorithmName.SHA1.Name, StringComparison.Ordinal) || // In 2.0, we didn't actually expose the name of the algorithm, so it's possible we could get null here. // If that's the case, we just assume SHA1 since that's the only thing we supported in 2.0. algorithm == null) { algorithmId = "{ff1816ec-aa5e-4d10-87f7-6f4963833460}"; } else { var supportedAlgorithms = string.Join(" ", new string[] { HashAlgorithmName.SHA1.Name, HashAlgorithmName.SHA256.Name }); var message = Resources.FormatUnsupportedChecksumAlgorithm( algorithm, supportedAlgorithms, nameof(RazorCodeGenerationOptions) + "." + nameof(RazorCodeGenerationOptions.SuppressChecksum), bool.TrueString); throw new InvalidOperationException(message); } var sourceDocument = Context.SourceDocument; var checksum = Checksum.BytesToString(sourceDocument.GetChecksum()); if (!string.IsNullOrEmpty(checksum)) { Context.CodeWriter .Write("#pragma checksum \"") .Write(sourceDocument.FilePath) .Write("\" \"") .Write(algorithmId) .Write("\" \"") .Write(checksum) .WriteLine("\""); } } Context.CodeWriter .WriteLine("// <auto-generated/>") .WriteLine("#pragma warning disable 1591"); VisitDefault(node); Context.CodeWriter.WriteLine("#pragma warning restore 1591"); } public override void VisitUsingDirective(UsingDirectiveIntermediateNode node) { Context.NodeWriter.WriteUsingDirective(Context, node); } public override void VisitNamespaceDeclaration(NamespaceDeclarationIntermediateNode node) { using (Context.CodeWriter.BuildNamespace(node.Content)) { Context.CodeWriter.WriteLine("#line hidden"); VisitDefault(node); } } public override void VisitClassDeclaration(ClassDeclarationIntermediateNode node) { using (Context.CodeWriter.BuildClassDeclaration( node.Modifiers, node.ClassName, node.BaseType, node.Interfaces, node.TypeParameters.Select(p => (p.ParameterName, p.Constraints)).ToArray())) { VisitDefault(node); } } public override void VisitMethodDeclaration(MethodDeclarationIntermediateNode node) { Context.CodeWriter.WriteLine("#pragma warning disable 1998"); for (var i = 0; i < node.Modifiers.Count; i++) { Context.CodeWriter.Write(node.Modifiers[i]); Context.CodeWriter.Write(" "); } Context.CodeWriter.Write(node.ReturnType); Context.CodeWriter.Write(" "); Context.CodeWriter.Write(node.MethodName); Context.CodeWriter.Write("("); for (var i = 0; i < node.Parameters.Count; i++) { var parameter = node.Parameters[i]; for (var j = 0; j < parameter.Modifiers.Count; j++) { Context.CodeWriter.Write(parameter.Modifiers[j]); Context.CodeWriter.Write(" "); } Context.CodeWriter.Write(parameter.TypeName); Context.CodeWriter.Write(" "); Context.CodeWriter.Write(parameter.ParameterName); if (i < node.Parameters.Count - 1) { Context.CodeWriter.Write(", "); } } Context.CodeWriter.Write(")"); Context.CodeWriter.WriteLine(); using (Context.CodeWriter.BuildScope()) { VisitDefault(node); } Context.CodeWriter.WriteLine("#pragma warning restore 1998"); } public override void VisitFieldDeclaration(FieldDeclarationIntermediateNode node) { Context.CodeWriter.WriteField(node.SuppressWarnings, node.Modifiers, node.FieldType, node.FieldName); } public override void VisitPropertyDeclaration(PropertyDeclarationIntermediateNode node) { Context.CodeWriter.WriteAutoPropertyDeclaration(node.Modifiers, node.PropertyType, node.PropertyName); } public override void VisitExtension(ExtensionIntermediateNode node) { node.WriteNode(_target, Context); } public override void VisitCSharpExpression(CSharpExpressionIntermediateNode node) { Context.NodeWriter.WriteCSharpExpression(Context, node); } public override void VisitCSharpCode(CSharpCodeIntermediateNode node) { Context.NodeWriter.WriteCSharpCode(Context, node); } public override void VisitHtmlAttribute(HtmlAttributeIntermediateNode node) { Context.NodeWriter.WriteHtmlAttribute(Context, node); } public override void VisitHtmlAttributeValue(HtmlAttributeValueIntermediateNode node) { Context.NodeWriter.WriteHtmlAttributeValue(Context, node); } public override void VisitCSharpExpressionAttributeValue(CSharpExpressionAttributeValueIntermediateNode node) { Context.NodeWriter.WriteCSharpExpressionAttributeValue(Context, node); } public override void VisitCSharpCodeAttributeValue(CSharpCodeAttributeValueIntermediateNode node) { Context.NodeWriter.WriteCSharpCodeAttributeValue(Context, node); } public override void VisitHtml(HtmlContentIntermediateNode node) { Context.NodeWriter.WriteHtmlContent(Context, node); } public override void VisitTagHelper(TagHelperIntermediateNode node) { VisitDefault(node); } public override void VisitComponent(ComponentIntermediateNode node) { Context.NodeWriter.WriteComponent(Context, node); } public override void VisitComponentAttribute(ComponentAttributeIntermediateNode node) { Context.NodeWriter.WriteComponentAttribute(Context, node); } public override void VisitComponentChildContent(ComponentChildContentIntermediateNode node) { Context.NodeWriter.WriteComponentChildContent(Context, node); } public override void VisitComponentTypeArgument(ComponentTypeArgumentIntermediateNode node) { Context.NodeWriter.WriteComponentTypeArgument(Context, node); } public override void VisitComponentTypeInferenceMethod(ComponentTypeInferenceMethodIntermediateNode node) { Context.NodeWriter.WriteComponentTypeInferenceMethod(Context, node); } public override void VisitMarkupElement(MarkupElementIntermediateNode node) { Context.NodeWriter.WriteMarkupElement(Context, node); } public override void VisitMarkupBlock(MarkupBlockIntermediateNode node) { Context.NodeWriter.WriteMarkupBlock(Context, node); } public override void VisitReferenceCapture(ReferenceCaptureIntermediateNode node) { Context.NodeWriter.WriteReferenceCapture(Context, node); } public override void VisitSetKey(SetKeyIntermediateNode node) { Context.NodeWriter.WriteSetKey(Context, node); } public override void VisitSplat(SplatIntermediateNode node) { Context.NodeWriter.WriteSplat(Context, node); } public override void VisitDefault(IntermediateNode node) { Context.RenderChildren(node); } } } }
#region -- License Terms -- // // MessagePack for CLI // // Copyright (C) 2010-2018 FUJIWARA, Yusuke // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion -- License Terms -- #if UNITY_5 || UNITY_STANDALONE || UNITY_WEBPLAYER || UNITY_WII || UNITY_IPHONE || UNITY_ANDROID || UNITY_PS3 || UNITY_XBOX360 || UNITY_FLASH || UNITY_BKACKBERRY || UNITY_WINRT #define UNITY #endif using System; using System.Collections; using System.Collections.Generic; #if !UNITY || MSGPACK_UNITY_FULL using System.Collections.Specialized; #endif // !UNITY || MSGPACK_UNITY_FULL using System.Globalization; #if !WINDOWS_PHONE && !NET35 && !UNITY using System.Numerics; #endif // !WINDOWS_PHONE && !NET35 && !UNITY using System.Reflection; using System.Text; using MsgPack.Serialization.DefaultSerializers; namespace MsgPack.Serialization { // This file generated from SerializerRepository.tt T4Template. // Do not modify this file. Edit SerializerRepository.tt instead. // ReSharper disable RedundantNameQualifier partial class SerializerRepository { #if UNITY && DEBUG public #else internal #endif const int DefaultTableCapacity = 58; [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Maintainability", "CA1506:AvoidExcessiveClassCoupling", Justification = "This API is naturally coupled with many types" )] #if UNITY && DEBUG public #else internal #endif static Dictionary<RuntimeTypeHandle, object> InitializeDefaultTable( SerializationContext ownerContext ) { var dictionary = new Dictionary<RuntimeTypeHandle, object>( DefaultTableCapacity ); dictionary.Add( typeof( MessagePackObject ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.MsgPack_MessagePackObjectMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( MessagePackObjectDictionary ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.MsgPack_MessagePackObjectDictionaryMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( MessagePackExtendedTypeObject ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.MsgPack_MessagePackExtendedTypeObjectMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( List<MessagePackObject> ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_Generic_ListOfMessagePackObjectMessagePackSerializer( ownerContext ) ); #if !UNITY dictionary.Add( typeof( Object ).TypeHandle, new MsgPack.Serialization.Polymorphic.PolymorphicSerializerProvider<object>( new MsgPack.Serialization.DefaultSerializers.System_ObjectMessagePackSerializer( ownerContext ) ) ); #else dictionary.Add( typeof( Object ).TypeHandle, new MsgPack.Serialization.Polymorphic.PolymorphicSerializerProvider<object>( ownerContext, new MsgPack.Serialization.DefaultSerializers.System_ObjectMessagePackSerializer( ownerContext ) ) ); #endif // !UNITY dictionary.Add( typeof( String ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_StringMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( StringBuilder ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Text_StringBuilderMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( Char[] ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_CharArrayMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( Byte[] ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_ByteArrayMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( DateTime ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeMessagePackSerializerProvider( ownerContext, false ) ); dictionary.Add( typeof( DateTimeOffset ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeOffsetMessagePackSerializerProvider( ownerContext, false ) ); dictionary.Add( typeof( Timestamp ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.TimestampMessagePackSerializerProvider( ownerContext, false ) ); #if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY dictionary.Add( typeof( System.Runtime.InteropServices.ComTypes.FILETIME ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.FileTimeMessagePackSerializerProvider( ownerContext, false ) ); #endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY // DateTime, DateTimeOffset, and FILETIME must have nullable providers. dictionary.Add( typeof( DateTime? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeMessagePackSerializerProvider( ownerContext, true ) ); dictionary.Add( typeof( DateTimeOffset? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.DateTimeOffsetMessagePackSerializerProvider( ownerContext, true ) ); dictionary.Add( typeof( Timestamp? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.TimestampMessagePackSerializerProvider( ownerContext, true ) ); #if ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY dictionary.Add( typeof( System.Runtime.InteropServices.ComTypes.FILETIME? ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.FileTimeMessagePackSerializerProvider( ownerContext, true ) ); #endif // ( !SILVERLIGHT || WINDOWS_PHONE ) && !UNITY #if !NETFX_CORE && !NETSTANDARD1_1 dictionary.Add( typeof( DBNull ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_DBNullMessagePackSerializer( ownerContext ) ); #endif // !NETFX_CORE && !NETSTANDARD1_1 dictionary.Add( typeof( System.Boolean ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_BooleanMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Byte ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_ByteMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Char ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_CharMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Decimal ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_DecimalMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Double ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_DoubleMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Guid ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_GuidMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Int16 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Int16MessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Int32 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Int32MessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Int64 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Int64MessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.SByte ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_SByteMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Single ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_SingleMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.TimeSpan ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_TimeSpanMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.UInt16 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UInt16MessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.UInt32 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UInt32MessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.UInt64 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UInt64MessagePackSerializer( ownerContext ) ); #if !NETSTANDARD1_1 #if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN dictionary.Add( typeof( System.Security.Cryptography.HashAlgorithmName ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Security_Cryptography_HashAlgorithmNameMessagePackSerializer( ownerContext ) ); #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #endif // !NETSTANDARD1_1 #if !NETSTANDARD1_1 #if !SILVERLIGHT #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Collections.Specialized.BitVector32 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_Specialized_BitVector32MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !SILVERLIGHT #endif // !NETSTANDARD1_1 #if !WINDOWS_PHONE #if !NET35 && !UNITY #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.BigInteger ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_BigIntegerMessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NET35 && !UNITY #endif // !WINDOWS_PHONE #if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Matrix3x2 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_Matrix3x2MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Matrix4x4 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_Matrix4x4MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Plane ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_PlaneMessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Quaternion ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_QuaternionMessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Vector2 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_Vector2MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Vector3 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_Vector3MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT #if !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Vector4 ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_Vector4MessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NETSTANDARD1_1 && !NETSTANDARD1_3 && !XAMARIN #endif // !NET35 && !UNITY && !NET40 && !NET45 && !SILVERLIGHT dictionary.Add( typeof( System.ArraySegment<> ).TypeHandle, typeof( System_ArraySegment_1MessagePackSerializer<> ) ); dictionary.Add( typeof( System.Globalization.CultureInfo ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Globalization_CultureInfoMessagePackSerializer( ownerContext ) ); dictionary.Add( typeof( System.Collections.DictionaryEntry ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_DictionaryEntryMessagePackSerializer( ownerContext ) ); #if !NETSTANDARD1_1 #if !SILVERLIGHT dictionary.Add( typeof( System.Collections.Stack ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_StackMessagePackSerializer( ownerContext ) ); #endif // !SILVERLIGHT #endif // !NETSTANDARD1_1 #if !NETSTANDARD1_1 #if !SILVERLIGHT dictionary.Add( typeof( System.Collections.Queue ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_QueueMessagePackSerializer( ownerContext ) ); #endif // !SILVERLIGHT #endif // !NETSTANDARD1_1 dictionary.Add( typeof( System.Collections.Generic.KeyValuePair<,> ).TypeHandle, typeof( System_Collections_Generic_KeyValuePair_2MessagePackSerializer<, > ) ); #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Collections.Generic.Stack<> ).TypeHandle, typeof( System_Collections_Generic_Stack_1MessagePackSerializer<> ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Collections.Generic.Queue<> ).TypeHandle, typeof( System_Collections_Generic_Queue_1MessagePackSerializer<> ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #if !WINDOWS_PHONE #if !NET35 && !UNITY #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Numerics.Complex ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Numerics_ComplexMessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !NET35 && !UNITY #endif // !WINDOWS_PHONE #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Uri ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_UriMessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Version ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_VersionMessagePackSerializer( ownerContext ) ); #if !NETSTANDARD1_1 #if !SILVERLIGHT #if !UNITY || MSGPACK_UNITY_FULL dictionary.Add( typeof( System.Collections.Specialized.NameValueCollection ).TypeHandle, new MsgPack.Serialization.DefaultSerializers.System_Collections_Specialized_NameValueCollectionMessagePackSerializer( ownerContext ) ); #endif // !UNITY || MSGPACK_UNITY_FULL #endif // !SILVERLIGHT #endif // !NETSTANDARD1_1 return dictionary; } } }
using System; using System.Collections.Generic; using System.Data; using System.Reflection; using NUnit.Framework; using StructureMap.Graph; using StructureMap.Pipeline; using StructureMap.Testing.Widget; using StructureMap.Testing.Widget3; using StructureMap.TypeRules; using Rule=StructureMap.Testing.Widget.Rule; namespace StructureMap.Testing.Graph { [TestFixture] public class PluginFamilyTester { public class TheGateway : IGateway { #region IGateway Members public string WhoAmI { get { throw new NotImplementedException(); } } public void DoSomething() { throw new NotImplementedException(); } #endregion } [Test] public void add_plugins_at_seal_from_the_list_of_types() { var family = new PluginFamily(typeof (IServiceProvider)); family.AddType(typeof (DataTable)); // DataView, DataSet, and DataTable are all IServiceProvider implementations, and should get added // to the PluginFamily var pluggedTypes = new List<Type> { typeof (DataView), typeof (DataSet), typeof (DataTable), GetType() }; family.AddTypes(pluggedTypes); family.PluginCount.ShouldEqual(3); family.FindPlugin(typeof (DataView)).ShouldNotBeNull(); family.FindPlugin(typeof (DataTable)).ShouldNotBeNull(); family.FindPlugin(typeof (DataSet)).ShouldNotBeNull(); } [Test] public void add_type_by_name() { var family = new PluginFamily(typeof (IServiceProvider)); family.AddType(typeof (DataTable), "table"); family.PluginCount.ShouldEqual(1); family.FindPlugin("table").ShouldNotBeNull(); } [Test] public void add_type_does_not_add_if_the_concrete_type_can_not_be_cast_to_plugintype() { var family = new PluginFamily(typeof (IServiceProvider)); family.AddType(GetType()); family.PluginCount.ShouldEqual(0); } [Test] public void add_type_works_if_the_concrete_type_can_be_cast_to_plugintype() { var family = new PluginFamily(typeof (IServiceProvider)); family.AddType(typeof (DataTable)); family.PluginCount.ShouldEqual(1); family.AddType(typeof (DataTable)); family.PluginCount.ShouldEqual(1); } [Test] public void AddAPluggedType() { var family = new PluginFamily(typeof (IWidget)); family.DefaultInstanceKey = "DefaultKey"; family.AddPlugin(typeof (NotPluggableWidget), "NotPlugged"); Assert.AreEqual(1, family.PluginCount, "Plugin Count"); } [Test, ExpectedException(typeof (StructureMapException))] public void AddAWrongType() { var family = new PluginFamily(typeof (IWidget)); family.DefaultInstanceKey = "DefaultKey"; family.AddPlugin(typeof (Rule), "Rule"); } [Test] public void FillDefault_happy_path() { var family = new PluginFamily(typeof (IWidget)); family.Parent = new PluginGraph(); family.AddInstance(new ConfiguredInstance(typeof (ColorWidget)).WithName("Default")); family.DefaultInstanceKey = "Default"; family.FillDefault(new Profile("theProfile")); family.Parent.Log.AssertHasNoError(210); } [Test] public void FillDefault_sad_path_when_the_default_instance_key_does_not_exist_throws_210() { var family = new PluginFamily(typeof (IWidget)); family.Parent = new PluginGraph(); family.DefaultInstanceKey = "something that cannot be found"; family.FillDefault(new Profile("theProfile")); family.Parent.Log.AssertHasError(210); } [Test] public void If_PluginFamily_only_has_one_instance_make_that_the_default() { var family = new PluginFamily(typeof (IGateway)); string theInstanceKey = "the default"; family.AddInstance(new ConfiguredInstance(typeof (TheGateway)).WithName(theInstanceKey)); family.Seal(); Assert.AreEqual(theInstanceKey, family.DefaultInstanceKey); } [Test] public void ImplicitPluginFamilyCreatesASingletonInterceptorWhenIsSingletonIsTrue() { var family = new PluginFamily(typeof (ISingletonRepository)); Assert.IsInstanceOfType(typeof (SingletonLifecycle), family.Lifecycle); var family2 = new PluginFamily(typeof (IDevice)); family2.Lifecycle.ShouldBeNull(); } [Test] public void Log_104_if_instance_cannot_be_added_into_PluginFamily() { TestUtility.AssertErrorIsLogged(104, graph => { var family = new PluginFamily(typeof (IGateway), graph); var instance = new ConfiguredInstance(typeof (ColorRule)); Assert.IsFalse(typeof (Rule).CanBeCastTo(typeof (IGateway))); family.AddInstance(instance); family.Seal(); }); } [Test] public void PluginFamilyImplicitlyConfiguredAsASingletonBehavesAsASingleton() { var pluginGraph = new PluginGraph(); pluginGraph.Scan(x => { x.Assembly(Assembly.GetExecutingAssembly()); }); pluginGraph.Seal(); var manager = new Container(pluginGraph); var repository1 = (ISingletonRepository) manager.GetInstance(typeof (ISingletonRepository)); var repository2 = (ISingletonRepository) manager.GetInstance(typeof (ISingletonRepository)); var repository3 = (ISingletonRepository) manager.GetInstance(typeof (ISingletonRepository)); var repository4 = (ISingletonRepository) manager.GetInstance(typeof (ISingletonRepository)); var repository5 = (ISingletonRepository) manager.GetInstance(typeof (ISingletonRepository)); Assert.AreSame(repository1, repository2); Assert.AreSame(repository1, repository3); Assert.AreSame(repository1, repository4); Assert.AreSame(repository1, repository5); } [Test] public void remove_all_clears_the_defaul_and_removes_all_plugins_instances() { var family = new PluginFamily(typeof (IServiceProvider)); var instance = new SmartInstance<DataSet>(); family.SetDefault(instance); family.AddInstance(new NullInstance()); family.AddType(typeof (DataSet)); family.RemoveAll(); family.DefaultInstanceKey.ShouldBeNull(); family.InstanceCount.ShouldEqual(0); } [Test] public void set_default() { var family = new PluginFamily(typeof (IServiceProvider)); var instance = new SmartInstance<DataSet>(); family.SetDefault(instance); family.GetDefaultInstance().ShouldBeTheSameAs(instance); family.DefaultInstanceKey.ShouldEqual(instance.Name); } [Test] public void set_the_scope_to_session() { var family = new PluginFamily(typeof (IServiceProvider)); family.SetScopeTo(InstanceScope.HttpSession); family.Lifecycle.ShouldBeOfType<HttpSessionLifecycle>(); } [Test] public void set_the_scope_to_session_hybrid() { var family = new PluginFamily(typeof (IServiceProvider)); family.SetScopeTo(InstanceScope.HybridHttpSession); family.Lifecycle.ShouldBeOfType<HybridSessionLifecycle>(); } [Test] public void SetScopeToHttpContext() { var family = new PluginFamily(typeof (IServiceProvider)); family.Lifecycle.ShouldBeNull(); family.SetScopeTo(InstanceScope.HttpContext); Assert.IsInstanceOfType(typeof (HttpContextLifecycle), family.Lifecycle); } [Test] public void SetScopeToHybrid() { var family = new PluginFamily(typeof (IServiceProvider)); family.SetScopeTo(InstanceScope.Hybrid); Assert.IsInstanceOfType(typeof (HybridLifecycle), family.Lifecycle); } [Test] public void SetScopeToSingleton() { var family = new PluginFamily(typeof (IServiceProvider)); family.SetScopeTo(InstanceScope.Singleton); Assert.IsInstanceOfType(typeof (SingletonLifecycle), family.Lifecycle); } [Test] public void SetScopeToThreadLocal() { var family = new PluginFamily(typeof (IServiceProvider)); family.SetScopeTo(InstanceScope.ThreadLocal); Assert.IsInstanceOfType(typeof (ThreadLocalStorageLifecycle), family.Lifecycle); } [Test] public void Lifecycle_is_imported_from_the_source_when_merging_PluginFamilies() { var source = new PluginFamily(typeof(GenericType<>)); source.SetScopeTo(InstanceScope.Unique); var importInto = new PluginFamily(typeof(GenericType<>)); importInto.ImportFrom(source); importInto.Lifecycle.ShouldBeOfType(source.Lifecycle.GetType()); } } /// <summary> /// Specifying the default instance is "Default" and marking the PluginFamily /// as an injected Singleton /// </summary> [PluginFamily("Default", IsSingleton = true)] public interface ISingletonRepository { } [Pluggable("Default")] public class SingletonRepositoryWithAttribute : ISingletonRepository { private readonly Guid _id = Guid.NewGuid(); public Guid Id { get { return _id; } } } public class SingletonRepositoryWithoutPluginAttribute : ISingletonRepository { } public class RandomClass { } [PluginFamily(IsSingleton = false)] public interface IDevice { } public class GenericType<T> { } }
/* * * (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.Mail { #region usings using System; using System.Text; using MIME; #endregion /// <summary> /// This class represent generic <b>mailbox-list</b> header fields. For example: From header. /// </summary> /// <example> /// <code> /// RFC 5322. /// header = "FiledName:" mailbox-list CRLF /// mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list /// </code> /// </example> public class Mail_h_MailboxList : MIME_h { #region Members private readonly string m_Name; private readonly Mail_t_MailboxList m_pAddresses; private string m_ParseValue; #endregion #region Properties /// <summary> /// Gets if this header field is modified since it has loaded. /// </summary> /// <remarks>All new added header fields has <b>IsModified = true</b>.</remarks> /// <exception cref="ObjectDisposedException">Is riased when this class is disposed and this property is accessed.</exception> public override bool IsModified { get { return m_pAddresses.IsModified; } } /// <summary> /// Gets header field name. For example "From". /// </summary> public override string Name { get { return m_Name; } } /// <summary> /// Gets addresses collection. /// </summary> public Mail_t_MailboxList Addresses { get { return m_pAddresses; } } #endregion #region Constructor /// <summary> /// Default constructor. /// </summary> /// <param name="filedName">Header field name. For example: "To".</param> /// <param name="values">Addresses collection.</param> /// <exception cref="ArgumentNullException">Is raised when <b>filedName</b> or <b>values</b> is null reference.</exception> /// <exception cref="ArgumentException">Is raised when any of the arguments has invalid value.</exception> public Mail_h_MailboxList(string filedName, Mail_t_MailboxList values) { if (filedName == null) { throw new ArgumentNullException("filedName"); } if (filedName == string.Empty) { throw new ArgumentException("Argument 'filedName' value must be specified."); } if (values == null) { throw new ArgumentNullException("values"); } m_Name = filedName; m_pAddresses = values; } #endregion #region Methods /// <summary> /// Parses header field from the specified value. /// </summary> /// <param name="value">Header field value. Header field name must be included. For example: 'Content-Type: text/plain'.</param> /// <returns>Returns parsed header field.</returns> /// <exception cref="ArgumentNullException">Is raised when <b>value</b> is null reference.</exception> /// <exception cref="ParseException">Is raised when header field parsing errors.</exception> public static Mail_h_MailboxList Parse(string value) { if (value == null) { throw new ArgumentNullException("value"); } string[] name_value = value.Split(new[] {':'}, 2); if (name_value.Length != 2) { throw new ParseException("Invalid header field value '" + value + "'."); } /* RFC 5322 3.4. mailbox = name-addr / addr-spec name-addr = [display-name] angle-addr angle-addr = [CFWS] "<" addr-spec ">" [CFWS] / obs-angle-addr display-name = phrase mailbox-list = (mailbox *("," mailbox)) / obs-mbox-list */ MIME_Reader r = new MIME_Reader(MIME_Utils.UnfoldHeader(name_value.Length == 2 ? name_value[1].TrimStart() : "")); Mail_h_MailboxList retVal = new Mail_h_MailboxList(name_value[0], new Mail_t_MailboxList()); while (true) { string word = r.QuotedReadToDelimiter(new[] {',', '<', ':'}); // We processed all data. if (word == null && r.Available == 0) { break; } // name-addr else if (r.Peek(true) == '<') { retVal.m_pAddresses.Add( new Mail_t_Mailbox( word != null ? MIME_Encoding_EncodedWord.DecodeAll(word) : null, r.ReadParenthesized())); } // addr-spec else { retVal.m_pAddresses.Add(new Mail_t_Mailbox(null, word)); } // We have more addresses. if (r.Peek(true) == ',') { r.Char(false); } } retVal.m_ParseValue = value; retVal.m_pAddresses.AcceptChanges(); return retVal; } /// <summary> /// Returns header field as string. /// </summary> /// <param name="wordEncoder">8-bit words ecnoder. Value null means that words are not encoded.</param> /// <param name="parmetersCharset">Charset to use to encode 8-bit characters. Value null means parameters not encoded.</param> /// <returns>Returns header field as string.</returns> public override string ToString(MIME_Encoding_EncodedWord wordEncoder, Encoding parmetersCharset) { if (IsModified) { StringBuilder retVal = new StringBuilder(); retVal.Append(Name + ": "); for (int i = 0; i < m_pAddresses.Count; i++) { if (i > 0) { retVal.Append("\t"); } // Don't add ',' for last item. if (i == (m_pAddresses.Count - 1)) { retVal.Append(m_pAddresses[i].ToString(wordEncoder) + "\r\n"); } else { retVal.Append(m_pAddresses[i].ToString(wordEncoder) + ",\r\n"); } } return retVal.ToString(); } else { return m_ParseValue; } } #endregion } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Management.Automation; namespace Microsoft.PowerShell.Commands { /// <summary> /// </summary> [Cmdlet("Sort", "Object", HelpUri = "https://go.microsoft.com/fwlink/?LinkID=2097038", DefaultParameterSetName = "Default", RemotingCapability = RemotingCapability.None)] public sealed class SortObjectCommand : OrderObjectBase { #region Command Line Switches /// <summary> /// Gets or sets a value indicating whether a stable sort is required. /// </summary> /// <value></value> /// <remarks> /// Items that are duplicates according to the sort algorithm will appear /// in the same relative order in a stable sort. /// </remarks> [Parameter(ParameterSetName = "Default")] public SwitchParameter Stable { get; set; } /// <summary> /// Gets or sets a value indicating whether the sort order is descending. /// </summary> [Parameter] public SwitchParameter Descending { get { return DescendingOrder; } set { DescendingOrder = value; } } /// <summary> /// Gets or sets a value indicating whether the sort filters out any duplicate objects. /// </summary> /// <value></value> [Parameter] public SwitchParameter Unique { get; set; } #endregion /// <summary> /// Gets or sets the number of items to return in a Top N sort. /// </summary> [Parameter(ParameterSetName = "Top", Mandatory = true)] [ValidateRange(1, int.MaxValue)] public int Top { get; set; } /// <summary> /// Gets or sets the number of items to return in a Bottom N sort. /// </summary> [Parameter(ParameterSetName = "Bottom", Mandatory = true)] [ValidateRange(1, int.MaxValue)] public int Bottom { get; set; } /// <summary> /// Moves unique entries to the front of the list. /// </summary> private int MoveUniqueEntriesToFront(List<OrderByPropertyEntry> sortedData, OrderByPropertyComparer comparer) { // If we have sorted data then we know we have at least one unique item int uniqueCount = sortedData.Count > 0 ? 1 : 0; // Move the first of each unique entry to the front of the list for (int uniqueItemIndex = 0, nextUniqueItemIndex = 1; uniqueItemIndex < sortedData.Count && uniqueCount != Top; uniqueItemIndex++, nextUniqueItemIndex++) { // Identify the index of the next unique item while (nextUniqueItemIndex < sortedData.Count && comparer.Compare(sortedData[uniqueItemIndex], sortedData[nextUniqueItemIndex]) == 0) { nextUniqueItemIndex++; } // If there are no more unique items, break if (nextUniqueItemIndex == sortedData.Count) { break; } // Move the next unique item forward and increment the unique item counter sortedData[uniqueItemIndex + 1] = sortedData[nextUniqueItemIndex]; uniqueCount++; } return uniqueCount; } /// <summary> /// Sort unsorted OrderByPropertyEntry data using a full sort. /// </summary> private int FullSort(List<OrderByPropertyEntry> dataToSort, OrderByPropertyComparer comparer) { // Track how many items in the list are sorted int sortedItemCount = dataToSort.Count; // Future: It may be worth comparing List.Sort with SortedSet when handling unique // records in case SortedSet is faster (SortedSet was not an option in earlier // versions of PowerShell). dataToSort.Sort(comparer); if (Unique) { // Move unique entries to the front of the list (this is significantly faster // than removing them) sortedItemCount = MoveUniqueEntriesToFront(dataToSort, comparer); } return sortedItemCount; } /// <summary> /// Sort unsorted OrderByPropertyEntry data using an indexed min-/max-heap sort. /// </summary> private int Heapify(List<OrderByPropertyEntry> dataToSort, OrderByPropertyComparer orderByPropertyComparer) { // Instantiate the Heapify comparer, which takes index into account for sort stability var comparer = new IndexedOrderByPropertyComparer(orderByPropertyComparer); // Identify how many items will be in the heap and the current number of items int heapCount = 0; int heapCapacity = Stable ? int.MaxValue : Top > 0 ? Top : Bottom; // Identify the comparator (the value all comparisons will be made against based on whether we're // doing a Top N or Bottom N sort) // Note: All comparison results in the loop below are performed related to the value of the // comparator. OrderByPropertyComparer.Compare will return -1 to indicate that the lhs is smaller // if an ascending sort is being executed, or -1 to indicate that the lhs is larger if a descending // sort is being executed. The comparator will be -1 if we're executing a Top N sort, or 1 if we're // executing a Bottom N sort. These two pairs of states allow us to perform the proper comparison // regardless of whether we're executing an ascending or descending Top N or Bottom N sort. This // allows us to build a min-heap or max-heap for each of these sorts with the exact same logic. // Min-heap: used for faster processing of a top N descending sort and a bottom N ascending sort // Max-heap: used for faster processing of a top N ascending sort and a bottom N descending sort int comparator = Top > 0 ? -1 : 1; // For unique sorts, use a sorted set to avoid adding unique items to the heap SortedSet<OrderByPropertyEntry> uniqueSet = Unique ? new SortedSet<OrderByPropertyEntry>(orderByPropertyComparer) : null; // Tracking the index is necessary so that unsortable items can be output at the end, in the order // in which they were received. for (int dataIndex = 0, discardedDuplicates = 0; dataIndex < dataToSort.Count - discardedDuplicates; dataIndex++) { // Min-heap: if the heap is full and the root item is larger than the entry, discard the entry // Max-heap: if the heap is full and the root item is smaller than the entry, discard the entry if (heapCount == heapCapacity && comparer.Compare(dataToSort[0], dataToSort[dataIndex]) == comparator) { continue; } // If we're doing a unique sort and the entry is not unique, discard the duplicate entry if (Unique && !uniqueSet.Add(dataToSort[dataIndex])) { discardedDuplicates++; if (dataIndex != dataToSort.Count - discardedDuplicates) { // When discarding duplicates, replace them with an item at the end of the list and // adjust our counter so that we check the item we just swapped in next dataToSort[dataIndex] = dataToSort[dataToSort.Count - discardedDuplicates]; dataIndex--; } continue; } // Add the current item to the heap and bubble it up into the correct position int childIndex = dataIndex; while (childIndex > 0) { int parentIndex = ((childIndex > (heapCapacity - 1) ? heapCapacity : childIndex) - 1) >> 1; // Min-heap: if the child item is larger than its parent, break // Max-heap: if the child item is smaller than its parent, break if (comparer.Compare(dataToSort[childIndex], dataToSort[parentIndex]) == comparator) { break; } var temp = dataToSort[parentIndex]; dataToSort[parentIndex] = dataToSort[childIndex]; dataToSort[childIndex] = temp; childIndex = parentIndex; } heapCount++; // If the heap size is too large, remove the root and rearrange the heap if (heapCount > heapCapacity) { // Move the last item to the root and reset the heap count (this effectively removes the last item) dataToSort[0] = dataToSort[dataIndex]; heapCount = heapCapacity; // Bubble the root item down into the correct position int parentIndex = 0; int parentItemCount = heapCapacity >> 1; while (parentIndex < parentItemCount) { // Min-heap: use the smaller of the two children in the comparison // Max-heap: use the larger of the two children in the comparison int leftChildIndex = (parentIndex << 1) + 1; int rightChildIndex = leftChildIndex + 1; childIndex = rightChildIndex == heapCapacity || comparer.Compare(dataToSort[leftChildIndex], dataToSort[rightChildIndex]) != comparator ? leftChildIndex : rightChildIndex; // Min-heap: if the smallest child is larger than or equal to its parent, break // Max-heap: if the largest child is smaller than or equal to its parent, break int childComparisonResult = comparer.Compare(dataToSort[childIndex], dataToSort[parentIndex]); if (childComparisonResult == 0 || childComparisonResult == comparator) { break; } var temp = dataToSort[childIndex]; dataToSort[childIndex] = dataToSort[parentIndex]; dataToSort[parentIndex] = temp; parentIndex = childIndex; } } } dataToSort.Sort(0, heapCount, comparer); return heapCount; } /// <summary> /// </summary> protected override void EndProcessing() { OrderByProperty orderByProperty = new( this, InputObjects, Property, !Descending, ConvertedCulture, CaseSensitive); var dataToProcess = orderByProperty.OrderMatrix; var comparer = orderByProperty.Comparer; if (comparer == null || dataToProcess == null || dataToProcess.Count == 0) { return; } // Track the number of items that will be output from the data once it is sorted int sortedItemCount = dataToProcess.Count; // If -Stable, -Top & -Bottom were not used, invoke an in-place full sort if (!Stable && Top == 0 && Bottom == 0) { sortedItemCount = FullSort(dataToProcess, comparer); } // Otherwise, use an indexed min-/max-heap to perform an in-place heap sort (heap // sorts are inheritantly stable, meaning they will preserve the respective order // of duplicate objects as they are sorted on the heap) else { sortedItemCount = Heapify(dataToProcess, comparer); } // Write out the portion of the processed data that was sorted for (int index = 0; index < sortedItemCount; index++) { WriteObject(dataToProcess[index].inputObject); } } } }
/* Copyright 2014 Google Inc. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using UnityEngine; using System; using System.Collections; using System.Collections.Generic; using System.Globalization; /* GoogleAnalyticsMPV3 handles building hits using the Measurement Protocol. Developers should call the methods in GoogleAnalyticsV3, which will call the appropriate methods in this class if the application is built for platforms other than Android and iOS. */ public class GoogleAnalyticsMPV3 { #if UNITY_ANDROID && !UNITY_EDITOR #elif UNITY_IPHONE && !UNITY_EDITOR #else private string trackingCode; private string bundleIdentifier; private string appName; private string appVersion; private GoogleAnalyticsV3.DebugMode logLevel; private bool anonymizeIP; private bool dryRun; private bool optOut; private int sessionTimeout; private string screenRes; private string clientId; private string url; private float timeStarted; private Dictionary<Field, object> trackerValues = new Dictionary<Field, object>(); private bool startSessionOnNextHit = false; private bool endSessionOnNextHit = false; private bool trackingCodeSet = true; public void InitializeTracker() { if(String.IsNullOrEmpty(trackingCode)){ Debug.Log("No tracking code set for 'Other' platforms - hits will not be set"); trackingCodeSet = false; return; } if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.INFO)) { Debug.Log("Platform is not Android or iOS - " + "hits will be sent using measurement protocol."); } screenRes = Screen.width + "x" + Screen.height; clientId = SystemInfo.deviceUniqueIdentifier; string language = Application.systemLanguage.ToString(); optOut = false; #if !UNITY_WP8 CultureInfo[] cultureInfos = CultureInfo.GetCultures(CultureTypes.AllCultures); foreach (CultureInfo info in cultureInfos) { if (info.EnglishName == Application.systemLanguage.ToString()) { language = info.Name; } } #endif try { url = "https://www.google-analytics.com/collect?v=1" + AddRequiredMPParameter(Fields.LANGUAGE, language) + AddRequiredMPParameter(Fields.SCREEN_RESOLUTION, screenRes) + AddRequiredMPParameter(Fields.APP_NAME, appName) + AddRequiredMPParameter(Fields.TRACKING_ID, trackingCode) + AddRequiredMPParameter(Fields.APP_ID, bundleIdentifier) + AddRequiredMPParameter(Fields.CLIENT_ID, clientId) + AddRequiredMPParameter(Fields.APP_VERSION, appVersion); if(anonymizeIP){ url += AddOptionalMPParameter(Fields.ANONYMIZE_IP, 1); } if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log("Base URL for hits: " + url); } } catch (Exception) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.Log("Error building url."); } } } public void SetTrackerVal(Field field, object value) { trackerValues[field] = value; } private string AddTrackerVals() { if(!trackingCodeSet){ return ""; } string vals = ""; foreach (KeyValuePair<Field, object> pair in trackerValues){ vals += AddOptionalMPParameter(pair.Key, pair.Value); } return vals; } internal void StartSession() { startSessionOnNextHit = true; } internal void StopSession() { endSessionOnNextHit = true; } private void SendGaHitWithMeasurementProtocol(string url) { if (optOut) { return; } if (String.IsNullOrEmpty(url)) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.Log("No tracking code set for 'Other' platforms - hit will not be sent."); } return; } if (dryRun) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log("Dry run or opt out enabled - hits will not be sent."); } return; } if (startSessionOnNextHit) { url += AddOptionalMPParameter(Fields.SESSION_CONTROL, "start"); startSessionOnNextHit = false; } else if (endSessionOnNextHit) { url += AddOptionalMPParameter(Fields.SESSION_CONTROL, "end"); endSessionOnNextHit = false; } // Add random z to avoid caching string newUrl = url + "&z=" + UnityEngine.Random.Range(0, 500); if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log(newUrl); } GoogleAnalyticsV3.getInstance().StartCoroutine(this.HandleWWW(new WWW(newUrl))); } /* Make request using yield and coroutine to prevent lock up waiting on request to return. */ public IEnumerator HandleWWW(WWW request) { while (!request.isDone) { yield return request; if (request.responseHeaders.ContainsKey("STATUS")) { if (request.responseHeaders["STATUS"].Contains("200 OK")) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.INFO)) { Debug.Log("Successfully sent Google Analytics hit."); } } else { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.LogWarning("Google Analytics hit request rejected with " + "status code " + request.responseHeaders["STATUS"]); } } } else { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.LogWarning("Google Analytics hit request failed with error " + request.error); } } } } private string AddRequiredMPParameter(Field parameter, object value) { if(!trackingCodeSet){ return ""; } else if (value == null) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.LogWarning("Value was null for required parameter " + parameter + ". Hit cannot be sent"); } throw new ArgumentNullException(); } else { return parameter + "=" + WWW.EscapeURL(value.ToString()); } } private string AddRequiredMPParameter(Field parameter, string value) { if(!trackingCodeSet){ return ""; } else if (value == null) { if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.WARNING)) { Debug.LogWarning("Value was null for required parameter " + parameter + ". Hit cannot be sent"); } throw new ArgumentNullException(); } else { return parameter + "=" + WWW.EscapeURL(value); } } private string AddOptionalMPParameter(Field parameter, object value) { if (value == null || !trackingCodeSet) { return ""; } else { return parameter + "=" + WWW.EscapeURL(value.ToString()); } } private string AddOptionalMPParameter(Field parameter, string value) { if (String.IsNullOrEmpty(value) || !trackingCodeSet) { return ""; } else { return parameter + "=" + WWW.EscapeURL(value); } } private string AddCustomVariables<T>(HitBuilder<T> builder) { if(!trackingCodeSet){ return ""; } String url = ""; foreach(KeyValuePair<int, string> entry in builder.GetCustomDimensions()) { if (entry.Value != null) { url += Fields.CUSTOM_DIMENSION.ToString() + entry.Key + "=" + WWW.EscapeURL(entry.Value.ToString()); } } foreach(KeyValuePair<int, string> entry in builder.GetCustomMetrics()) { if (entry.Value != null) { url += Fields.CUSTOM_METRIC.ToString() + entry.Key + "=" + WWW.EscapeURL(entry.Value.ToString()); } } if(!String.IsNullOrEmpty(url)){ if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log("Added custom variables to hit."); } } return url; } private string AddCampaignParameters<T>(HitBuilder<T> builder) { if(!trackingCodeSet){ return ""; } String url = ""; url += AddOptionalMPParameter(Fields.CAMPAIGN_NAME, builder.GetCampaignName()); url += AddOptionalMPParameter(Fields.CAMPAIGN_SOURCE, builder.GetCampaignSource()); url += AddOptionalMPParameter(Fields.CAMPAIGN_MEDIUM, builder.GetCampaignMedium()); url += AddOptionalMPParameter(Fields.CAMPAIGN_KEYWORD, builder.GetCampaignKeyword()); url += AddOptionalMPParameter(Fields.CAMPAIGN_CONTENT, builder.GetCampaignContent()); url += AddOptionalMPParameter(Fields.CAMPAIGN_ID, builder.GetCampaignID()); url += AddOptionalMPParameter(Fields.GCLID, builder.GetGclid()); url += AddOptionalMPParameter(Fields.DCLID, builder.GetDclid()); if(!String.IsNullOrEmpty(url)){ if (GoogleAnalyticsV3.belowThreshold(logLevel, GoogleAnalyticsV3.DebugMode.VERBOSE)) { Debug.Log("Added campaign parameters to hit. url:" + url); } } return url; } public void LogScreen(AppViewHitBuilder builder) { trackerValues[Fields.SCREEN_NAME] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "appview") + AddRequiredMPParameter(Fields.SCREEN_NAME, builder.GetScreenName()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void LogEvent(EventHitBuilder builder) { trackerValues[Fields.EVENT_CATEGORY] = null; trackerValues[Fields.EVENT_ACTION] = null; trackerValues[Fields.EVENT_LABEL] = null; trackerValues[Fields.EVENT_VALUE] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "event") + AddOptionalMPParameter(Fields.EVENT_CATEGORY, builder.GetEventCategory()) + AddOptionalMPParameter(Fields.EVENT_ACTION, builder.GetEventAction()) + AddOptionalMPParameter(Fields.EVENT_LABEL, builder.GetEventLabel()) + AddOptionalMPParameter(Fields.EVENT_VALUE, builder.GetEventValue()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void LogTransaction(TransactionHitBuilder builder) { trackerValues[Fields.TRANSACTION_ID] = null; trackerValues[Fields.TRANSACTION_AFFILIATION] = null; trackerValues[Fields.TRANSACTION_REVENUE] = null; trackerValues[Fields.TRANSACTION_SHIPPING] = null; trackerValues[Fields.TRANSACTION_TAX] = null; trackerValues[Fields.CURRENCY_CODE] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "transaction") + AddRequiredMPParameter(Fields.TRANSACTION_ID, builder.GetTransactionID()) + AddOptionalMPParameter(Fields.TRANSACTION_AFFILIATION, builder.GetAffiliation()) + AddOptionalMPParameter(Fields.TRANSACTION_REVENUE, builder.GetRevenue()) + AddOptionalMPParameter(Fields.TRANSACTION_SHIPPING, builder.GetShipping()) + AddOptionalMPParameter(Fields.TRANSACTION_TAX, builder.GetTax()) + AddOptionalMPParameter(Fields.CURRENCY_CODE, builder.GetCurrencyCode()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void LogItem(ItemHitBuilder builder) { trackerValues[Fields.TRANSACTION_ID] = null; trackerValues[Fields.ITEM_NAME] = null; trackerValues[Fields.ITEM_SKU] = null; trackerValues[Fields.ITEM_CATEGORY] = null; trackerValues[Fields.ITEM_PRICE] = null; trackerValues[Fields.ITEM_QUANTITY] = null; trackerValues[Fields.CURRENCY_CODE] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "item") + AddRequiredMPParameter(Fields.TRANSACTION_ID, builder.GetTransactionID()) + AddRequiredMPParameter(Fields.ITEM_NAME, builder.GetName()) + AddOptionalMPParameter(Fields.ITEM_SKU, builder.GetSKU()) + AddOptionalMPParameter(Fields.ITEM_CATEGORY, builder.GetCategory()) + AddOptionalMPParameter(Fields.ITEM_PRICE, builder.GetPrice()) + AddOptionalMPParameter(Fields.ITEM_QUANTITY, builder.GetQuantity()) + AddOptionalMPParameter(Fields.CURRENCY_CODE, builder.GetCurrencyCode()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void LogException(ExceptionHitBuilder builder) { trackerValues[Fields.EX_DESCRIPTION] = null; trackerValues[Fields.EX_FATAL] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "exception") + AddOptionalMPParameter(Fields.EX_DESCRIPTION, builder.GetExceptionDescription()) + AddOptionalMPParameter(Fields.EX_FATAL, builder.IsFatal()) + AddTrackerVals()); } public void LogSocial(SocialHitBuilder builder) { trackerValues[Fields.SOCIAL_NETWORK] = null; trackerValues[Fields.SOCIAL_ACTION] = null; trackerValues[Fields.SOCIAL_TARGET] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "social") + AddRequiredMPParameter(Fields.SOCIAL_NETWORK, builder.GetSocialNetwork()) + AddRequiredMPParameter(Fields.SOCIAL_ACTION, builder.GetSocialAction()) + AddRequiredMPParameter(Fields.SOCIAL_TARGET, builder.GetSocialTarget()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void LogTiming(TimingHitBuilder builder) { trackerValues[Fields.TIMING_CATEGORY] = null; trackerValues[Fields.TIMING_VALUE] = null; trackerValues[Fields.TIMING_LABEL] = null; trackerValues[Fields.TIMING_VAR] = null; SendGaHitWithMeasurementProtocol(url + AddRequiredMPParameter(Fields.HIT_TYPE, "timing") + AddOptionalMPParameter(Fields.TIMING_CATEGORY, builder.GetTimingCategory()) + AddOptionalMPParameter(Fields.TIMING_VALUE, builder.GetTimingInterval()) + AddOptionalMPParameter(Fields.TIMING_LABEL, builder.GetTimingLabel()) + AddOptionalMPParameter(Fields.TIMING_VAR, builder.GetTimingName()) + AddCustomVariables(builder) + AddCampaignParameters(builder) + AddTrackerVals()); } public void ClearUserIDOverride() { SetTrackerVal(Fields.USER_ID, null); } public void SetTrackingCode(string trackingCode) { this.trackingCode = trackingCode; } public void SetBundleIdentifier(string bundleIdentifier) { this.bundleIdentifier = bundleIdentifier; } public void SetAppName(string appName) { this.appName = appName; } public void SetAppVersion(string appVersion) { this.appVersion = appVersion; } public void SetLogLevelValue(GoogleAnalyticsV3.DebugMode logLevel) { this.logLevel = logLevel; } public void SetAnonymizeIP(bool anonymizeIP) { this.anonymizeIP = anonymizeIP; } public void SetDryRun(bool dryRun) { this.dryRun = dryRun; } public void SetOptOut(bool optOut) { this.optOut = optOut; } #endif }
using System; using UnityEngine; using UnityEngine.Rendering; namespace UnityStandardAssets.CinematicEffects { [ExecuteInEditMode] #if UNITY_5_4_OR_NEWER [ImageEffectAllowedInSceneView] #endif [RequireComponent(typeof(Camera))] [AddComponentMenu("Image Effects/Cinematic/Temporal Anti-aliasing")] public class TemporalAntiAliasing : MonoBehaviour { public enum Sequence { Halton } [Serializable] public struct JitterSettings { [Tooltip("The sequence used to generate the points used as jitter offsets.")] public Sequence sequence; [Tooltip("The diameter (in texels) inside which jitter samples are spread. Smaller values result in crisper but more aliased output, while larger values result in more stable but blurrier output.")] [Range(0.1f, 3f)] public float spread; [Tooltip("Number of temporal samples. A larger value results in a smoother image but takes longer to converge; whereas a smaller value converges fast but allows for less subpixel information.")] [Range(4, 64)] public int sampleCount; } [Serializable] public struct SharpenFilterSettings { [Tooltip("Controls the amount of sharpening applied to the color buffer.")] [Range(0f, 3f)] public float amount; } [Serializable] public struct BlendSettings { [Tooltip("The blend coefficient for a stationary fragment. Controls the percentage of history sample blended into the final color.")] [Range(0f, 1f)] public float stationary; [Tooltip("The blend coefficient for a fragment with significant motion. Controls the percentage of history sample blended into the final color.")] [Range(0f, 1f)] public float moving; [Tooltip("Amount of motion amplification in percentage. A higher value will make the final blend more sensitive to smaller motion, but might result in more aliased output; while a smaller value might desensitivize the algorithm resulting in a blurry output.")] [Range(30f, 100f)] public float motionAmplification; } [Serializable] public struct DebugSettings { [Tooltip("Forces the game view to update automatically while not in play mode.")] public bool forceRepaint; } [Serializable] public class Settings { [AttributeUsage(AttributeTargets.Field)] public class LayoutAttribute : PropertyAttribute { } [Layout] public JitterSettings jitterSettings; [Layout] public SharpenFilterSettings sharpenFilterSettings; [Layout] public BlendSettings blendSettings; [Layout] public DebugSettings debugSettings; public static Settings defaultSettings { get { return new Settings { jitterSettings = new JitterSettings { sequence = Sequence.Halton, spread = 1f, sampleCount = 8 }, sharpenFilterSettings = new SharpenFilterSettings { amount = 0.25f }, blendSettings = new BlendSettings { stationary = 0.98f, moving = 0.8f, motionAmplification = 60f }, debugSettings = new DebugSettings { forceRepaint = false } }; } } } [SerializeField] public Settings settings = Settings.defaultSettings; private Shader m_Shader; public Shader shader { get { if (m_Shader == null) m_Shader = Shader.Find("Hidden/Temporal Anti-aliasing"); return m_Shader; } } private Material m_Material; public Material material { get { if (m_Material == null) { if (shader == null || !shader.isSupported) return null; m_Material = new Material(shader); } return m_Material; } } private Camera m_Camera; public new Camera camera { get { if (m_Camera == null) m_Camera = GetComponent<Camera>(); return m_Camera; } } private void RenderFullScreenQuad(int pass) { GL.PushMatrix(); GL.LoadOrtho(); material.SetPass(pass); //Render the full screen quad manually. GL.Begin(GL.QUADS); GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(0.0f, 0.0f, 0.1f); GL.TexCoord2(1.0f, 0.0f); GL.Vertex3(1.0f, 0.0f, 0.1f); GL.TexCoord2(1.0f, 1.0f); GL.Vertex3(1.0f, 1.0f, 0.1f); GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(0.0f, 1.0f, 0.1f); GL.End(); GL.PopMatrix(); } private RenderTexture m_History; private int m_SampleIndex = 0; #if UNITY_EDITOR private double m_NextForceRepaintTime = 0; #endif private float GetHaltonValue(int index, int radix) { float result = 0.0f; float fraction = 1.0f / (float)radix; while (index > 0) { result += (float)(index % radix) * fraction; index /= radix; fraction /= (float)radix; } return result; } private Vector2 GenerateRandomOffset() { Vector2 offset = new Vector2( GetHaltonValue(m_SampleIndex & 1023, 2), GetHaltonValue(m_SampleIndex & 1023, 3)); if (++m_SampleIndex >= settings.jitterSettings.sampleCount) m_SampleIndex = 0; return offset; } // Adapted heavily from PlayDead's TAA code // https://github.com/playdeadgames/temporal/blob/master/Assets/Scripts/Extensions.cs private Matrix4x4 GetPerspectiveProjectionMatrix(Vector2 offset) { float vertical = Mathf.Tan(0.5f * Mathf.Deg2Rad * camera.fieldOfView); float horizontal = vertical * camera.aspect; offset.x *= horizontal / (0.5f * camera.pixelWidth); offset.y *= vertical / (0.5f * camera.pixelHeight); float left = (offset.x - horizontal) * camera.nearClipPlane; float right = (offset.x + horizontal) * camera.nearClipPlane; float top = (offset.y + vertical) * camera.nearClipPlane; float bottom = (offset.y - vertical) * camera.nearClipPlane; Matrix4x4 matrix = new Matrix4x4(); matrix[0, 0] = (2.0f * camera.nearClipPlane) / (right - left); matrix[0, 1] = 0.0f; matrix[0, 2] = (right + left) / (right - left); matrix[0, 3] = 0.0f; matrix[1, 0] = 0.0f; matrix[1, 1] = (2.0f * camera.nearClipPlane) / (top - bottom); matrix[1, 2] = (top + bottom) / (top - bottom); matrix[1, 3] = 0.0f; matrix[2, 0] = 0.0f; matrix[2, 1] = 0.0f; matrix[2, 2] = -(camera.farClipPlane + camera.nearClipPlane) / (camera.farClipPlane - camera.nearClipPlane); matrix[2, 3] = -(2.0f * camera.farClipPlane * camera.nearClipPlane) / (camera.farClipPlane - camera.nearClipPlane); matrix[3, 0] = 0.0f; matrix[3, 1] = 0.0f; matrix[3, 2] = -1.0f; matrix[3, 3] = 0.0f; return matrix; } private Matrix4x4 GetOrthographicProjectionMatrix(Vector2 offset) { float vertical = camera.orthographicSize; float horizontal = vertical * camera.aspect; offset.x *= horizontal / (0.5f * camera.pixelWidth); offset.y *= vertical / (0.5f * camera.pixelHeight); float left = offset.x - horizontal; float right = offset.x + horizontal; float top = offset.y + vertical; float bottom = offset.y - vertical; return Matrix4x4.Ortho(left, right, bottom, top, camera.nearClipPlane, camera.farClipPlane); } void OnEnable() { #if !UNITY_5_4_OR_NEWER enabled = false; #endif #if UNITY_EDITOR UnityEditor.EditorApplication.update += ForceRepaint; #endif camera.depthTextureMode = DepthTextureMode.Depth | DepthTextureMode.MotionVectors; #if UNITY_5_5_OR_NEWER camera.useJitteredProjectionMatrixForTransparentRendering = true; #endif } void OnDisable() { if (m_History != null) { RenderTexture.ReleaseTemporary(m_History); m_History = null; } camera.depthTextureMode &= ~(DepthTextureMode.MotionVectors); m_SampleIndex = 0; } void OnPreCull() { Vector2 jitter = GenerateRandomOffset(); jitter *= settings.jitterSettings.spread; #if UNITY_5_4_OR_NEWER camera.nonJitteredProjectionMatrix = camera.projectionMatrix; #endif camera.projectionMatrix = camera.orthographic ? GetOrthographicProjectionMatrix(jitter) : GetPerspectiveProjectionMatrix(jitter); jitter.x /= camera.pixelWidth; jitter.y /= camera.pixelHeight; material.SetVector("_Jitter", jitter); } [ImageEffectOpaque] void OnRenderImage(RenderTexture source, RenderTexture destination) { if (m_History == null || (m_History.width != source.width || m_History.height != source.height)) { if (m_History) RenderTexture.ReleaseTemporary(m_History); m_History = RenderTexture.GetTemporary(source.width, source.height, 0, source.format, RenderTextureReadWrite.Default); m_History.filterMode = FilterMode.Bilinear; m_History.hideFlags = HideFlags.HideAndDontSave; Graphics.Blit(source, m_History, material, 2); } material.SetVector("_SharpenParameters", new Vector4(settings.sharpenFilterSettings.amount, 0f, 0f, 0f)); material.SetVector("_FinalBlendParameters", new Vector4(settings.blendSettings.stationary, settings.blendSettings.moving, 100f * settings.blendSettings.motionAmplification, 0f)); material.SetTexture("_MainTex", source); material.SetTexture("_HistoryTex", m_History); RenderTexture temporary = RenderTexture.GetTemporary(source.width, source.height, 0, source.format, RenderTextureReadWrite.Default); temporary.filterMode = FilterMode.Bilinear; var effectDestination = destination; var doesNeedExtraBlit = false; if (destination == null) { effectDestination = RenderTexture.GetTemporary(source.width, source.height, 0, source.format, RenderTextureReadWrite.Default); effectDestination.filterMode = FilterMode.Bilinear; doesNeedExtraBlit = true; } var renderTargets = new RenderBuffer[2]; renderTargets[0] = effectDestination.colorBuffer; renderTargets[1] = temporary.colorBuffer; Graphics.SetRenderTarget(renderTargets, effectDestination.depthBuffer); RenderFullScreenQuad(camera.orthographic ? 1 : 0); RenderTexture.ReleaseTemporary(m_History); m_History = temporary; if (doesNeedExtraBlit) { Graphics.Blit(effectDestination, destination); RenderTexture.ReleaseTemporary(effectDestination); } RenderTexture.active = destination; } public void OnPostRender() { camera.ResetProjectionMatrix(); } #if UNITY_EDITOR private void ForceRepaint() { if (settings.debugSettings.forceRepaint && !UnityEditor.EditorApplication.isPlaying) { var time = UnityEditor.EditorApplication.timeSinceStartup; if (time > m_NextForceRepaintTime) { UnityEditorInternal.InternalEditorUtility.RepaintAllViews(); m_NextForceRepaintTime = time + 0.033333; } } } #endif } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Buffers; using System.Diagnostics; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Security.Cryptography.Asn1; namespace System.Security.Cryptography { internal static class DSAKeyFormatHelper { private static readonly string[] s_validOids = { Oids.Dsa, }; internal static void ReadDsaPrivateKey( ReadOnlyMemory<byte> xBytes, in AlgorithmIdentifierAsn algId, out DSAParameters ret) { if (!algId.Parameters.HasValue) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } DssParms parms = DssParms.Decode(algId.Parameters.Value, AsnEncodingRules.BER); ret = new DSAParameters { P = parms.P.ToByteArray(isUnsigned: true, isBigEndian: true), Q = parms.Q.ToByteArray(isUnsigned: true, isBigEndian: true), }; ret.G = parms.G.ExportKeyParameter(ret.P.Length); AsnReader reader = new AsnReader(xBytes, AsnEncodingRules.DER); // Force a positive interpretation because Windows sometimes writes negative numbers. BigInteger x = new BigInteger(reader.ReadIntegerBytes().Span, isUnsigned: true, isBigEndian: true); ret.X = x.ExportKeyParameter(ret.Q.Length); reader.ThrowIfNotEmpty(); // The public key is not contained within the format, calculate it. BigInteger y = BigInteger.ModPow(parms.G, x, parms.P); ret.Y = y.ExportKeyParameter(ret.P.Length); } internal static void ReadDsaPublicKey( ReadOnlyMemory<byte> yBytes, in AlgorithmIdentifierAsn algId, out DSAParameters ret) { AsnReader reader = new AsnReader(yBytes, AsnEncodingRules.DER); BigInteger y = reader.ReadInteger(); reader.ThrowIfNotEmpty(); if (!algId.Parameters.HasValue) { throw new CryptographicException(SR.Cryptography_Der_Invalid_Encoding); } DssParms parms = DssParms.Decode(algId.Parameters.Value, AsnEncodingRules.BER); ret = new DSAParameters { P = parms.P.ToByteArray(isUnsigned: true, isBigEndian: true), Q = parms.Q.ToByteArray(isUnsigned: true, isBigEndian: true), }; ret.G = parms.G.ExportKeyParameter(ret.P.Length); ret.Y = y.ExportKeyParameter(ret.P.Length); } internal static void ReadSubjectPublicKeyInfo( ReadOnlySpan<byte> source, out int bytesRead, out DSAParameters key) { KeyFormatHelper.ReadSubjectPublicKeyInfo<DSAParameters>( s_validOids, source, ReadDsaPublicKey, out bytesRead, out key); } internal static ReadOnlyMemory<byte> ReadSubjectPublicKeyInfo( ReadOnlyMemory<byte> source, out int bytesRead) { return KeyFormatHelper.ReadSubjectPublicKeyInfo( s_validOids, source, out bytesRead); } internal static void ReadPkcs8( ReadOnlySpan<byte> source, out int bytesRead, out DSAParameters key) { KeyFormatHelper.ReadPkcs8<DSAParameters>( s_validOids, source, ReadDsaPrivateKey, out bytesRead, out key); } internal static void ReadEncryptedPkcs8( ReadOnlySpan<byte> source, ReadOnlySpan<char> password, out int bytesRead, out DSAParameters key) { KeyFormatHelper.ReadEncryptedPkcs8<DSAParameters>( s_validOids, source, password, ReadDsaPrivateKey, out bytesRead, out key); } internal static void ReadEncryptedPkcs8( ReadOnlySpan<byte> source, ReadOnlySpan<byte> passwordBytes, out int bytesRead, out DSAParameters key) { KeyFormatHelper.ReadEncryptedPkcs8<DSAParameters>( s_validOids, source, passwordBytes, ReadDsaPrivateKey, out bytesRead, out key); } internal static AsnWriter WriteSubjectPublicKeyInfo(in DSAParameters dsaParameters) { AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); writer.PushSequence(); WriteAlgorithmId(writer, dsaParameters); WriteKeyComponent(writer, dsaParameters.Y, bitString: true); writer.PopSequence(); return writer; } internal static AsnWriter WritePkcs8(in DSAParameters dsaParameters) { AsnWriter writer = new AsnWriter(AsnEncodingRules.DER); writer.PushSequence(); writer.WriteInteger(0); WriteAlgorithmId(writer, dsaParameters); WriteKeyComponent(writer, dsaParameters.X, bitString: false); writer.PopSequence(); return writer; } private static void WriteAlgorithmId(AsnWriter writer, in DSAParameters dsaParameters) { writer.PushSequence(); writer.WriteObjectIdentifier(Oids.Dsa); // Dss-Parms ::= SEQUENCE { // p INTEGER, // q INTEGER, // g INTEGER } writer.PushSequence(); writer.WriteKeyParameterInteger(dsaParameters.P); writer.WriteKeyParameterInteger(dsaParameters.Q); writer.WriteKeyParameterInteger(dsaParameters.G); writer.PopSequence(); writer.PopSequence(); } private static void WriteKeyComponent(AsnWriter writer, byte[] component, bool bitString) { using (AsnWriter inner = new AsnWriter(AsnEncodingRules.DER)) { inner.WriteKeyParameterInteger(component); if (bitString) { writer.WriteBitString(inner.EncodeAsSpan()); } else { writer.WriteOctetString(inner.EncodeAsSpan()); } } } } }
// <copyright file="MetricViewTests.cs" company="OpenTelemetry Authors"> // Copyright The OpenTelemetry 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. // </copyright> using System; using System.Collections.Generic; using System.Diagnostics.Metrics; using OpenTelemetry.Tests; using Xunit; using Xunit.Abstractions; namespace OpenTelemetry.Metrics.Tests { public class MetricViewTests { private const int MaxTimeToAllowForFlush = 10000; private readonly ITestOutputHelper output; public MetricViewTests(ITestOutputHelper output) { this.output = output; } [Fact] public void ViewToRenameMetric() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("name1", "renamed") .AddInMemoryExporter(exportedItems) .Build(); // Expecting one metric stream. var counterLong = meter.CreateCounter<long>("name1"); counterLong.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Single(exportedItems); var metric = exportedItems[0]; Assert.Equal("renamed", metric.Name); } [Theory] [MemberData(nameof(MetricTestData.InvalidInstrumentNames), MemberType = typeof(MetricTestData))] public void AddViewWithInvalidNameThrowsArgumentException(string viewNewName) { var exportedItems = new List<Metric>(); using var meter1 = new Meter("AddViewWithInvalidNameThrowsArgumentException"); var ex = Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder() .AddMeter(meter1.Name) .AddView("name1", viewNewName) .AddInMemoryExporter(exportedItems) .Build()); Assert.Contains($"Custom view name {viewNewName} is invalid.", ex.Message); ex = Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder() .AddMeter(meter1.Name) .AddView("name1", new MetricStreamConfiguration { Name = viewNewName }) .AddInMemoryExporter(exportedItems) .Build()); Assert.Contains($"Custom view name {viewNewName} is invalid.", ex.Message); } [Fact] public void AddViewWithNullMetricStreamConfigurationThrowsArgumentnullException() { var exportedItems = new List<Metric>(); using var meter1 = new Meter("AddViewWithInvalidNameThrowsArgumentException"); Assert.Throws<ArgumentNullException>(() => Sdk.CreateMeterProviderBuilder() .AddMeter(meter1.Name) .AddView("name1", (MetricStreamConfiguration)null) .AddInMemoryExporter(exportedItems) .Build()); } [Fact] public void AddViewWithNameThrowsInvalidArgumentExceptionWhenConflict() { var exportedItems = new List<Metric>(); using var meter1 = new Meter("AddViewWithGuaranteedConflictThrowsInvalidArgumentException"); Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder() .AddMeter(meter1.Name) .AddView("instrumenta.*", name: "newname") .AddInMemoryExporter(exportedItems) .Build()); } [Fact] public void AddViewWithNameInMetricStreamConfigurationThrowsInvalidArgumentExceptionWhenConflict() { var exportedItems = new List<Metric>(); using var meter1 = new Meter("AddViewWithGuaranteedConflictThrowsInvalidArgumentException"); Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder() .AddMeter(meter1.Name) .AddView("instrumenta.*", new MetricStreamConfiguration() { Name = "newname" }) .AddInMemoryExporter(exportedItems) .Build()); } [Theory] [MemberData(nameof(MetricTestData.InvalidHistogramBoundaries), MemberType = typeof(MetricTestData))] public void AddViewWithInvalidHistogramBoundsThrowsArgumentException(double[] boundaries) { var ex = Assert.Throws<ArgumentException>(() => Sdk.CreateMeterProviderBuilder() .AddView("name1", new ExplicitBucketHistogramConfiguration { Boundaries = boundaries })); Assert.Contains("Histogram boundaries must be in ascending order with distinct values", ex.Message); } [Theory] [MemberData(nameof(MetricTestData.ValidInstrumentNames), MemberType = typeof(MetricTestData))] public void ViewWithValidNameExported(string viewNewName) { var exportedItems = new List<Metric>(); using var meter1 = new Meter("ViewWithInvalidNameIgnoredTest"); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter1.Name) .AddView("name1", viewNewName) .AddInMemoryExporter(exportedItems) .Build(); var counterLong = meter1.CreateCounter<long>("name1"); counterLong.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); // Expecting one metric stream. Assert.Single(exportedItems); var metric = exportedItems[0]; Assert.Equal(viewNewName, metric.Name); } [Fact] public void ViewToRenameMetricConditionally() { using var meter1 = new Meter($"{Utils.GetCurrentMethodName()}.1"); using var meter2 = new Meter($"{Utils.GetCurrentMethodName()}.2"); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter1.Name) .AddMeter(meter2.Name) .AddView((instrument) => { if (instrument.Meter.Name.Equals(meter2.Name, StringComparison.OrdinalIgnoreCase) && instrument.Name.Equals("name1", StringComparison.OrdinalIgnoreCase)) { return new MetricStreamConfiguration() { Name = "name1_Renamed", Description = "new description" }; } else { return null; } }) .AddInMemoryExporter(exportedItems) .Build(); // Without views only 1 stream would be // exported (the 2nd one gets dropped due to // name conflict). Due to renaming with Views, // we expect 2 metric streams here. var counter1 = meter1.CreateCounter<long>("name1", "unit", "original_description"); var counter2 = meter2.CreateCounter<long>("name1", "unit", "original_description"); counter1.Add(10); counter2.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(2, exportedItems.Count); Assert.Equal("name1", exportedItems[0].Name); Assert.Equal("name1_Renamed", exportedItems[1].Name); Assert.Equal("original_description", exportedItems[0].Description); Assert.Equal("new description", exportedItems[1].Description); } [Theory] [MemberData(nameof(MetricTestData.InvalidInstrumentNames), MemberType = typeof(MetricTestData))] public void ViewWithInvalidNameIgnoredConditionally(string viewNewName) { using var meter1 = new Meter("ViewToRenameMetricConditionallyTest"); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter1.Name) // since here it's a func, we can't validate the name right away // so the view is allowed to be added, but upon instrument creation it's going to be ignored. .AddView((instrument) => { if (instrument.Meter.Name.Equals(meter1.Name, StringComparison.OrdinalIgnoreCase) && instrument.Name.Equals("name1", StringComparison.OrdinalIgnoreCase)) { // invalid instrument name as per the spec return new MetricStreamConfiguration() { Name = viewNewName, Description = "new description" }; } else { return null; } }) .AddInMemoryExporter(exportedItems) .Build(); // We should expect 1 metric here, // but because the MetricStreamName passed is invalid, the instrument is ignored var counter1 = meter1.CreateCounter<long>("name1", "unit", "original_description"); counter1.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Empty(exportedItems); } [Theory] [MemberData(nameof(MetricTestData.ValidInstrumentNames), MemberType = typeof(MetricTestData))] public void ViewWithValidNameConditionally(string viewNewName) { using var meter1 = new Meter("ViewToRenameMetricConditionallyTest"); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter1.Name) .AddView((instrument) => { if (instrument.Meter.Name.Equals(meter1.Name, StringComparison.OrdinalIgnoreCase) && instrument.Name.Equals("name1", StringComparison.OrdinalIgnoreCase)) { // invalid instrument name as per the spec return new MetricStreamConfiguration() { Name = viewNewName, Description = "new description" }; } else { return null; } }) .AddInMemoryExporter(exportedItems) .Build(); // Expecting one metric stream. var counter1 = meter1.CreateCounter<long>("name1", "unit", "original_description"); counter1.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); // Expecting one metric stream. Assert.Single(exportedItems); var metric = exportedItems[0]; Assert.Equal(viewNewName, metric.Name); } [Fact] public void ViewWithNullCustomNameTakesInstrumentName() { var exportedItems = new List<Metric>(); using var meter = new Meter("ViewToRenameMetricConditionallyTest"); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView((instrument) => { if (instrument.Name.Equals("name1", StringComparison.OrdinalIgnoreCase)) { // null View name return new MetricStreamConfiguration() { }; } else { return null; } }) .AddInMemoryExporter(exportedItems) .Build(); // Expecting one metric stream. // Since the View name was null, the instrument name was used instead var counter1 = meter.CreateCounter<long>("name1", "unit", "original_description"); counter1.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); // Expecting one metric stream. Assert.Single(exportedItems); var metric = exportedItems[0]; Assert.Equal(counter1.Name, metric.Name); } [Fact] public void ViewToProduceMultipleStreamsFromInstrument() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("name1", "renamedStream1") .AddView("name1", "renamedStream2") .AddInMemoryExporter(exportedItems) .Build(); // Expecting two metric stream. var counterLong = meter.CreateCounter<long>("name1"); counterLong.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(2, exportedItems.Count); Assert.Equal("renamedStream1", exportedItems[0].Name); Assert.Equal("renamedStream2", exportedItems[1].Name); } [Fact] public void ViewToProduceMultipleStreamsWithDuplicatesFromInstrument() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("name1", "renamedStream1") .AddView("name1", "renamedStream2") .AddView("name1", "renamedStream2") .AddInMemoryExporter(exportedItems) .Build(); // Expecting two metric stream. // the .AddView("name1", "renamedStream2") // won't produce new Metric as the name // conflicts. var counterLong = meter.CreateCounter<long>("name1"); counterLong.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(2, exportedItems.Count); Assert.Equal("renamedStream1", exportedItems[0].Name); Assert.Equal("renamedStream2", exportedItems[1].Name); } [Fact] public void ViewToProduceCustomHistogramBound() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List<Metric>(); var boundaries = new double[] { 10, 20 }; using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("MyHistogram", new ExplicitBucketHistogramConfiguration() { Name = "MyHistogramDefaultBound" }) .AddView("MyHistogram", new ExplicitBucketHistogramConfiguration() { Boundaries = boundaries }) .AddInMemoryExporter(exportedItems) .Build(); var histogram = meter.CreateHistogram<long>("MyHistogram"); histogram.Record(-10); histogram.Record(0); histogram.Record(1); histogram.Record(9); histogram.Record(10); histogram.Record(11); histogram.Record(19); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(2, exportedItems.Count); var metricDefault = exportedItems[0]; var metricCustom = exportedItems[1]; Assert.Equal("MyHistogramDefaultBound", metricDefault.Name); Assert.Equal("MyHistogram", metricCustom.Name); List<MetricPoint> metricPointsDefault = new List<MetricPoint>(); foreach (ref readonly var mp in metricDefault.GetMetricPoints()) { metricPointsDefault.Add(mp); } Assert.Single(metricPointsDefault); var histogramPoint = metricPointsDefault[0]; var count = histogramPoint.GetHistogramCount(); var sum = histogramPoint.GetHistogramSum(); Assert.Equal(40, sum); Assert.Equal(7, count); int index = 0; int actualCount = 0; var expectedBucketCounts = new long[] { 2, 1, 2, 2, 0, 0, 0, 0, 0, 0, 0 }; foreach (var histogramMeasurement in histogramPoint.GetHistogramBuckets()) { Assert.Equal(expectedBucketCounts[index], histogramMeasurement.BucketCount); index++; actualCount++; } Assert.Equal(Metric.DefaultHistogramBounds.Length + 1, actualCount); List<MetricPoint> metricPointsCustom = new List<MetricPoint>(); foreach (ref readonly var mp in metricCustom.GetMetricPoints()) { metricPointsCustom.Add(mp); } Assert.Single(metricPointsCustom); histogramPoint = metricPointsCustom[0]; count = histogramPoint.GetHistogramCount(); sum = histogramPoint.GetHistogramSum(); Assert.Equal(40, sum); Assert.Equal(7, count); index = 0; actualCount = 0; expectedBucketCounts = new long[] { 5, 2, 0 }; foreach (var histogramMeasurement in histogramPoint.GetHistogramBuckets()) { Assert.Equal(expectedBucketCounts[index], histogramMeasurement.BucketCount); index++; actualCount++; } Assert.Equal(boundaries.Length + 1, actualCount); } [Fact] public void ViewToSelectTagKeys() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("FruitCounter", new MetricStreamConfiguration() { TagKeys = new string[] { "name" }, Name = "NameOnly" }) .AddView("FruitCounter", new MetricStreamConfiguration() { TagKeys = new string[] { "size" }, Name = "SizeOnly" }) .AddView("FruitCounter", new MetricStreamConfiguration() { TagKeys = new string[] { }, Name = "NoTags" }) .AddInMemoryExporter(exportedItems) .Build(); var counter = meter.CreateCounter<long>("FruitCounter"); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "small")); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "small")); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "medium")); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "medium")); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "large")); counter.Add(10, new("name", "apple"), new("color", "red"), new("size", "large")); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(3, exportedItems.Count); var metric = exportedItems[0]; Assert.Equal("NameOnly", metric.Name); List<MetricPoint> metricPoints = new List<MetricPoint>(); foreach (ref readonly var mp in metric.GetMetricPoints()) { metricPoints.Add(mp); } // Only one point expected "apple" Assert.Single(metricPoints); metric = exportedItems[1]; Assert.Equal("SizeOnly", metric.Name); metricPoints.Clear(); foreach (ref readonly var mp in metric.GetMetricPoints()) { metricPoints.Add(mp); } // 3 points small,medium,large expected Assert.Equal(3, metricPoints.Count); metric = exportedItems[2]; Assert.Equal("NoTags", metric.Name); metricPoints.Clear(); foreach (ref readonly var mp in metric.GetMetricPoints()) { metricPoints.Add(mp); } // Single point expected. Assert.Single(metricPoints); } [Fact] public void ViewToDropSingleInstrument() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("counterNotInteresting", new MetricStreamConfiguration() { Aggregation = Aggregation.Drop }) .AddInMemoryExporter(exportedItems) .Build(); // Expecting one metric stream. var counterInteresting = meter.CreateCounter<long>("counterInteresting"); var counterNotInteresting = meter.CreateCounter<long>("counterNotInteresting"); counterInteresting.Add(10); counterNotInteresting.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Single(exportedItems); var metric = exportedItems[0]; Assert.Equal("counterInteresting", metric.Name); } [Fact] public void ViewToDropSingleInstrumentObservableCounter() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("observableCounterNotInteresting", new MetricStreamConfiguration() { Aggregation = Aggregation.Drop }) .AddInMemoryExporter(exportedItems) .Build(); // Expecting one metric stream. meter.CreateObservableCounter("observableCounterNotInteresting", () => { return 10; }, "ms"); meter.CreateObservableCounter("observableCounterInteresting", () => { return 10; }, "ms"); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Single(exportedItems); var metric = exportedItems[0]; Assert.Equal("observableCounterInteresting", metric.Name); } [Fact] public void ViewToDropSingleInstrumentObservableGauge() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("observableGaugeNotInteresting", new MetricStreamConfiguration() { Aggregation = Aggregation.Drop }) .AddInMemoryExporter(exportedItems) .Build(); // Expecting one metric stream. meter.CreateObservableGauge("observableGaugeNotInteresting", () => { return 10; }, "ms"); meter.CreateObservableGauge("observableGaugeInteresting", () => { return 10; }, "ms"); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Single(exportedItems); var metric = exportedItems[0]; Assert.Equal("observableGaugeInteresting", metric.Name); } [Fact] public void ViewToDropMultipleInstruments() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("server*", new MetricStreamConfiguration() { Aggregation = Aggregation.Drop }) .AddInMemoryExporter(exportedItems) .Build(); // Expecting two client metric streams as both server* are dropped. var serverRequests = meter.CreateCounter<long>("server.requests"); var serverExceptions = meter.CreateCounter<long>("server.exceptions"); var clientRequests = meter.CreateCounter<long>("client.requests"); var clientExceptions = meter.CreateCounter<long>("client.exceptions"); serverRequests.Add(10); serverExceptions.Add(10); clientRequests.Add(10); clientExceptions.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Equal(2, exportedItems.Count); Assert.Equal("client.requests", exportedItems[0].Name); Assert.Equal("client.exceptions", exportedItems[1].Name); } [Fact] public void ViewToDropAndRetainInstrument() { using var meter = new Meter(Utils.GetCurrentMethodName()); var exportedItems = new List<Metric>(); using var meterProvider = Sdk.CreateMeterProviderBuilder() .AddMeter(meter.Name) .AddView("server.requests", MetricStreamConfiguration.Drop) .AddView("server.requests", "server.request_renamed") .AddInMemoryExporter(exportedItems) .Build(); // Expecting one metric stream even though a View is asking // to drop the instrument, because another View is matching // the instrument, which asks to aggregate with defaults // and a use a new name for the resulting metric. var serverRequests = meter.CreateCounter<long>("server.requests"); serverRequests.Add(10); meterProvider.ForceFlush(MaxTimeToAllowForFlush); Assert.Single(exportedItems); Assert.Equal("server.request_renamed", exportedItems[0].Name); } [Fact] public void MetricStreamConfigurationForDropMustNotAllowOverriding() { MetricStreamConfiguration.Drop.Aggregation = Aggregation.Histogram; Assert.Equal(Aggregation.Drop, MetricStreamConfiguration.Drop.Aggregation); } } }
// <copyright file="SparseMatrixTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // // Copyright (c) 2009-2016 Math.NET // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // </copyright> using System; using System.Collections.Generic; using MathNet.Numerics.LinearAlgebra; using MathNet.Numerics.LinearAlgebra.Complex32; using NUnit.Framework; namespace MathNet.Numerics.UnitTests.LinearAlgebraTests.Complex32 { using Numerics; /// <summary> /// Sparse matrix tests. /// </summary> public class SparseMatrixTests : MatrixTests { /// <summary> /// Creates a matrix for the given number of rows and columns. /// </summary> /// <param name="rows">The number of rows.</param> /// <param name="columns">The number of columns.</param> /// <returns>A matrix with the given dimensions.</returns> protected override Matrix<Complex32> CreateMatrix(int rows, int columns) { return new SparseMatrix(rows, columns); } /// <summary> /// Creates a matrix from a 2D array. /// </summary> /// <param name="data">The 2D array to create this matrix from.</param> /// <returns>A matrix with the given values.</returns> protected override Matrix<Complex32> CreateMatrix(Complex32[,] data) { return SparseMatrix.OfArray(data); } /// <summary> /// Can create a matrix form array. /// </summary> [Test] public void CanCreateMatrixFrom1DArray() { var testData = new Dictionary<string, Matrix<Complex32>> { {"Singular3x3", SparseMatrix.OfColumnMajor(3, 3, new[] {new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(2.0f, 1), new Complex32(2.0f, 1), new Complex32(2.0f, 1)})}, {"Square3x3", SparseMatrix.OfColumnMajor(3, 3, new[] {new Complex32(-1.1f, 1), Complex32.Zero, new Complex32(-4.4f, 1), new Complex32(-2.2f, 1), new Complex32(1.1f, 1), new Complex32(5.5f, 1), new Complex32(-3.3f, 1), new Complex32(2.2f, 1), new Complex32(6.6f, 1)})}, {"Square4x4", SparseMatrix.OfColumnMajor(4, 4, new[] {new Complex32(-1.1f, 1), Complex32.Zero, new Complex32(1.0f, 1), new Complex32(-4.4f, 1), new Complex32(-2.2f, 1), new Complex32(1.1f, 1), new Complex32(2.1f, 1), new Complex32(5.5f, 1), new Complex32(-3.3f, 1), new Complex32(2.2f, 1), new Complex32(6.2f, 1), new Complex32(6.6f, 1), new Complex32(-4.4f, 1), new Complex32(3.3f, 1), new Complex32(4.3f, 1), new Complex32(-7.7f, 1)})}, {"Tall3x2", SparseMatrix.OfColumnMajor(3, 2, new[] {new Complex32(-1.1f, 1), Complex32.Zero, new Complex32(-4.4f, 1), new Complex32(-2.2f, 1), new Complex32(1.1f, 1), new Complex32(5.5f, 1)})}, {"Wide2x3", SparseMatrix.OfColumnMajor(2, 3, new[] {new Complex32(-1.1f, 1), Complex32.Zero, new Complex32(-2.2f, 1), new Complex32(1.1f, 1), new Complex32(-3.3f, 1), new Complex32(2.2f, 1)})} }; foreach (var name in testData.Keys) { Assert.AreEqual(TestMatrices[name], testData[name]); } } /// <summary> /// Matrix from array is a copy. /// </summary> [Test] public void MatrixFrom1DArrayIsCopy() { // Sparse Matrix copies values from Complex32[], but no remember reference. var data = new[] {new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(1.0f, 1), new Complex32(2.0f, 1), new Complex32(2.0f, 1), new Complex32(2.0f, 1)}; var matrix = SparseMatrix.OfColumnMajor(3, 3, data); matrix[0, 0] = new Complex32(10.0f, 1); Assert.AreNotEqual(new Complex32(10.0f, 1), data[0]); } /// <summary> /// Matrix from two-dimensional array is a copy. /// </summary> [Test] public void MatrixFrom2DArrayIsCopy() { var matrix = SparseMatrix.OfArray(TestData2D["Singular3x3"]); matrix[0, 0] = new Complex32(10.0f, 1); Assert.AreEqual(new Complex32(1.0f, 1), TestData2D["Singular3x3"][0, 0]); } /// <summary> /// Can create a matrix from two-dimensional array. /// </summary> /// <param name="name">Matrix name.</param> [TestCase("Singular3x3")] [TestCase("Singular4x4")] [TestCase("Square3x3")] [TestCase("Square4x4")] [TestCase("Tall3x2")] [TestCase("Wide2x3")] public void CanCreateMatrixFrom2DArray(string name) { var matrix = SparseMatrix.OfArray(TestData2D[name]); for (var i = 0; i < TestData2D[name].GetLength(0); i++) { for (var j = 0; j < TestData2D[name].GetLength(1); j++) { Assert.AreEqual(TestData2D[name][i, j], matrix[i, j]); } } } /// <summary> /// Can create an identity matrix. /// </summary> [Test] public void CanCreateIdentity() { var matrix = SparseMatrix.CreateIdentity(5); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { Assert.AreEqual(i == j ? Complex32.One : Complex32.Zero, matrix[i, j]); } } } /// <summary> /// Identity with wrong order throws <c>ArgumentOutOfRangeException</c>. /// </summary> /// <param name="order">The size of the square matrix</param> [TestCase(0)] [TestCase(-1)] public void IdentityWithWrongOrderThrowsArgumentOutOfRangeException(int order) { Assert.That(() => SparseMatrix.CreateIdentity(order), Throws.TypeOf<ArgumentOutOfRangeException>()); } /// <summary> /// Can create a large sparse matrix /// </summary> [Test] public void CanCreateLargeSparseMatrix() { var matrix = new SparseMatrix(500, 1000); var nonzero = 0; var rnd = new System.Random(0); for (var i = 0; i < matrix.RowCount; i++) { for (var j = 0; j < matrix.ColumnCount; j++) { var value = rnd.Next(10)*rnd.Next(10)*rnd.Next(10)*rnd.Next(10)*rnd.Next(10); if (value != 0) { nonzero++; } matrix[i, j] = value; } } Assert.AreEqual(matrix.NonZerosCount, nonzero); } /// <summary> /// Test whether order matters when adding sparse matrices. /// </summary> [Test] public void CanAddSparseMatricesBothWays() { var m1 = new SparseMatrix(1, 3); var m2 = SparseMatrix.OfArray(new Complex32[,] { { 0, 1, 1 } }); var sum1 = m1 + m2; var sum2 = m2 + m1; Assert.IsTrue(sum1.Equals(m2)); Assert.IsTrue(sum1.Equals(sum2)); var sparseResult = new SparseMatrix(1, 3); sparseResult.Add(m2, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new Complex32[,] { { 0, 1, 1 } }); sparseResult.Add(m1, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new Complex32[,] { { 0, 1, 1 } }); m1.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(sum1)); sparseResult = SparseMatrix.OfArray(new Complex32[,] { { 0, 1, 1 } }); sparseResult.Add(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(2*sum1)); var denseResult = new DenseMatrix(1, 3); denseResult.Add(m2, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); denseResult = DenseMatrix.OfArray(new Complex32[,] {{0, 1, 1}}); denseResult.Add(m1, denseResult); Assert.IsTrue(denseResult.Equals(sum1)); var m3 = DenseMatrix.OfArray(new Complex32[,] {{0, 1, 1}}); var sum3 = m1 + m3; var sum4 = m3 + m1; Assert.IsTrue(sum3.Equals(m3)); Assert.IsTrue(sum3.Equals(sum4)); } /// <summary> /// Test whether order matters when subtracting sparse matrices. /// </summary> [Test] public void CanSubtractSparseMatricesBothWays() { var m1 = new SparseMatrix(1, 3); var m2 = SparseMatrix.OfArray(new Complex32[,] { { 0, 1, 1 } }); var diff1 = m1 - m2; var diff2 = m2 - m1; Assert.IsTrue(diff1.Equals(m2.Negate())); Assert.IsTrue(diff1.Equals(diff2.Negate())); var sparseResult = new SparseMatrix(1, 3); sparseResult.Subtract(m2, sparseResult); Assert.IsTrue(sparseResult.Equals(diff1)); sparseResult = SparseMatrix.OfArray(new Complex32[,] { { 0, 1, 1 } }); sparseResult.Subtract(m1, sparseResult); Assert.IsTrue(sparseResult.Equals(diff2)); sparseResult = SparseMatrix.OfArray(new Complex32[,] { { 0, 1, 1 } }); m1.Subtract(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(diff1)); sparseResult = SparseMatrix.OfArray(new Complex32[,] { { 0, 1, 1 } }); sparseResult.Subtract(sparseResult, sparseResult); Assert.IsTrue(sparseResult.Equals(0*diff1)); var denseResult = new DenseMatrix(1, 3); denseResult.Subtract(m2, denseResult); Assert.IsTrue(denseResult.Equals(diff1)); denseResult = DenseMatrix.OfArray(new Complex32[,] {{0, 1, 1}}); denseResult.Subtract(m1, denseResult); Assert.IsTrue(denseResult.Equals(diff2)); var m3 = DenseMatrix.OfArray(new Complex32[,] {{0, 1, 1}}); var diff3 = m1 - m3; var diff4 = m3 - m1; Assert.IsTrue(diff3.Equals(m3.Negate())); Assert.IsTrue(diff3.Equals(diff4.Negate())); } /// <summary> /// Test whether we can create a large sparse matrix /// </summary> [Test] public void CanCreateLargeMatrix() { const int Order = 1000000; var matrix = new SparseMatrix(Order); Assert.AreEqual(Order, matrix.RowCount); Assert.AreEqual(Order, matrix.ColumnCount); Assert.DoesNotThrow(() => matrix[0, 0] = 1); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.IO; using System.IO.MemoryMappedFiles; using System.Diagnostics; using System.Collections.Generic; using System.Reflection.Metadata; using System.Reflection.Metadata.Ecma335; using System.Reflection.PortableExecutable; using Internal.TypeSystem; using Internal.TypeSystem.Ecma; using Internal.IL; namespace ILCompiler { public partial class CompilerTypeSystemContext : MetadataTypeSystemContext, IMetadataStringDecoderProvider { private MetadataFieldLayoutAlgorithm _metadataFieldLayoutAlgorithm = new CompilerMetadataFieldLayoutAlgorithm(); private MetadataRuntimeInterfacesAlgorithm _metadataRuntimeInterfacesAlgorithm = new MetadataRuntimeInterfacesAlgorithm(); private ArrayOfTRuntimeInterfacesAlgorithm _arrayOfTRuntimeInterfacesAlgorithm; private MetadataVirtualMethodAlgorithm _virtualMethodAlgorithm = new MetadataVirtualMethodAlgorithm(); private CachingVirtualMethodEnumerationAlgorithm _virtualMethodEnumAlgorithm = new CachingVirtualMethodEnumerationAlgorithm(); private DelegateVirtualMethodEnumerationAlgorithm _delegateVirtualMethodEnumAlgorithm = new DelegateVirtualMethodEnumerationAlgorithm(); private MetadataStringDecoder _metadataStringDecoder; private class ModuleData { public string SimpleName; public string FilePath; public EcmaModule Module; public MemoryMappedViewAccessor MappedViewAccessor; } private class ModuleHashtable : LockFreeReaderHashtable<EcmaModule, ModuleData> { protected override int GetKeyHashCode(EcmaModule key) { return key.GetHashCode(); } protected override int GetValueHashCode(ModuleData value) { return value.Module.GetHashCode(); } protected override bool CompareKeyToValue(EcmaModule key, ModuleData value) { return Object.ReferenceEquals(key, value.Module); } protected override bool CompareValueToValue(ModuleData value1, ModuleData value2) { return Object.ReferenceEquals(value1.Module, value2.Module); } protected override ModuleData CreateValueFromKey(EcmaModule key) { Debug.Assert(false, "CreateValueFromKey not supported"); return null; } } private ModuleHashtable _moduleHashtable = new ModuleHashtable(); private class SimpleNameHashtable : LockFreeReaderHashtable<string, ModuleData> { StringComparer _comparer = StringComparer.OrdinalIgnoreCase; protected override int GetKeyHashCode(string key) { return _comparer.GetHashCode(key); } protected override int GetValueHashCode(ModuleData value) { return _comparer.GetHashCode(value.SimpleName); } protected override bool CompareKeyToValue(string key, ModuleData value) { return _comparer.Equals(key, value.SimpleName); } protected override bool CompareValueToValue(ModuleData value1, ModuleData value2) { return _comparer.Equals(value1.SimpleName, value2.SimpleName); } protected override ModuleData CreateValueFromKey(string key) { Debug.Assert(false, "CreateValueFromKey not supported"); return null; } } private SimpleNameHashtable _simpleNameHashtable = new SimpleNameHashtable(); private class DelegateInfoHashtable : LockFreeReaderHashtable<TypeDesc, DelegateInfo> { protected override int GetKeyHashCode(TypeDesc key) { return key.GetHashCode(); } protected override int GetValueHashCode(DelegateInfo value) { return value.Type.GetHashCode(); } protected override bool CompareKeyToValue(TypeDesc key, DelegateInfo value) { return Object.ReferenceEquals(key, value.Type); } protected override bool CompareValueToValue(DelegateInfo value1, DelegateInfo value2) { return Object.ReferenceEquals(value1.Type, value2.Type); } protected override DelegateInfo CreateValueFromKey(TypeDesc key) { return new DelegateInfo(key); } } private DelegateInfoHashtable _delegateInfoHashtable = new DelegateInfoHashtable(); public CompilerTypeSystemContext(TargetDetails details) : base(details) { } public IReadOnlyDictionary<string, string> InputFilePaths { get; set; } public IReadOnlyDictionary<string, string> ReferenceFilePaths { get; set; } public override ModuleDesc ResolveAssembly(System.Reflection.AssemblyName name, bool throwIfNotFound) { return GetModuleForSimpleName(name.Name, throwIfNotFound); } public EcmaModule GetModuleForSimpleName(string simpleName, bool throwIfNotFound = true) { ModuleData existing; if (_simpleNameHashtable.TryGetValue(simpleName, out existing)) return existing.Module; string filePath; if (!InputFilePaths.TryGetValue(simpleName, out filePath)) { if (!ReferenceFilePaths.TryGetValue(simpleName, out filePath)) { if (throwIfNotFound) throw new FileNotFoundException("Assembly not found: " + simpleName); return null; } } return AddModule(filePath, simpleName); } public EcmaModule GetModuleFromPath(string filePath) { // This method is not expected to be called frequently. Linear search is acceptable. foreach (var entry in ModuleHashtable.Enumerator.Get(_moduleHashtable)) { if (entry.FilePath == filePath) return entry.Module; } return AddModule(filePath, null); } private unsafe static PEReader OpenPEFile(string filePath, out MemoryMappedViewAccessor mappedViewAccessor) { // System.Reflection.Metadata has heuristic that tries to save virtual address space. This heuristic does not work // well for us since it can make IL access very slow (call to OS for each method IL query). We will map the file // ourselves to get the desired performance characteristics reliably. FileStream fileStream = null; MemoryMappedFile mappedFile = null; MemoryMappedViewAccessor accessor = null; try { // Create stream because CreateFromFile(string, ...) uses FileShare.None which is too strict fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read, FileShare.Read, 4096, false); mappedFile = MemoryMappedFile.CreateFromFile( fileStream, null, fileStream.Length, MemoryMappedFileAccess.Read, HandleInheritability.None, true); accessor = mappedFile.CreateViewAccessor(0, 0, MemoryMappedFileAccess.Read); var safeBuffer = accessor.SafeMemoryMappedViewHandle; var peReader = new PEReader((byte*)safeBuffer.DangerousGetHandle(), (int)safeBuffer.ByteLength); // MemoryMappedFile does not need to be kept around. MemoryMappedViewAccessor is enough. mappedViewAccessor = accessor; accessor = null; return peReader; } finally { if (accessor != null) accessor.Dispose(); if (mappedFile != null) mappedFile.Dispose(); if (fileStream != null) fileStream.Dispose(); } } private EcmaModule AddModule(string filePath, string expectedSimpleName) { MemoryMappedViewAccessor mappedViewAccessor = null; PdbSymbolReader pdbReader = null; try { PEReader peReader = OpenPEFile(filePath, out mappedViewAccessor); pdbReader = OpenAssociatedSymbolFile(filePath); EcmaModule module = EcmaModule.Create(this, peReader, pdbReader); MetadataReader metadataReader = module.MetadataReader; string simpleName = metadataReader.GetString(metadataReader.GetAssemblyDefinition().Name); if (expectedSimpleName != null && !simpleName.Equals(expectedSimpleName, StringComparison.OrdinalIgnoreCase)) throw new FileNotFoundException("Assembly name does not match filename " + filePath); ModuleData moduleData = new ModuleData() { SimpleName = simpleName, FilePath = filePath, Module = module, MappedViewAccessor = mappedViewAccessor }; lock (this) { ModuleData actualModuleData = _simpleNameHashtable.AddOrGetExisting(moduleData); if (actualModuleData != moduleData) { if (actualModuleData.FilePath != filePath) throw new FileNotFoundException("Module with same simple name already exists " + filePath); return actualModuleData.Module; } mappedViewAccessor = null; // Ownership has been transfered pdbReader = null; // Ownership has been transferred _moduleHashtable.AddOrGetExisting(moduleData); } return module; } finally { if (mappedViewAccessor != null) mappedViewAccessor.Dispose(); if (pdbReader != null) pdbReader.Dispose(); } } public DelegateInfo GetDelegateInfo(TypeDesc delegateType) { return _delegateInfoHashtable.GetOrCreateValue(delegateType); } public override FieldLayoutAlgorithm GetLayoutAlgorithmForType(DefType type) { return _metadataFieldLayoutAlgorithm; } protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForNonPointerArrayType(ArrayType type) { if (_arrayOfTRuntimeInterfacesAlgorithm == null) { _arrayOfTRuntimeInterfacesAlgorithm = new ArrayOfTRuntimeInterfacesAlgorithm(SystemModule.GetKnownType("System", "Array`1")); } return _arrayOfTRuntimeInterfacesAlgorithm; } protected override RuntimeInterfacesAlgorithm GetRuntimeInterfacesAlgorithmForDefType(DefType type) { return _metadataRuntimeInterfacesAlgorithm; } public override VirtualMethodAlgorithm GetVirtualMethodAlgorithmForType(TypeDesc type) { Debug.Assert(!type.IsArray, "Wanted to call GetClosestMetadataType?"); return _virtualMethodAlgorithm; } public override VirtualMethodEnumerationAlgorithm GetVirtualMethodEnumerationAlgorithmForType(TypeDesc type) { Debug.Assert(!type.IsArray, "Wanted to call GetClosestMetadataType?"); if (type.IsDelegate) return _delegateVirtualMethodEnumAlgorithm; return _virtualMethodEnumAlgorithm; } protected override Instantiation ConvertInstantiationToCanonForm(Instantiation instantiation, CanonicalFormKind kind, out bool changed) { return RuntimeDeterminedCanonicalizationAlgorithm.ConvertInstantiationToCanonForm(instantiation, kind, out changed); } protected override TypeDesc ConvertToCanon(TypeDesc typeToConvert, CanonicalFormKind kind) { return RuntimeDeterminedCanonicalizationAlgorithm.ConvertToCanon(typeToConvert, kind); } protected override TypeDesc ConvertToCanon(TypeDesc typeToConvert, ref CanonicalFormKind kind) { return RuntimeDeterminedCanonicalizationAlgorithm.ConvertToCanon(typeToConvert, ref kind); } public MetadataStringDecoder GetMetadataStringDecoder() { if (_metadataStringDecoder == null) _metadataStringDecoder = new CachingMetadataStringDecoder(0x10000); // TODO: Tune the size return _metadataStringDecoder; } protected override bool ComputeHasGCStaticBase(FieldDesc field) { Debug.Assert(field.IsStatic); TypeDesc fieldType = field.FieldType; if (fieldType.IsValueType) return ((DefType)fieldType).ContainsGCPointers; else return fieldType.IsGCPointer; } // // Symbols // private PdbSymbolReader OpenAssociatedSymbolFile(string peFilePath) { // Assume that the .pdb file is next to the binary var pdbFilename = Path.ChangeExtension(peFilePath, ".pdb"); if (!File.Exists(pdbFilename)) return null; // Try to open the symbol file as portable pdb first PdbSymbolReader reader = PortablePdbSymbolReader.TryOpen(pdbFilename, GetMetadataStringDecoder()); if (reader == null) { // Fallback to the diasymreader for non-portable pdbs reader = UnmanagedPdbSymbolReader.TryOpenSymbolReaderForMetadataFile(peFilePath); } return reader; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace System.Reflection.Emit { using System; using System.Threading; using System.Security.Permissions; using System.Diagnostics.Contracts; [System.Runtime.InteropServices.ComVisible(true)] public struct OpCode { // // Use packed bitfield for flags to avoid code bloat // internal const int OperandTypeMask = 0x1F; // 000000000000000000000000000XXXXX internal const int FlowControlShift = 5; // 00000000000000000000000XXXX00000 internal const int FlowControlMask = 0x0F; internal const int OpCodeTypeShift = 9; // 00000000000000000000XXX000000000 internal const int OpCodeTypeMask = 0x07; internal const int StackBehaviourPopShift = 12; // 000000000000000XXXXX000000000000 internal const int StackBehaviourPushShift = 17; // 0000000000XXXXX00000000000000000 internal const int StackBehaviourMask = 0x1F; internal const int SizeShift = 22; // 00000000XX0000000000000000000000 internal const int SizeMask = 0x03; internal const int EndsUncondJmpBlkFlag = 0x01000000; // 0000000X000000000000000000000000 // unused // 0000XXX0000000000000000000000000 internal const int StackChangeShift = 28; // XXXX0000000000000000000000000000 #if FEATURE_CORECLR private OpCodeValues m_value; private int m_flags; internal OpCode(OpCodeValues value, int flags) { m_value = value; m_flags = flags; } internal bool EndsUncondJmpBlk() { return (m_flags & EndsUncondJmpBlkFlag) != 0; } internal int StackChange() { return (m_flags >> StackChangeShift); } public OperandType OperandType { get { return (OperandType)(m_flags & OperandTypeMask); } } public FlowControl FlowControl { get { return (FlowControl)((m_flags >> FlowControlShift) & FlowControlMask); } } public OpCodeType OpCodeType { get { return (OpCodeType)((m_flags >> OpCodeTypeShift) & OpCodeTypeMask); } } public StackBehaviour StackBehaviourPop { get { return (StackBehaviour)((m_flags >> StackBehaviourPopShift) & StackBehaviourMask); } } public StackBehaviour StackBehaviourPush { get { return (StackBehaviour)((m_flags >> StackBehaviourPushShift) & StackBehaviourMask); } } public int Size { get { return (m_flags >> SizeShift) & SizeMask; } } public short Value { get { return (short)m_value; } } #else // FEATURE_CORECLR // // The exact layout is part of the legacy COM mscorlib surface, so it is // pretty much set in stone for desktop CLR. Ideally, we would use the packed // bit field like for CoreCLR, but that would be a breaking change. // // disable csharp compiler warning #0414: field assigned unused value #pragma warning disable 0414 private String m_stringname; // not used - computed lazily #pragma warning restore 0414 private StackBehaviour m_pop; private StackBehaviour m_push; private OperandType m_operand; private OpCodeType m_type; private int m_size; private byte m_s1; private byte m_s2; private FlowControl m_ctrl; // Specifies whether the current instructions causes the control flow to // change unconditionally. private bool m_endsUncondJmpBlk; // Specifies the stack change that the current instruction causes not // taking into account the operand dependant stack changes. private int m_stackChange; internal OpCode(OpCodeValues value, int flags) { m_stringname = null; // computed lazily m_pop = (StackBehaviour)((flags >> StackBehaviourPopShift) & StackBehaviourMask); m_push = (StackBehaviour)((flags >> StackBehaviourPushShift) & StackBehaviourMask); m_operand = (OperandType)(flags & OperandTypeMask); m_type = (OpCodeType)((flags >> OpCodeTypeShift) & OpCodeTypeMask); m_size = (flags >> SizeShift) & SizeMask; m_s1 = (byte)((int)value >> 8); m_s2 = (byte)(int)value; m_ctrl = (FlowControl)((flags >> FlowControlShift) & FlowControlMask); m_endsUncondJmpBlk = (flags & EndsUncondJmpBlkFlag) != 0; m_stackChange = (flags >> StackChangeShift); } internal bool EndsUncondJmpBlk() { return m_endsUncondJmpBlk; } internal int StackChange() { return m_stackChange; } public OperandType OperandType { get { return (m_operand); } } public FlowControl FlowControl { get { return (m_ctrl); } } public OpCodeType OpCodeType { get { return (m_type); } } public StackBehaviour StackBehaviourPop { get { return (m_pop); } } public StackBehaviour StackBehaviourPush { get { return (m_push); } } public int Size { get { return (m_size); } } public short Value { get { if (m_size == 2) return (short)(m_s1 << 8 | m_s2); return (short)m_s2; } } #endif // FEATURE_CORECLR private static volatile string[] g_nameCache; public String Name { get { if (Size == 0) return null; // Create and cache the opcode names lazily. They should be rarely used (only for logging, etc.) // Note that we do not any locks here because of we always get the same names. The last one wins. string[] nameCache = g_nameCache; if (nameCache == null) { nameCache = new String[0x11f]; g_nameCache = nameCache; } OpCodeValues opCodeValue = (OpCodeValues)(ushort)Value; int idx = (int)opCodeValue; if (idx > 0xFF) { if (idx >= 0xfe00 && idx <= 0xfe1e) { // Transform two byte opcode value to lower range that's suitable // for array index idx = 0x100 + (idx - 0xfe00); } else { // Unknown opcode return null; } } String name = Volatile.Read(ref nameCache[idx]); if (name != null) return name; // Create ilasm style name from the enum value name. name = Enum.GetName(typeof(OpCodeValues), opCodeValue).ToLowerInvariant().Replace("_", "."); Volatile.Write(ref nameCache[idx], name); return name; } } [Pure] public override bool Equals(Object obj) { if (obj is OpCode) return Equals((OpCode)obj); else return false; } [Pure] public bool Equals(OpCode obj) { return obj.Value == Value; } [Pure] public static bool operator ==(OpCode a, OpCode b) { return a.Equals(b); } [Pure] public static bool operator !=(OpCode a, OpCode b) { return !(a == b); } public override int GetHashCode() { return Value; } public override String ToString() { return Name; } } }
// 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. //--------------------------------------------------------------------------- // // Description: InputBamlStreamList class // It enumerates all the baml streams in the input file for parsing // //--------------------------------------------------------------------------- using System; using System.IO; using System.Globalization; using System.Runtime.InteropServices; using System.Collections; using System.Reflection; using System.Diagnostics; using System.Resources; namespace BamlLocalization { /// <summary> /// Class that enumerates all the baml streams in the input file /// </summary> internal class InputBamlStreamList { /// <summary> /// constructor /// </summary> internal InputBamlStreamList(LocBamlOptions options) { _bamlStreams = new ArrayList(); switch(options.InputType) { case FileType.BAML: { _bamlStreams.Add( new BamlStream( Path.GetFileName(options.Input), File.OpenRead(options.Input) ) ); break; } case FileType.RESOURCES: { using (ResourceReader resourceReader = new ResourceReader(options.Input)) { // enumerate all bamls in a resources EnumerateBamlInResources(resourceReader, options.Input); } break; } case FileType.EXE: case FileType.DLL: { // for a dll, it is the same idea Assembly assembly = Assembly.LoadFrom(options.Input); foreach (string resourceName in assembly.GetManifestResourceNames()) { ResourceLocation resourceLocation = assembly.GetManifestResourceInfo(resourceName).ResourceLocation; // if this resource is in another assemlby, we will skip it if ((resourceLocation & ResourceLocation.ContainedInAnotherAssembly) != 0) { continue; // in resource assembly, we don't have resource that is contained in another assembly } Stream resourceStream = assembly.GetManifestResourceStream(resourceName); using (ResourceReader reader = new ResourceReader(resourceStream)) { EnumerateBamlInResources(reader, resourceName); } } break; } default: { Debug.Assert(false, "Not supported type"); break; } } } /// <summary> /// return the number of baml streams found /// </summary> internal int Count { get{return _bamlStreams.Count;} } /// <summary> /// Gets the baml stream in the input file through indexer /// </summary> internal BamlStream this[int i] { get { return (BamlStream) _bamlStreams[i];} } /// <summary> /// Close the baml streams enumerated /// </summary> internal void Close() { for (int i = 0; i < _bamlStreams.Count; i++) { ((BamlStream) _bamlStreams[i]).Close(); } } //-------------------------------- // private function //-------------------------------- /// <summary> /// Enumerate baml streams in a resources file /// </summary> private void EnumerateBamlInResources(ResourceReader reader, string resourceName) { foreach (DictionaryEntry entry in reader) { string name = entry.Key as string; if (BamlStream.IsResourceEntryBamlStream(name, entry.Value)) { _bamlStreams.Add( new BamlStream( BamlStream.CombineBamlStreamName(resourceName, name), (Stream) entry.Value ) ); } } } ArrayList _bamlStreams; } /// <summary> /// BamlStream class which represents a baml stream /// </summary> internal class BamlStream { private string _name; private Stream _stream; /// <summary> /// constructor /// </summary> internal BamlStream(string name, Stream stream) { _name = name; _stream = stream; } /// <summary> /// name of the baml /// </summary> internal string Name { get { return _name;} } /// <summary> /// The actual Baml stream /// </summary> internal Stream Stream { get { return _stream;} } /// <summary> /// close the stream /// </summary> internal void Close() { if (_stream != null) { _stream.Close(); } } /// <summary> /// Helper method which determines whether a stream name and value pair indicates a baml stream /// </summary> internal static bool IsResourceEntryBamlStream(string name, object value) { string extension = Path.GetExtension(name); if (string.Compare( extension, "." + FileType.BAML.ToString(), true, CultureInfo.InvariantCulture ) == 0 ) { //it has .Baml at the end Type type = value.GetType(); if (typeof(Stream).IsAssignableFrom(type)) return true; } return false; } /// <summary> /// Combine baml stream name and resource name to uniquely identify a baml within a /// localization project /// </summary> internal static string CombineBamlStreamName(string resource, string bamlName) { Debug.Assert(resource != null && bamlName != null, "Resource name and baml name can't be null"); string suffix = Path.GetFileName(bamlName); string prefix = Path.GetFileName(resource); return prefix + LocBamlConst.BamlAndResourceSeperator + suffix; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CompositeModel3D.cs" company="Helix 3D Toolkit"> // http://helixtoolkit.codeplex.com, license: MIT // </copyright> // -------------------------------------------------------------------------------------------------------------------- namespace HelixToolkit.Wpf.SharpDX { using System.Collections.Generic; using System.Collections.Specialized; using System.Windows.Markup; using global::SharpDX; /// <summary> /// Represents a composite Model3D. /// </summary> [ContentProperty("Children")] public class CompositeModel3D : GeometryModel3D { private readonly ObservableElement3DCollection children; /// <summary> /// Initializes a new instance of the <see cref="CompositeModel3D" /> class. /// </summary> public CompositeModel3D() { this.children = new ObservableElement3DCollection(); this.children.CollectionChanged += this.ChildrenChanged; } /// <summary> /// Gets the children. /// </summary> /// <value> /// The children. /// </value> public ObservableElement3DCollection Children { get { return this.children; } } /// <summary> /// Attaches the specified host. /// </summary> /// <param name="host"> /// The host. /// </param> public override void Attach(IRenderHost host) { base.Attach(host); foreach (var model in this.Children) { if (model.Parent == null) { this.AddLogicalChild(model); } model.Attach(host); } } /// <summary> /// Detaches this instance. /// </summary> public override void Detach() { foreach (var model in this.Children) { model.Detach(); if (model.Parent == this) { this.RemoveLogicalChild(model); } } base.Detach(); } /// <summary> /// Compute hit-testing for all children /// </summary> public override bool HitTest(Ray ray, ref List<HitTestResult> hits) { bool hit = base.HitTest(ray, ref hits); foreach (var c in this.Children) { var hc = c as IHitable; if (hc != null) { var tc = c as ITransformable; if (tc != null) { tc.PushMatrix(this.modelMatrix); if (hc.HitTest(ray, ref hits)) { hit = true; } tc.PopMatrix(); } else { if (hc.HitTest(ray, ref hits)) { hit = true; } } } } return hit; } /// <summary> /// /// </summary> public override void Dispose() { this.Detach(); } /// <summary> /// Renders the specified context. /// </summary> /// <param name="context"> /// The context. /// </param> public override void Render(RenderContext context) { base.Render(context); // you mean like this? foreach (var c in this.Children) { var model = c as ITransformable; if (model != null) { // push matrix model.PushMatrix(this.modelMatrix); // render model c.Render(context); // pop matrix model.PopMatrix(); } else { c.Render(context); } } } /// <summary> /// Handles changes in the Children collection. /// </summary> /// <param name="sender"> /// The sender. /// </param> /// <param name="e"> /// The <see cref="NotifyCollectionChangedEventArgs"/> instance containing the event data. /// </param> private void ChildrenChanged(object sender, NotifyCollectionChangedEventArgs e) { switch (e.Action) { case NotifyCollectionChangedAction.Remove: case NotifyCollectionChangedAction.Replace: foreach (Model3D item in e.OldItems) { // todo: detach? // yes, always item.Detach(); if (item.Parent == this) { this.RemoveLogicalChild(item); } } break; } switch (e.Action) { case NotifyCollectionChangedAction.Add: case NotifyCollectionChangedAction.Replace: foreach (Model3D item in e.NewItems) { if (this.IsAttached) { // todo: attach? // yes, always // where to get a refrence to renderHost? // store it as private memeber of the class? if (item.Parent == null) { this.AddLogicalChild(item); } item.Attach(this.renderHost); } } break; } UpdateBounds(); } /// <summary> /// a Model3D does not have bounds, /// if you want to have a model with bounds, use GeometryModel3D instead: /// but this prevents the CompositeModel3D containg lights, etc. (Lights3D are Models3D, which do not have bounds) /// </summary> private void UpdateBounds() { var bb = this.Bounds; foreach (var item in this.Children) { var model = item as IBoundable; if (model != null) { bb = BoundingBox.Merge(bb, model.Bounds); } } this.Bounds = bb; } } }
#region License // // The Open Toolkit Library License // // Copyright (c) 2006 - 2010 the Open Toolkit library. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights to // use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of // the Software, and to permit persons to whom the Software is furnished to do // so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. // #endregion // Created by Erik Ylvisaker on 3/17/08. using System; using System.Collections.Generic; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Text; namespace OpenTK.Platform.MacOS { using Carbon; using Graphics; class CarbonGLNative : INativeWindow { #region Fields CarbonWindowInfo window; CarbonInput mInputDriver; static MacOSKeyMap Keymap = new MacOSKeyMap(); IntPtr uppHandler; string title = "OpenTK Window"; Rectangle bounds, clientRectangle; Rectangle windowedBounds; bool mIsDisposed = false; bool mExists = true; DisplayDevice mDisplayDevice; WindowAttributes mWindowAttrib; WindowClass mWindowClass; WindowPositionMethod mPositionMethod = WindowPositionMethod.CenterOnMainScreen; int mTitlebarHeight; private WindowBorder windowBorder = WindowBorder.Resizable; private WindowState windowState = WindowState.Normal; static Dictionary<IntPtr, WeakReference> mWindows = new Dictionary<IntPtr, WeakReference>(new IntPtrEqualityComparer()); KeyPressEventArgs mKeyPressArgs = new KeyPressEventArgs((char)0); bool mMouseIn = false; bool mIsActive = false; Icon mIcon; // Used to accumulate mouse motion when the cursor is hidden. float mouse_rel_x; float mouse_rel_y; #endregion #region AGL Device Hack static internal Dictionary<IntPtr, WeakReference> WindowRefMap { get { return mWindows; } } internal DisplayDevice TargetDisplayDevice { get { return mDisplayDevice; } } #endregion #region Constructors static CarbonGLNative() { Application.Initialize(); } CarbonGLNative() : this(WindowClass.Document, WindowAttributes.StandardDocument | WindowAttributes.StandardHandler | WindowAttributes.InWindowMenu | WindowAttributes.LiveResize) { } CarbonGLNative(WindowClass @class, WindowAttributes attrib) { mWindowClass = @class; mWindowAttrib = attrib; } public CarbonGLNative(int x, int y, int width, int height, string title, GraphicsMode mode, GameWindowFlags options, DisplayDevice device) { CreateNativeWindow(WindowClass.Document, WindowAttributes.StandardDocument | WindowAttributes.StandardHandler | WindowAttributes.InWindowMenu | WindowAttributes.LiveResize, new Rect((short)x, (short)y, (short)width, (short)height)); mDisplayDevice = device; } #endregion #region IDisposable public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { if (mIsDisposed) return; Debug.Print("Disposing of CarbonGLNative window."); CursorVisible = true; API.DisposeWindow(window.WindowRef); mIsDisposed = true; mExists = false; CG.SetLocalEventsSuppressionInterval(0.25); if (disposing) { mWindows.Remove(window.WindowRef); window.Dispose(); window = null; } DisposeUPP(); Disposed(this, EventArgs.Empty); } ~CarbonGLNative() { Dispose(false); } #endregion #region Private Members void DisposeUPP() { if (uppHandler != IntPtr.Zero) { //API.RemoveEventHandler(uppHandler); //API.DisposeEventHandlerUPP(uppHandler); } uppHandler = IntPtr.Zero; } void CreateNativeWindow(WindowClass @class, WindowAttributes attrib, Rect r) { Debug.Print("Creating window..."); Debug.Indent(); IntPtr windowRef = API.CreateNewWindow(@class, attrib, r); API.SetWindowTitle(windowRef, title); window = new CarbonWindowInfo(windowRef, true, false); SetLocation(r.X, r.Y); SetSize(r.Width, r.Height); Debug.Unindent(); Debug.Print("Created window."); mWindows.Add(windowRef, new WeakReference(this)); LoadSize(); Rect titleSize = API.GetWindowBounds(window.WindowRef, WindowRegionCode.TitleBarRegion); mTitlebarHeight = titleSize.Height; Debug.Print("Titlebar size: {0}", titleSize); ConnectEvents(); System.Diagnostics.Debug.Print("Attached window events."); } void ConnectEvents() { mInputDriver = new CarbonInput(); EventTypeSpec[] eventTypes = new EventTypeSpec[] { new EventTypeSpec(EventClass.Window, WindowEventKind.WindowClose), new EventTypeSpec(EventClass.Window, WindowEventKind.WindowClosed), new EventTypeSpec(EventClass.Window, WindowEventKind.WindowBoundsChanged), new EventTypeSpec(EventClass.Window, WindowEventKind.WindowActivate), new EventTypeSpec(EventClass.Window, WindowEventKind.WindowDeactivate), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseDown), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseUp), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseMoved), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseDragged), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseEntered), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.MouseExited), //new EventTypeSpec(EventClass.Mouse, MouseEventKind.WheelMoved), //new EventTypeSpec(EventClass.Keyboard, KeyboardEventKind.RawKeyDown), //new EventTypeSpec(EventClass.Keyboard, KeyboardEventKind.RawKeyRepeat), //new EventTypeSpec(EventClass.Keyboard, KeyboardEventKind.RawKeyUp), //new EventTypeSpec(EventClass.Keyboard, KeyboardEventKind.RawKeyModifiersChanged), }; MacOSEventHandler handler = EventHandler; uppHandler = API.NewEventHandlerUPP(handler); API.InstallWindowEventHandler(window.WindowRef, uppHandler, eventTypes, window.WindowRef, IntPtr.Zero); Application.WindowEventHandler = this; } void Activate() { API.SelectWindow(window.WindowRef); } void Show() { IntPtr parent = IntPtr.Zero; API.ShowWindow(window.WindowRef); API.RepositionWindow(window.WindowRef, parent, WindowPositionMethod); API.SelectWindow(window.WindowRef); } void Hide() { API.HideWindow(window.WindowRef); } internal void SetFullscreen(AglContext context) { windowedBounds = bounds; int width, height; context.SetFullScreen(window, out width, out height); Debug.Print("Prev Size: {0}, {1}", Width, Height); clientRectangle.Size = new Size(width, height); Debug.Print("New Size: {0}, {1}", Width, Height); // TODO: if we go full screen we need to make this use the device specified. bounds = mDisplayDevice.Bounds; windowState = WindowState.Fullscreen; } internal void UnsetFullscreen(AglContext context) { context.UnsetFullScreen(window); Debug.Print("Telling Carbon to reset window state to " + windowState.ToString()); SetCarbonWindowState(); SetSize((short)windowedBounds.Width, (short)windowedBounds.Height); } bool IsDisposed { get { return mIsDisposed; } } WindowPositionMethod WindowPositionMethod { get { return mPositionMethod; } set { mPositionMethod = value; } } internal OSStatus DispatchEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) { switch (evt.EventClass) { case EventClass.Window: return ProcessWindowEvent(inCaller, inEvent, evt, userData); case EventClass.Mouse: return ProcessMouseEvent(inCaller, inEvent, evt, userData); case EventClass.Keyboard: return ProcessKeyboardEvent(inCaller, inEvent, evt, userData); default: return OSStatus.EventNotHandled; } } protected static OSStatus EventHandler(IntPtr inCaller, IntPtr inEvent, IntPtr userData) { if (mWindows.ContainsKey(userData) == false) { // Bail out if the window passed in is not actually our window. // I think this happens if using winforms with a GameWindow sometimes. return OSStatus.EventNotHandled; } WeakReference reference = mWindows[userData]; if (reference.IsAlive == false) { // Bail out if the CarbonGLNative window has been garbage collected. mWindows.Remove(userData); return OSStatus.EventNotHandled; } CarbonGLNative window = (CarbonGLNative)reference.Target; if (window == null) { Debug.WriteLine("Window for event not found."); return OSStatus.EventNotHandled; } EventInfo evt = new EventInfo(inEvent); return window.DispatchEvent(inCaller, inEvent, evt, userData); } private OSStatus ProcessKeyboardEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) { System.Diagnostics.Debug.Assert(evt.EventClass == EventClass.Keyboard); MacOSKeyCode code = (MacOSKeyCode)0; char charCode = '\0'; switch (evt.KeyboardEventKind) { case KeyboardEventKind.RawKeyDown: case KeyboardEventKind.RawKeyRepeat: case KeyboardEventKind.RawKeyUp: GetCharCodes(inEvent, out code, out charCode); mKeyPressArgs.KeyChar = charCode; break; } switch (evt.KeyboardEventKind) { case KeyboardEventKind.RawKeyRepeat: if (InputDriver.Keyboard[0].KeyRepeat) goto case KeyboardEventKind.RawKeyDown; break; case KeyboardEventKind.RawKeyDown: { OpenTK.Input.Key key; if (Keymap.TryGetValue(code, out key)) { InputDriver.Keyboard[0][key] = true; OnKeyPress(mKeyPressArgs); } return OSStatus.NoError; } case KeyboardEventKind.RawKeyUp: { OpenTK.Input.Key key; if (Keymap.TryGetValue(code, out key)) { InputDriver.Keyboard[0][key] = false; } return OSStatus.NoError; } case KeyboardEventKind.RawKeyModifiersChanged: ProcessModifierKey(inEvent); return OSStatus.NoError; } return OSStatus.EventNotHandled; } private OSStatus ProcessWindowEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) { System.Diagnostics.Debug.Assert(evt.EventClass == EventClass.Window); switch (evt.WindowEventKind) { case WindowEventKind.WindowClose: CancelEventArgs cancel = new CancelEventArgs(); OnClosing(cancel); if (cancel.Cancel) return OSStatus.NoError; else return OSStatus.EventNotHandled; case WindowEventKind.WindowClosed: mExists = false; OnClosed(); return OSStatus.NoError; case WindowEventKind.WindowBoundsChanged: int thisWidth = Width; int thisHeight = Height; int thisX = X; int thisY = Y; LoadSize(); if (thisX != X || thisY != Y) Move(this, EventArgs.Empty); if (thisWidth != Width || thisHeight != Height) Resize(this, EventArgs.Empty); return OSStatus.EventNotHandled; case WindowEventKind.WindowActivate: OnActivate(); return OSStatus.EventNotHandled; case WindowEventKind.WindowDeactivate: OnDeactivate(); return OSStatus.EventNotHandled; default: Debug.Print("{0}", evt); return OSStatus.EventNotHandled; } } protected OSStatus ProcessMouseEvent(IntPtr inCaller, IntPtr inEvent, EventInfo evt, IntPtr userData) { System.Diagnostics.Debug.Assert(evt.EventClass == EventClass.Mouse); MouseButton button = MouseButton.Primary; HIPoint pt = new HIPoint(); HIPoint screenLoc = new HIPoint(); IntPtr thisEventWindow; API.GetEventWindowRef(inEvent, out thisEventWindow); OSStatus err = API.GetEventMouseLocation(inEvent, out screenLoc); if (this.windowState == WindowState.Fullscreen) { pt = screenLoc; } else if (CursorVisible) { err = API.GetEventWindowMouseLocation(inEvent, out pt); pt.Y -= mTitlebarHeight; } else { err = API.GetEventMouseDelta(inEvent, out pt); pt.X += mouse_rel_x; pt.Y += mouse_rel_y; pt = ConfineMouseToWindow(thisEventWindow, pt); ResetMouseToWindowCenter(); mouse_rel_x = pt.X; mouse_rel_y = pt.Y; } if (err != OSStatus.NoError && err != OSStatus.EventParameterNotFound) { // this error comes up from the application event handler. throw new MacOSException(err); } Point mousePosInClient = new Point((int)pt.X, (int)pt.Y); CheckEnterLeaveEvents(thisEventWindow, mousePosInClient); switch (evt.MouseEventKind) { case MouseEventKind.MouseDown: case MouseEventKind.MouseUp: button = API.GetEventMouseButton(inEvent); bool pressed = evt.MouseEventKind == MouseEventKind.MouseDown; switch (button) { case MouseButton.Primary: InputDriver.Mouse[0][OpenTK.Input.MouseButton.Left] = pressed; break; case MouseButton.Secondary: InputDriver.Mouse[0][OpenTK.Input.MouseButton.Right] = pressed; break; case MouseButton.Tertiary: InputDriver.Mouse[0][OpenTK.Input.MouseButton.Middle] = pressed; break; } return OSStatus.NoError; case MouseEventKind.WheelMoved: float delta = API.GetEventMouseWheelDelta(inEvent); InputDriver.Mouse[0].WheelPrecise += delta; return OSStatus.NoError; case MouseEventKind.MouseMoved: case MouseEventKind.MouseDragged: if (this.windowState == WindowState.Fullscreen) { if (mousePosInClient.X != InputDriver.Mouse[0].X || mousePosInClient.Y != InputDriver.Mouse[0].Y) { InputDriver.Mouse[0].Position = mousePosInClient; } } else { // ignore clicks in the title bar if (pt.Y < 0) return OSStatus.EventNotHandled; if (mousePosInClient.X != InputDriver.Mouse[0].X || mousePosInClient.Y != InputDriver.Mouse[0].Y) { InputDriver.Mouse[0].Position = mousePosInClient; } } return OSStatus.EventNotHandled; default: Debug.Print("{0}", evt); return OSStatus.EventNotHandled; } } void ResetMouseToWindowCenter() { OpenTK.Input.Mouse.SetPosition( (Bounds.Left + Bounds.Right) / 2, (Bounds.Top + Bounds.Bottom) / 2); } private void CheckEnterLeaveEvents(IntPtr eventWindowRef, Point pt) { if (window == null) return; bool thisIn = eventWindowRef == window.WindowRef; if (pt.Y < 0) thisIn = false; if (thisIn != mMouseIn) { mMouseIn = thisIn; if (mMouseIn) OnMouseEnter(); else OnMouseLeave(); } } // Point in client (window) coordinates private HIPoint ConfineMouseToWindow(IntPtr window, HIPoint client) { if (client.X < 0) client.X = 0; if (client.X >= Width) client.X = Width - 1; if (client.Y < 0) client.Y = 0; if (client.Y >= Height) client.Y = Height - 1; return client; } private static void GetCharCodes(IntPtr inEvent, out MacOSKeyCode code, out char charCode) { code = API.GetEventKeyboardKeyCode(inEvent); charCode = API.GetEventKeyboardChar(inEvent); } private void ProcessModifierKey(IntPtr inEvent) { MacOSKeyModifiers modifiers = API.GetEventKeyModifiers(inEvent); bool caps = (modifiers & MacOSKeyModifiers.CapsLock) != 0 ? true : false; bool control = (modifiers & MacOSKeyModifiers.Control) != 0 ? true : false; bool command = (modifiers & MacOSKeyModifiers.Command) != 0 ? true : false; bool option = (modifiers & MacOSKeyModifiers.Option) != 0 ? true : false; bool shift = (modifiers & MacOSKeyModifiers.Shift) != 0 ? true : false; Debug.Print("Modifiers Changed: {0}", modifiers); Input.KeyboardDevice keyboard = InputDriver.Keyboard[0]; if (keyboard[OpenTK.Input.Key.AltLeft] ^ option) keyboard[OpenTK.Input.Key.AltLeft] = option; if (keyboard[OpenTK.Input.Key.ShiftLeft] ^ shift) keyboard[OpenTK.Input.Key.ShiftLeft] = shift; if (keyboard[OpenTK.Input.Key.WinLeft] ^ command) keyboard[OpenTK.Input.Key.WinLeft] = command; if (keyboard[OpenTK.Input.Key.ControlLeft] ^ control) keyboard[OpenTK.Input.Key.ControlLeft] = control; if (keyboard[OpenTK.Input.Key.CapsLock] ^ caps) keyboard[OpenTK.Input.Key.CapsLock] = caps; } Rect GetRegion() { Rect retval = API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion); return retval; } void SetLocation(short x, short y) { if (windowState == WindowState.Fullscreen) return; API.MoveWindow(window.WindowRef, x, y, false); } void SetSize(short width, short height) { if (WindowState == WindowState.Fullscreen) return; // The bounds of the window should be the size specified, but // API.SizeWindow sets the content region size. So // we reduce the size to get the correct bounds. width -= (short)(bounds.Width - clientRectangle.Width); height -= (short)(bounds.Height - clientRectangle.Height); API.SizeWindow(window.WindowRef, width, height, true); } void SetClientSize(short width, short height) { if (WindowState == WindowState.Fullscreen) return; API.SizeWindow(window.WindowRef, width, height, true); } private void LoadSize() { if (WindowState == WindowState.Fullscreen) return; Rect r = API.GetWindowBounds(window.WindowRef, WindowRegionCode.StructureRegion); bounds = new Rectangle(r.X, r.Y, r.Width, r.Height); r = API.GetWindowBounds(window.WindowRef, WindowRegionCode.GlobalPortRegion); clientRectangle = new Rectangle(0, 0, r.Width, r.Height); } #endregion #region INativeWindow Members public void ProcessEvents() { Application.ProcessEvents(); } public Point PointToClient(Point point) { Rect r = Carbon.API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion); return new Point(point.X - r.X, point.Y - r.Y); } public Point PointToScreen(Point point) { Rect r = Carbon.API.GetWindowBounds(window.WindowRef, WindowRegionCode.ContentRegion); return new Point(point.X + r.X, point.Y + r.Y); } public bool Exists { get { return mExists; } } public IWindowInfo WindowInfo { get { return window; } } public bool IsIdle { get { return true; } } public OpenTK.Input.IInputDriver InputDriver { get { return mInputDriver; } } public Icon Icon { get { return mIcon; } set { if (value != Icon) { SetIcon(value); mIcon = value; IconChanged(this, EventArgs.Empty); } } } private void SetIcon(Icon icon) { // The code for this function was adapted from Mono's // XplatUICarbon implementation, written by Geoff Norton // http://anonsvn.mono-project.com/viewvc/trunk/mcs/class/Managed.Windows.Forms/System.Windows.Forms/XplatUICarbon.cs?view=markup&pathrev=136932 if (icon == null) { API.RestoreApplicationDockTileImage(); } else { Bitmap bitmap; int size; IntPtr[] data; int index; bitmap = new Bitmap(128, 128); using (System.Drawing.Graphics g = System.Drawing.Graphics.FromImage(bitmap)) { g.DrawImage(icon.ToBitmap(), 0, 0, 128, 128); } index = 0; size = bitmap.Width * bitmap.Height; data = new IntPtr[size]; for (int y = 0; y < bitmap.Height; y++) { for (int x = 0; x < bitmap.Width; x++) { int pixel = bitmap.GetPixel(x, y).ToArgb(); if (BitConverter.IsLittleEndian) { byte a = (byte)((pixel >> 24) & 0xFF); byte r = (byte)((pixel >> 16) & 0xFF); byte g = (byte)((pixel >> 8) & 0xFF); byte b = (byte)(pixel & 0xFF); data[index++] = (IntPtr)(a + (r << 8) + (g << 16) + (b << 24)); } else { data[index++] = (IntPtr)pixel; } } } IntPtr provider = API.CGDataProviderCreateWithData(IntPtr.Zero, data, size * 4, IntPtr.Zero); IntPtr image = API.CGImageCreate(128, 128, 8, 32, 4 * 128, API.CGColorSpaceCreateDeviceRGB(), 4, provider, IntPtr.Zero, 0, 0); API.SetApplicationDockTileImage(image); } } public string Title { get { return title; } set { if (value != Title) { API.SetWindowTitle(window.WindowRef, value); title = value; TitleChanged(this, EventArgs.Empty); } } } public bool Visible { get { return API.IsWindowVisible(window.WindowRef); } set { if (value != Visible) { if (value) Show(); else Hide(); VisibleChanged(this, EventArgs.Empty); } } } public bool Focused { get { return this.mIsActive; } } public Rectangle Bounds { get { return bounds; } set { Location = value.Location; Size = value.Size; } } public Point Location { get { return Bounds.Location; } set { SetLocation((short)value.X, (short)value.Y); } } public Size Size { get { return bounds.Size; } set { SetSize((short)value.Width, (short)value.Height); } } public int Width { get { return ClientRectangle.Width; } set { SetClientSize((short)value, (short)Height); } } public int Height { get { return ClientRectangle.Height; } set { SetClientSize((short)Width, (short)value); } } public int X { get { return ClientRectangle.X; } set { Location = new Point(value, Y); } } public int Y { get { return ClientRectangle.Y; } set { Location = new Point(X, value); } } public Rectangle ClientRectangle { get { return clientRectangle; } // just set the size, and ignore the location value. // this is the behavior of the Windows WinGLNative. set { ClientSize = value.Size; } } public Size ClientSize { get { return clientRectangle.Size; } set { API.SizeWindow(window.WindowRef, (short)value.Width, (short)value.Height, true); LoadSize(); Resize(this, EventArgs.Empty); } } public bool CursorVisible { get { return CG.CursorIsVisible(); } set { if (value) { CG.DisplayShowCursor(IntPtr.Zero); CG.AssociateMouseAndMouseCursorPosition(true); } else { CG.DisplayHideCursor(IntPtr.Zero); ResetMouseToWindowCenter(); CG.AssociateMouseAndMouseCursorPosition(false); } } } public void Close() { CancelEventArgs e = new CancelEventArgs(); OnClosing(e); if (e.Cancel) return; OnClosed(); Dispose(); } public WindowState WindowState { get { if (windowState == WindowState.Fullscreen) return WindowState.Fullscreen; if (Carbon.API.IsWindowCollapsed(window.WindowRef)) return WindowState.Minimized; if (Carbon.API.IsWindowInStandardState(window.WindowRef)) { return WindowState.Maximized; } return WindowState.Normal; } set { if (value == WindowState) return; Debug.Print("Switching window state from {0} to {1}", WindowState, value); WindowState oldState = WindowState; windowState = value; if (oldState == WindowState.Fullscreen) { window.GoWindowedHack = true; // when returning from full screen, wait until the context is updated // to actually do the work. return; } if (oldState == WindowState.Minimized) { API.CollapseWindow(window.WindowRef, false); } SetCarbonWindowState(); } } private void SetCarbonWindowState() { CarbonPoint idealSize; switch (windowState) { case WindowState.Fullscreen: window.GoFullScreenHack = true; break; case WindowState.Maximized: // hack because mac os has no concept of maximized. Instead windows are "zoomed" // meaning they are maximized up to their reported ideal size. So we report a // large ideal size. idealSize = new CarbonPoint(9000, 9000); API.ZoomWindowIdeal(window.WindowRef, WindowPartCode.inZoomOut, ref idealSize); break; case WindowState.Normal: if (WindowState == WindowState.Maximized) { idealSize = new CarbonPoint(); API.ZoomWindowIdeal(window.WindowRef, WindowPartCode.inZoomIn, ref idealSize); } break; case WindowState.Minimized: API.CollapseWindow(window.WindowRef, true); break; } WindowStateChanged(this, EventArgs.Empty); LoadSize(); Resize(this, EventArgs.Empty); } public WindowBorder WindowBorder { get { return windowBorder; } set { if (windowBorder == value) return; windowBorder = value; if (windowBorder == WindowBorder.Resizable) { API.ChangeWindowAttributes(window.WindowRef, WindowAttributes.Resizable | WindowAttributes.FullZoom, WindowAttributes.NoAttributes); } else if (windowBorder == WindowBorder.Fixed) { API.ChangeWindowAttributes(window.WindowRef, WindowAttributes.NoAttributes, WindowAttributes.Resizable | WindowAttributes.FullZoom); } WindowBorderChanged(this, EventArgs.Empty); } } #region --- Event wrappers --- private void OnKeyPress(KeyPressEventArgs keyPressArgs) { KeyPress(this, keyPressArgs); } private void OnWindowStateChanged() { WindowStateChanged(this, EventArgs.Empty); } protected virtual void OnClosing(CancelEventArgs e) { Closing(this, e); } protected virtual void OnClosed() { Closed(this, EventArgs.Empty); } private void OnMouseLeave() { MouseLeave(this, EventArgs.Empty); } private void OnMouseEnter() { MouseEnter(this, EventArgs.Empty); } private void OnActivate() { mIsActive = true; FocusedChanged(this, EventArgs.Empty); } private void OnDeactivate() { mIsActive = false; FocusedChanged(this, EventArgs.Empty); } #endregion public event EventHandler<EventArgs> Move = delegate { }; public event EventHandler<EventArgs> Resize = delegate { }; public event EventHandler<CancelEventArgs> Closing = delegate { }; public event EventHandler<EventArgs> Closed = delegate { }; public event EventHandler<EventArgs> Disposed = delegate { }; public event EventHandler<EventArgs> IconChanged = delegate { }; public event EventHandler<EventArgs> TitleChanged = delegate { }; public event EventHandler<EventArgs> VisibleChanged = delegate { }; public event EventHandler<EventArgs> FocusedChanged = delegate { }; public event EventHandler<EventArgs> WindowBorderChanged = delegate { }; public event EventHandler<EventArgs> WindowStateChanged = delegate { }; public event EventHandler<OpenTK.Input.KeyboardKeyEventArgs> KeyDown = delegate { }; public event EventHandler<KeyPressEventArgs> KeyPress = delegate { }; public event EventHandler<OpenTK.Input.KeyboardKeyEventArgs> KeyUp = delegate { }; public event EventHandler<EventArgs> MouseEnter = delegate { }; public event EventHandler<EventArgs> MouseLeave = delegate { }; #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. //////////////////////////////////////////////////////////////////////////////// //////////////////////////////////////////////////////////////////////////////// // // RuntimeHelpers // This class defines a set of static methods that provide support for compilers. // // namespace System.Runtime.CompilerServices { using System; using System.Security; using System.Runtime; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.ConstrainedExecution; using System.Runtime.Serialization; using System.Security.Permissions; using System.Threading; using System.Runtime.Versioning; using System.Diagnostics.Contracts; public static class RuntimeHelpers { #if FEATURE_CORECLR // Exposed here as a more appropriate place than on FormatterServices itself, // which is a high level reflection heavy type. public static Object GetUninitializedObject(Type type) { return FormatterServices.GetUninitializedObject(type); } #endif // FEATURE_CORECLR [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void InitializeArray(Array array,RuntimeFieldHandle fldHandle); // GetObjectValue is intended to allow value classes to be manipulated as 'Object' // but have aliasing behavior of a value class. The intent is that you would use // this function just before an assignment to a variable of type 'Object'. If the // value being assigned is a mutable value class, then a shallow copy is returned // (because value classes have copy semantics), but otherwise the object itself // is returned. // // Note: VB calls this method when they're about to assign to an Object // or pass it as a parameter. The goal is to make sure that boxed // value types work identical to unboxed value types - ie, they get // cloned when you pass them around, and are always passed by value. // Of course, reference types are not cloned. // [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern Object GetObjectValue(Object obj); // RunClassConstructor causes the class constructor for the given type to be triggered // in the current domain. After this call returns, the class constructor is guaranteed to // have at least been started by some thread. In the absence of class constructor // deadlock conditions, the call is further guaranteed to have completed. // // This call will generate an exception if the specified class constructor threw an // exception when it ran. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunClassConstructor(RuntimeType type); public static void RunClassConstructor(RuntimeTypeHandle type) { _RunClassConstructor(type.GetRuntimeType()); } // RunModuleConstructor causes the module constructor for the given type to be triggered // in the current domain. After this call returns, the module constructor is guaranteed to // have at least been started by some thread. In the absence of module constructor // deadlock conditions, the call is further guaranteed to have completed. // // This call will generate an exception if the specified module constructor threw an // exception when it ran. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] private static extern void _RunModuleConstructor(System.Reflection.RuntimeModule module); public static void RunModuleConstructor(ModuleHandle module) { _RunModuleConstructor(module.GetRuntimeModule()); } [System.Security.SecurityCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] private static unsafe extern void _PrepareMethod(IRuntimeMethodInfo method, IntPtr* pInstantiation, int cInstantiation); [System.Security.SecurityCritical] // auto-generated [DllImport(JitHelpers.QCall, CharSet = CharSet.Unicode), SuppressUnmanagedCodeSecurity] internal static extern void _CompileMethod(IRuntimeMethodInfo method); // Simple (instantiation not required) method. [System.Security.SecurityCritical] // auto-generated_required public static void PrepareMethod(RuntimeMethodHandle method) { unsafe { _PrepareMethod(method.GetMethodInfo(), null, 0); } } // Generic method or method with generic class with specific instantiation. [System.Security.SecurityCritical] // auto-generated_required public static void PrepareMethod(RuntimeMethodHandle method, RuntimeTypeHandle[] instantiation) { unsafe { int length; IntPtr[] instantiationHandles = RuntimeTypeHandle.CopyRuntimeTypeHandles(instantiation, out length); fixed (IntPtr* pInstantiation = instantiationHandles) { _PrepareMethod(method.GetMethodInfo(), pInstantiation, length); GC.KeepAlive(instantiation); } } } // This method triggers a given delegate to be prepared. This involves preparing the // delegate's Invoke method and preparing the target of that Invoke. In the case of // a multi-cast delegate, we rely on the fact that each individual component was prepared // prior to the Combine. In other words, this service does not navigate through the // entire multicasting list. // If our own reliable event sinks perform the Combine (for example AppDomain.DomainUnload), // then the result is fully prepared. But if a client calls Combine himself and then // then adds that combination to e.g. AppDomain.DomainUnload, then the client is responsible // for his own preparation. [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void PrepareDelegate(Delegate d); // See comment above for PrepareDelegate // // PrepareContractedDelegate weakens this a bit by only assuring that we prepare // delegates which also have a ReliabilityContract. This is useful for services that // want to provide opt-in reliability, generally some random event sink providing // always reliable semantics to random event handlers that are likely to have not // been written with relability in mind is a lost cause anyway. // // NOTE: that for the NGen case you can sidestep the required ReliabilityContract // by using the [PrePrepareMethod] attribute. [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void PrepareContractedDelegate(Delegate d); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern int GetHashCode(Object o); [System.Security.SecuritySafeCritical] // auto-generated [MethodImplAttribute(MethodImplOptions.InternalCall)] public new static extern bool Equals(Object o1, Object o2); public static int OffsetToStringData { // This offset is baked in by string indexer intrinsic, so there is no harm // in getting it baked in here as well. [System.Runtime.Versioning.NonVersionable] get { // Number of bytes from the address pointed to by a reference to // a String to the first 16-bit character in the String. Skip // over the MethodTable pointer, & String // length. Of course, the String reference points to the memory // after the sync block, so don't count that. // This property allows C#'s fixed statement to work on Strings. // On 64 bit platforms, this should be 12 (8+4) and on 32 bit 8 (4+4). #if BIT64 return 12; #else // 32 return 8; #endif // BIT64 } } // This method ensures that there is sufficient stack to execute the average Framework function. // If there is not enough stack, then it throws System.InsufficientExecutionStackException. // Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack // below. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] public static extern void EnsureSufficientExecutionStack(); #if FEATURE_CORECLR // This method ensures that there is sufficient stack to execute the average Framework function. // If there is not enough stack, then it return false. // Note: this method is not part of the CER support, and is not to be confused with ProbeForSufficientStack // below. [System.Security.SecuritySafeCritical] [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.Success)] internal static extern bool TryEnsureSufficientExecutionStack(); #endif [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static extern void ProbeForSufficientStack(); // This method is a marker placed immediately before a try clause to mark the corresponding catch and finally blocks as // constrained. There's no code here other than the probe because most of the work is done at JIT time when we spot a call to this routine. [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static void PrepareConstrainedRegions() { ProbeForSufficientStack(); } // When we detect a CER with no calls, we can point the JIT to this non-probing version instead // as we don't need to probe. [System.Security.SecurityCritical] // auto-generated_required [ReliabilityContract(Consistency.WillNotCorruptState, Cer.MayFail)] public static void PrepareConstrainedRegionsNoOP() { } #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public delegate void TryCode(Object userData); #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif public delegate void CleanupCode(Object userData, bool exceptionThrown); [System.Security.SecurityCritical] // auto-generated_required [MethodImplAttribute(MethodImplOptions.InternalCall)] public static extern void ExecuteCodeWithGuaranteedCleanup(TryCode code, CleanupCode backoutCode, Object userData); #if FEATURE_CORECLR [System.Security.SecurityCritical] // auto-generated #endif [PrePrepareMethod] internal static void ExecuteBackoutCodeHelper(Object backoutCode, Object userData, bool exceptionThrown) { ((CleanupCode)backoutCode)(userData, exceptionThrown); } } }
using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using LibGit2Sharp.Core; using LibGit2Sharp.Core.Handles; namespace LibGit2Sharp { /// <summary> /// Show changes between the working tree and the index or a tree, changes between the index and a tree, changes between two trees, or changes between two files on disk. /// <para> /// Copied and renamed files currently cannot be detected, as the feature is not supported by libgit2 yet. /// These files will be shown as a pair of Deleted/Added files.</para> /// </summary> public class Diff { private readonly Repository repo; private static GitDiffOptions BuildOptions(DiffModifiers diffOptions, FilePath[] filePaths = null, MatchedPathsAggregator matchedPathsAggregator = null, CompareOptions compareOptions = null) { var options = new GitDiffOptions(); options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_TYPECHANGE; compareOptions = compareOptions ?? new CompareOptions(); options.ContextLines = (ushort)compareOptions.ContextLines; options.InterhunkLines = (ushort)compareOptions.InterhunkLines; if (diffOptions.HasFlag(DiffModifiers.IncludeUntracked)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNTRACKED | GitDiffOptionFlags.GIT_DIFF_RECURSE_UNTRACKED_DIRS | GitDiffOptionFlags.GIT_DIFF_SHOW_UNTRACKED_CONTENT; } if (diffOptions.HasFlag(DiffModifiers.IncludeIgnored)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_IGNORED | GitDiffOptionFlags.GIT_DIFF_RECURSE_IGNORED_DIRS; } if (diffOptions.HasFlag(DiffModifiers.IncludeUnmodified) || compareOptions.IncludeUnmodified || (compareOptions.Similarity != null && (compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.CopiesHarder || compareOptions.Similarity.RenameDetectionMode == RenameDetectionMode.Exact))) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_INCLUDE_UNMODIFIED; } if (compareOptions.Algorithm == DiffAlgorithm.Patience) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_PATIENCE; } if (diffOptions.HasFlag(DiffModifiers.DisablePathspecMatch)) { options.Flags |= GitDiffOptionFlags.GIT_DIFF_DISABLE_PATHSPEC_MATCH; } if (matchedPathsAggregator != null) { options.NotifyCallback = matchedPathsAggregator.OnGitDiffNotify; } if (filePaths != null) { options.PathSpec = GitStrArrayManaged.BuildFrom(filePaths); } return options; } /// <summary> /// Needed for mocking purposes. /// </summary> protected Diff() { } internal Diff(Repository repo) { this.repo = repo; } private static readonly IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> HandleRetrieverDispatcher = BuildHandleRetrieverDispatcher(); private static IDictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> BuildHandleRetrieverDispatcher() { return new Dictionary<DiffTargets, Func<Repository, TreeComparisonHandleRetriever>> { { DiffTargets.Index, IndexToTree }, { DiffTargets.WorkingDirectory, WorkdirToTree }, { DiffTargets.Index | DiffTargets.WorkingDirectory, WorkdirAndIndexToTree }, }; } private static readonly IDictionary<Type, Func<DiffSafeHandle, object>> ChangesBuilders = new Dictionary<Type, Func<DiffSafeHandle, object>> { { typeof(Patch), diff => new Patch(diff) }, { typeof(TreeChanges), diff => new TreeChanges(diff) }, { typeof(PatchStats), diff => new PatchStats(diff) }, }; /// <summary> /// Show changes between two <see cref="Blob"/>s. /// </summary> /// <param name="oldBlob">The <see cref="Blob"/> you want to compare from.</param> /// <param name="newBlob">The <see cref="Blob"/> you want to compare to.</param> /// <returns>A <see cref="ContentChanges"/> containing the changes between the <paramref name="oldBlob"/> and the <paramref name="newBlob"/>.</returns> public virtual ContentChanges Compare(Blob oldBlob, Blob newBlob) { return Compare(oldBlob, newBlob, null); } /// <summary> /// Show changes between two <see cref="Blob"/>s. /// </summary> /// <param name="oldBlob">The <see cref="Blob"/> you want to compare from.</param> /// <param name="newBlob">The <see cref="Blob"/> you want to compare to.</param> /// <param name="compareOptions">Additional options to define comparison behavior.</param> /// <returns>A <see cref="ContentChanges"/> containing the changes between the <paramref name="oldBlob"/> and the <paramref name="newBlob"/>.</returns> public virtual ContentChanges Compare(Blob oldBlob, Blob newBlob, CompareOptions compareOptions) { using (GitDiffOptions options = BuildOptions(DiffModifiers.None, compareOptions: compareOptions)) { return new ContentChanges(repo, oldBlob, newBlob, options); } } /// <summary> /// Show changes between two <see cref="Tree"/>s. /// </summary> /// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param> /// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param> /// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns> public virtual T Compare<T>(Tree oldTree, Tree newTree) where T : class { return Compare<T>(oldTree, newTree, null, null, null); } /// <summary> /// Show changes between two <see cref="Tree"/>s. /// </summary> /// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param> /// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns> public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths) where T : class { return Compare<T>(oldTree, newTree, paths, null, null); } /// <summary> /// Show changes between two <see cref="Tree"/>s. /// </summary> /// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param> /// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns> public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions) where T : class { return Compare<T>(oldTree, newTree, paths, explicitPathsOptions, null); } /// <summary> /// Show changes between two <see cref="Tree"/>s. /// </summary> /// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param> /// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns> public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths, CompareOptions compareOptions) where T : class { return Compare<T>(oldTree, newTree, paths, null, compareOptions); } /// <summary> /// Show changes between two <see cref="Tree"/>s. /// </summary> /// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param> /// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns> public virtual T Compare<T>(Tree oldTree, Tree newTree, CompareOptions compareOptions) where T : class { return Compare<T>(oldTree, newTree, null, null, compareOptions); } /// <summary> /// Show changes between two <see cref="Tree"/>s. /// </summary> /// <param name="oldTree">The <see cref="Tree"/> you want to compare from.</param> /// <param name="newTree">The <see cref="Tree"/> you want to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <returns>A <see cref="TreeChanges"/> containing the changes between the <paramref name="oldTree"/> and the <paramref name="newTree"/>.</returns> public virtual T Compare<T>(Tree oldTree, Tree newTree, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions, CompareOptions compareOptions) where T : class { Func<DiffSafeHandle, object> builder; if (!ChangesBuilders.TryGetValue(typeof (T), out builder)) { throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T), typeof (TreeChanges), typeof (Patch))); } var comparer = TreeToTree(repo); ObjectId oldTreeId = oldTree != null ? oldTree.Id : null; ObjectId newTreeId = newTree != null ? newTree.Id : null; var diffOptions = DiffModifiers.None; if (explicitPathsOptions != null) { diffOptions |= DiffModifiers.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffModifiers.IncludeUnmodified; } } using (DiffSafeHandle diff = BuildDiffList(oldTreeId, newTreeId, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return (T)builder(diff); } } /// <summary> /// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="oldTree">The <see cref="Tree"/> to compare from.</param> /// <param name="diffTargets">The targets to compare to.</param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns> public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets) where T : class { return Compare<T>(oldTree, diffTargets, null, null, null); } /// <summary> /// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="oldTree">The <see cref="Tree"/> to compare from.</param> /// <param name="diffTargets">The targets to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns> public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets, IEnumerable<string> paths) where T : class { return Compare<T>(oldTree, diffTargets, paths, null, null); } /// <summary> /// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="oldTree">The <see cref="Tree"/> to compare from.</param> /// <param name="diffTargets">The targets to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns> public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions) where T : class { return Compare<T>(oldTree, diffTargets, paths, explicitPathsOptions, null); } /// <summary> /// Show changes between a <see cref="Tree"/> and the Index, the Working Directory, or both. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="oldTree">The <see cref="Tree"/> to compare from.</param> /// <param name="diffTargets">The targets to compare to.</param> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the <see cref="Tree"/> and the selected target.</returns> public virtual T Compare<T>(Tree oldTree, DiffTargets diffTargets, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions, CompareOptions compareOptions) where T : class { Func<DiffSafeHandle, object> builder; if (!ChangesBuilders.TryGetValue(typeof (T), out builder)) { throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T), typeof (TreeChanges), typeof (Patch))); } var comparer = HandleRetrieverDispatcher[diffTargets](repo); ObjectId oldTreeId = oldTree != null ? oldTree.Id : null; DiffModifiers diffOptions = diffTargets.HasFlag(DiffTargets.WorkingDirectory) ? DiffModifiers.IncludeUntracked : DiffModifiers.None; if (explicitPathsOptions != null) { diffOptions |= DiffModifiers.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffModifiers.IncludeUnmodified; } } using (DiffSafeHandle diff = BuildDiffList(oldTreeId, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return (T)builder(diff); } } /// <summary> /// Show changes between the working directory and the index. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns> public virtual T Compare<T>() where T : class { return Compare<T>(DiffModifiers.None); } /// <summary> /// Show changes between the working directory and the index. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns> public virtual T Compare<T>(IEnumerable<string> paths) where T : class { return Compare<T>(DiffModifiers.None, paths); } /// <summary> /// Show changes between the working directory and the index. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="includeUntracked">If true, include untracked files from the working dir as additions. Otherwise ignore them.</param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns> public virtual T Compare<T>(IEnumerable<string> paths, bool includeUntracked) where T : class { return Compare<T>(includeUntracked ? DiffModifiers.IncludeUntracked : DiffModifiers.None, paths); } /// <summary> /// Show changes between the working directory and the index. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="includeUntracked">If true, include untracked files from the working dir as additions. Otherwise ignore them.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns> public virtual T Compare<T>(IEnumerable<string> paths, bool includeUntracked, ExplicitPathsOptions explicitPathsOptions) where T : class { return Compare<T>(includeUntracked ? DiffModifiers.IncludeUntracked : DiffModifiers.None, paths, explicitPathsOptions); } /// <summary> /// Show changes between the working directory and the index. /// <para> /// The level of diff performed can be specified by passing either a <see cref="TreeChanges"/> /// or <see cref="Patch"/> type as the generic parameter. /// </para> /// </summary> /// <param name="paths">The list of paths (either files or directories) that should be compared.</param> /// <param name="includeUntracked">If true, include untracked files from the working dir as additions. Otherwise ignore them.</param> /// <param name="explicitPathsOptions"> /// If set, the passed <paramref name="paths"/> will be treated as explicit paths. /// Use these options to determine how unmatched explicit paths should be handled. /// </param> /// <param name="compareOptions">Additional options to define patch generation behavior.</param> /// <typeparam name="T">Can be either a <see cref="TreeChanges"/> if you are only interested in the list of files modified, added, ..., or /// a <see cref="Patch"/> if you want the actual patch content for the whole diff and for individual files.</typeparam> /// <returns>A <typeparamref name="T"/> containing the changes between the working directory and the index.</returns> public virtual T Compare<T>(IEnumerable<string> paths, bool includeUntracked, ExplicitPathsOptions explicitPathsOptions, CompareOptions compareOptions) where T : class { return Compare<T>(includeUntracked ? DiffModifiers.IncludeUntracked : DiffModifiers.None, paths, explicitPathsOptions, compareOptions); } internal virtual T Compare<T>(DiffModifiers diffOptions, IEnumerable<string> paths = null, ExplicitPathsOptions explicitPathsOptions = null, CompareOptions compareOptions = null) where T : class { Func<DiffSafeHandle, object> builder; if (!ChangesBuilders.TryGetValue(typeof (T), out builder)) { throw new LibGit2SharpException(string.Format(CultureInfo.InvariantCulture, "Unexpected type '{0}' passed to Compare. Supported values are either '{1}' or '{2}'.", typeof (T), typeof (TreeChanges), typeof (Patch))); } var comparer = WorkdirToIndex(repo); if (explicitPathsOptions != null) { diffOptions |= DiffModifiers.DisablePathspecMatch; if (explicitPathsOptions.ShouldFailOnUnmatchedPath || explicitPathsOptions.OnUnmatchedPath != null) { diffOptions |= DiffModifiers.IncludeUnmodified; } } using (DiffSafeHandle diff = BuildDiffList(null, null, comparer, diffOptions, paths, explicitPathsOptions, compareOptions)) { return (T)builder(diff); } } internal delegate DiffSafeHandle TreeComparisonHandleRetriever(ObjectId oldTreeId, ObjectId newTreeId, GitDiffOptions options); private static TreeComparisonHandleRetriever TreeToTree(Repository repo) { return (oh, nh, o) => Proxy.git_diff_tree_to_tree(repo.Handle, oh, nh, o); } private static TreeComparisonHandleRetriever WorkdirToIndex(Repository repo) { return (oh, nh, o) => Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o); } private static TreeComparisonHandleRetriever WorkdirToTree(Repository repo) { return (oh, nh, o) => Proxy.git_diff_tree_to_workdir(repo.Handle, oh, o); } private static TreeComparisonHandleRetriever WorkdirAndIndexToTree(Repository repo) { TreeComparisonHandleRetriever comparisonHandleRetriever = (oh, nh, o) => { DiffSafeHandle diff = Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o); using (DiffSafeHandle diff2 = Proxy.git_diff_index_to_workdir(repo.Handle, repo.Index.Handle, o)) { Proxy.git_diff_merge(diff, diff2); } return diff; }; return comparisonHandleRetriever; } private static TreeComparisonHandleRetriever IndexToTree(Repository repo) { return (oh, nh, o) => Proxy.git_diff_tree_to_index(repo.Handle, repo.Index.Handle, oh, o); } private DiffSafeHandle BuildDiffList(ObjectId oldTreeId, ObjectId newTreeId, TreeComparisonHandleRetriever comparisonHandleRetriever, DiffModifiers diffOptions, IEnumerable<string> paths, ExplicitPathsOptions explicitPathsOptions, CompareOptions compareOptions) { var matchedPaths = new MatchedPathsAggregator(); var filePaths = repo.ToFilePaths(paths); using (GitDiffOptions options = BuildOptions(diffOptions, filePaths, matchedPaths, compareOptions)) { var diffList = comparisonHandleRetriever(oldTreeId, newTreeId, options); if (explicitPathsOptions != null) { try { DispatchUnmatchedPaths(explicitPathsOptions, filePaths, matchedPaths); } catch { diffList.Dispose(); throw; } } DetectRenames(diffList, compareOptions); return diffList; } } private static void DetectRenames(DiffSafeHandle diffList, CompareOptions compareOptions) { var similarityOptions = (compareOptions == null) ? null : compareOptions.Similarity; if (similarityOptions == null || similarityOptions.RenameDetectionMode == RenameDetectionMode.Default) { Proxy.git_diff_find_similar(diffList, null); return; } if (similarityOptions.RenameDetectionMode == RenameDetectionMode.None) { return; } var opts = new GitDiffFindOptions { RenameThreshold = (ushort)similarityOptions.RenameThreshold, RenameFromRewriteThreshold = (ushort)similarityOptions.RenameFromRewriteThreshold, CopyThreshold = (ushort)similarityOptions.CopyThreshold, BreakRewriteThreshold = (ushort)similarityOptions.BreakRewriteThreshold, RenameLimit = (UIntPtr)similarityOptions.RenameLimit, }; switch (similarityOptions.RenameDetectionMode) { case RenameDetectionMode.Exact: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_EXACT_MATCH_ONLY | GitDiffFindFlags.GIT_DIFF_FIND_RENAMES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED; break; case RenameDetectionMode.Renames: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES; break; case RenameDetectionMode.Copies: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES; break; case RenameDetectionMode.CopiesHarder: opts.Flags = GitDiffFindFlags.GIT_DIFF_FIND_RENAMES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES | GitDiffFindFlags.GIT_DIFF_FIND_COPIES_FROM_UNMODIFIED; break; } if (!compareOptions.IncludeUnmodified) { opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_REMOVE_UNMODIFIED; } switch (similarityOptions.WhitespaceMode) { case WhitespaceMode.DontIgnoreWhitespace: opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_DONT_IGNORE_WHITESPACE; break; case WhitespaceMode.IgnoreLeadingWhitespace: opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_LEADING_WHITESPACE; break; case WhitespaceMode.IgnoreAllWhitespace: opts.Flags |= GitDiffFindFlags.GIT_DIFF_FIND_IGNORE_WHITESPACE; break; } Proxy.git_diff_find_similar(diffList, opts); } private static void DispatchUnmatchedPaths(ExplicitPathsOptions explicitPathsOptions, IEnumerable<FilePath> filePaths, IEnumerable<FilePath> matchedPaths) { List<FilePath> unmatchedPaths = (filePaths != null ? filePaths.Except(matchedPaths) : Enumerable.Empty<FilePath>()).ToList(); if (!unmatchedPaths.Any()) { return; } if (explicitPathsOptions.OnUnmatchedPath != null) { unmatchedPaths.ForEach(filePath => explicitPathsOptions.OnUnmatchedPath(filePath.Native)); } if (explicitPathsOptions.ShouldFailOnUnmatchedPath) { throw new UnmatchedPathException(BuildUnmatchedPathsMessage(unmatchedPaths)); } } private static string BuildUnmatchedPathsMessage(List<FilePath> unmatchedPaths) { var message = new StringBuilder("There were some unmatched paths:" + Environment.NewLine); unmatchedPaths.ForEach(filePath => message.AppendFormat("- {0}{1}", filePath.Native, Environment.NewLine)); return message.ToString(); } } }
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 Provisioning.WorkflowTemplate { /// <summary> /// Encapsulates all the information from SharePoint. /// </summary> public abstract class SharePointContext { public const string SPHostUrlKey = "SPHostUrl"; public const string SPAppWebUrlKey = "SPAppWebUrl"; public const string SPLanguageKey = "SPLanguage"; public const string SPClientTagKey = "SPClientTag"; public const string SPProductNumberKey = "SPProductNumber"; protected static readonly TimeSpan AccessTokenLifetimeTolerance = TimeSpan.FromMinutes(5.0); private readonly Uri spHostUrl; private readonly Uri spAppWebUrl; private readonly string spLanguage; private readonly string spClientTag; private readonly string spProductNumber; // <AccessTokenString, UtcExpiresOn> protected Tuple<string, DateTime> userAccessTokenForSPHost; protected Tuple<string, DateTime> userAccessTokenForSPAppWeb; protected Tuple<string, DateTime> appOnlyAccessTokenForSPHost; protected Tuple<string, DateTime> appOnlyAccessTokenForSPAppWeb; /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } string spHostUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SPHostUrlKey]); Uri spHostUrl; if (Uri.TryCreate(spHostUrlString, UriKind.Absolute, out spHostUrl) && (spHostUrl.Scheme == Uri.UriSchemeHttp || spHostUrl.Scheme == Uri.UriSchemeHttps)) { return spHostUrl; } return null; } /// <summary> /// Gets the SharePoint host url from QueryString of the specified HTTP request. /// </summary> /// <param name="httpRequest">The specified HTTP request.</param> /// <returns>The SharePoint host url. Returns <c>null</c> if the HTTP request doesn't contain the SharePoint host url.</returns> public static Uri GetSPHostUrl(HttpRequest httpRequest) { return GetSPHostUrl(new HttpRequestWrapper(httpRequest)); } /// <summary> /// The SharePoint host url. /// </summary> public Uri SPHostUrl { get { return this.spHostUrl; } } /// <summary> /// The SharePoint app web url. /// </summary> public Uri SPAppWebUrl { get { return this.spAppWebUrl; } } /// <summary> /// The SharePoint language. /// </summary> public string SPLanguage { get { return this.spLanguage; } } /// <summary> /// The SharePoint client tag. /// </summary> public string SPClientTag { get { return this.spClientTag; } } /// <summary> /// The SharePoint product number. /// </summary> public string SPProductNumber { get { return this.spProductNumber; } } /// <summary> /// The user access token for the SharePoint host. /// </summary> public abstract string UserAccessTokenForSPHost { get; } /// <summary> /// The user access token for the SharePoint app web. /// </summary> public abstract string UserAccessTokenForSPAppWeb { get; } /// <summary> /// The app only access token for the SharePoint host. /// </summary> public abstract string AppOnlyAccessTokenForSPHost { get; } /// <summary> /// The app only access token for the SharePoint app web. /// </summary> public abstract string AppOnlyAccessTokenForSPAppWeb { get; } /// <summary> /// Constructor. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> protected SharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber) { if (spHostUrl == null) { throw new ArgumentNullException("spHostUrl"); } if (string.IsNullOrEmpty(spLanguage)) { throw new ArgumentNullException("spLanguage"); } if (string.IsNullOrEmpty(spClientTag)) { throw new ArgumentNullException("spClientTag"); } if (string.IsNullOrEmpty(spProductNumber)) { throw new ArgumentNullException("spProductNumber"); } this.spHostUrl = spHostUrl; this.spAppWebUrl = spAppWebUrl; this.spLanguage = spLanguage; this.spClientTag = spClientTag; this.spProductNumber = spProductNumber; } /// <summary> /// Creates a user ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.UserAccessTokenForSPHost); } /// <summary> /// Creates a user ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateUserClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.UserAccessTokenForSPAppWeb); } /// <summary> /// Creates app only ClientContext for the SharePoint host. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPHost() { return CreateClientContext(this.SPHostUrl, this.AppOnlyAccessTokenForSPHost); } /// <summary> /// Creates an app only ClientContext for the SharePoint app web. /// </summary> /// <returns>A ClientContext instance.</returns> public ClientContext CreateAppOnlyClientContextForSPAppWeb() { return CreateClientContext(this.SPAppWebUrl, this.AppOnlyAccessTokenForSPAppWeb); } /// <summary> /// Gets the database connection string from SharePoint for autohosted app. /// </summary> /// <returns>The database connection string. Returns <c>null</c> if the app is not autohosted or there is no database.</returns> public string GetDatabaseConnectionString() { string dbConnectionString = null; using (ClientContext clientContext = CreateAppOnlyClientContextForSPHost()) { if (clientContext != null) { var result = AppInstance.RetrieveAppDatabaseConnectionString(clientContext); clientContext.ExecuteQuery(); dbConnectionString = result.Value; } } if (dbConnectionString == null) { const string LocalDBInstanceForDebuggingKey = "LocalDBInstanceForDebugging"; var dbConnectionStringSettings = WebConfigurationManager.ConnectionStrings[LocalDBInstanceForDebuggingKey]; dbConnectionString = dbConnectionStringSettings != null ? dbConnectionStringSettings.ConnectionString : null; } return dbConnectionString; } /// <summary> /// Determines if the specified access token is valid. /// It considers an access token as not valid if it is null, or it has expired. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <returns>True if the access token is valid.</returns> protected static bool IsAccessTokenValid(Tuple<string, DateTime> accessToken) { return accessToken != null && !string.IsNullOrEmpty(accessToken.Item1) && accessToken.Item2 > DateTime.UtcNow; } /// <summary> /// Creates a ClientContext with the specified SharePoint site url and the access token. /// </summary> /// <param name="spSiteUrl">The site url.</param> /// <param name="accessToken">The access token.</param> /// <returns>A ClientContext instance.</returns> private static ClientContext CreateClientContext(Uri spSiteUrl, string accessToken) { if (spSiteUrl != null && !string.IsNullOrEmpty(accessToken)) { return TokenHelper.GetClientContextWithAccessToken(spSiteUrl.AbsoluteUri, accessToken); } return null; } } /// <summary> /// Redirection status. /// </summary> public enum RedirectionStatus { Ok, ShouldRedirect, CanNotRedirect } /// <summary> /// Provides SharePointContext instances. /// </summary> public abstract class SharePointContextProvider { private static SharePointContextProvider current; /// <summary> /// The current SharePointContextProvider instance. /// </summary> public static SharePointContextProvider Current { get { return SharePointContextProvider.current; } } /// <summary> /// Initializes the default SharePointContextProvider instance. /// </summary> static SharePointContextProvider() { if (!TokenHelper.IsHighTrustApp()) { SharePointContextProvider.current = new SharePointAcsContextProvider(); } else { SharePointContextProvider.current = new SharePointHighTrustContextProvider(); } } /// <summary> /// Registers the specified SharePointContextProvider instance as current. /// It should be called by Application_Start() in Global.asax. /// </summary> /// <param name="provider">The SharePointContextProvider to be set as current.</param> public static void Register(SharePointContextProvider provider) { if (provider == null) { throw new ArgumentNullException("provider"); } SharePointContextProvider.current = provider; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContextBase httpContext, out Uri redirectUrl) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } redirectUrl = null; if (SharePointContextProvider.Current.GetSharePointContext(httpContext) != null) { return RedirectionStatus.Ok; } const string SPHasRedirectedToSharePointKey = "SPHasRedirectedToSharePoint"; if (!string.IsNullOrEmpty(httpContext.Request.QueryString[SPHasRedirectedToSharePointKey])) { return RedirectionStatus.CanNotRedirect; } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return RedirectionStatus.CanNotRedirect; } if (StringComparer.OrdinalIgnoreCase.Equals(httpContext.Request.HttpMethod, "POST")) { return RedirectionStatus.CanNotRedirect; } Uri requestUrl = httpContext.Request.Url; var queryNameValueCollection = HttpUtility.ParseQueryString(requestUrl.Query); // Removes the values that are included in {StandardTokens}, as {StandardTokens} will be inserted at the beginning of the query string. queryNameValueCollection.Remove(SharePointContext.SPHostUrlKey); queryNameValueCollection.Remove(SharePointContext.SPAppWebUrlKey); queryNameValueCollection.Remove(SharePointContext.SPLanguageKey); queryNameValueCollection.Remove(SharePointContext.SPClientTagKey); queryNameValueCollection.Remove(SharePointContext.SPProductNumberKey); // Adds SPHasRedirectedToSharePoint=1. queryNameValueCollection.Add(SPHasRedirectedToSharePointKey, "1"); UriBuilder returnUrlBuilder = new UriBuilder(requestUrl); returnUrlBuilder.Query = queryNameValueCollection.ToString(); // Inserts StandardTokens. const string StandardTokens = "{StandardTokens}"; string returnUrlString = returnUrlBuilder.Uri.AbsoluteUri; returnUrlString = returnUrlString.Insert(returnUrlString.IndexOf("?") + 1, StandardTokens + "&"); // Constructs redirect url. string redirectUrlString = TokenHelper.GetAppContextTokenRequestUrl(spHostUrl.AbsoluteUri, Uri.EscapeDataString(returnUrlString)); redirectUrl = new Uri(redirectUrlString, UriKind.Absolute); return RedirectionStatus.ShouldRedirect; } /// <summary> /// Checks if it is necessary to redirect to SharePoint for user to authenticate. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <param name="redirectUrl">The redirect url to SharePoint if the status is ShouldRedirect. <c>Null</c> if the status is Ok or CanNotRedirect.</param> /// <returns>Redirection status.</returns> public static RedirectionStatus CheckRedirectionStatus(HttpContext httpContext, out Uri redirectUrl) { return CheckRedirectionStatus(new HttpContextWrapper(httpContext), out redirectUrl); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequestBase httpRequest) { if (httpRequest == null) { throw new ArgumentNullException("httpRequest"); } // SPHostUrl Uri spHostUrl = SharePointContext.GetSPHostUrl(httpRequest); if (spHostUrl == null) { return null; } // SPAppWebUrl string spAppWebUrlString = TokenHelper.EnsureTrailingSlash(httpRequest.QueryString[SharePointContext.SPAppWebUrlKey]); Uri spAppWebUrl; if (!Uri.TryCreate(spAppWebUrlString, UriKind.Absolute, out spAppWebUrl) || !(spAppWebUrl.Scheme == Uri.UriSchemeHttp || spAppWebUrl.Scheme == Uri.UriSchemeHttps)) { spAppWebUrl = null; } // SPLanguage string spLanguage = httpRequest.QueryString[SharePointContext.SPLanguageKey]; if (string.IsNullOrEmpty(spLanguage)) { return null; } // SPClientTag string spClientTag = httpRequest.QueryString[SharePointContext.SPClientTagKey]; if (string.IsNullOrEmpty(spClientTag)) { return null; } // SPProductNumber string spProductNumber = httpRequest.QueryString[SharePointContext.SPProductNumberKey]; if (string.IsNullOrEmpty(spProductNumber)) { return null; } return CreateSharePointContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, httpRequest); } /// <summary> /// Creates a SharePointContext instance with the specified HTTP request. /// </summary> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> public SharePointContext CreateSharePointContext(HttpRequest httpRequest) { return CreateSharePointContext(new HttpRequestWrapper(httpRequest)); } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContextBase httpContext) { if (httpContext == null) { throw new ArgumentNullException("httpContext"); } Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); if (spHostUrl == null) { return null; } SharePointContext spContext = LoadSharePointContext(httpContext); if (spContext == null || !ValidateSharePointContext(spContext, httpContext)) { spContext = CreateSharePointContext(httpContext.Request); if (spContext != null) { SaveSharePointContext(spContext, httpContext); } } return spContext; } /// <summary> /// Gets a SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found and a new instance can't be created.</returns> public SharePointContext GetSharePointContext(HttpContext httpContext) { return GetSharePointContext(new HttpContextWrapper(httpContext)); } /// <summary> /// Creates a SharePointContext instance. /// </summary> /// <param name="spHostUrl">The SharePoint host url.</param> /// <param name="spAppWebUrl">The SharePoint app web url.</param> /// <param name="spLanguage">The SharePoint language.</param> /// <param name="spClientTag">The SharePoint client tag.</param> /// <param name="spProductNumber">The SharePoint product number.</param> /// <param name="httpRequest">The HTTP request.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if errors occur.</returns> protected abstract SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest); /// <summary> /// Validates if the given SharePointContext can be used with the specified HTTP context. /// </summary> /// <param name="spContext">The SharePointContext.</param> /// <param name="httpContext">The HTTP context.</param> /// <returns>True if the given SharePointContext can be used with the specified HTTP context.</returns> protected abstract bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext); /// <summary> /// Loads the SharePointContext instance associated with the specified HTTP context. /// </summary> /// <param name="httpContext">The HTTP context.</param> /// <returns>The SharePointContext instance. Returns <c>null</c> if not found.</returns> protected abstract SharePointContext LoadSharePointContext(HttpContextBase httpContext); /// <summary> /// Saves the specified SharePointContext instance associated with the specified HTTP context. /// <c>null</c> is accepted for clearing the SharePointContext instance associated with the HTTP context. /// </summary> /// <param name="spContext">The SharePointContext instance to be saved, or <c>null</c>.</param> /// <param name="httpContext">The HTTP context.</param> protected abstract void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext); } #region ACS /// <summary> /// Encapsulates all the information from SharePoint in ACS mode. /// </summary> public class SharePointAcsContext : SharePointContext { private readonly string contextToken; private readonly SharePointContextToken contextTokenObj; /// <summary> /// The context token. /// </summary> public string ContextToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextToken : null; } } /// <summary> /// The context token's "CacheKey" claim. /// </summary> public string CacheKey { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.CacheKey : null; } } /// <summary> /// The context token's "refreshtoken" claim. /// </summary> public string RefreshToken { get { return this.contextTokenObj.ValidTo > DateTime.UtcNow ? this.contextTokenObj.RefreshToken : null; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPHostUrl.Authority)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetAccessToken(this.contextTokenObj, this.SPAppWebUrl.Authority)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPHostUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPHostUrl))); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetAppOnlyAccessToken(TokenHelper.SharePointPrincipal, this.SPAppWebUrl.Authority, TokenHelper.GetRealmFromTargetUrl(this.SPAppWebUrl))); } } public SharePointAcsContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, string contextToken, SharePointContextToken contextTokenObj) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (string.IsNullOrEmpty(contextToken)) { throw new ArgumentNullException("contextToken"); } if (contextTokenObj == null) { throw new ArgumentNullException("contextTokenObj"); } this.contextToken = contextToken; this.contextTokenObj = contextTokenObj; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<OAuth2AccessTokenResponse> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } try { OAuth2AccessTokenResponse oAuth2AccessTokenResponse = tokenRenewalHandler(); DateTime expiresOn = oAuth2AccessTokenResponse.ExpiresOn; if ((expiresOn - oAuth2AccessTokenResponse.NotBefore) > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(oAuth2AccessTokenResponse.AccessToken, expiresOn); } catch (WebException) { } } } /// <summary> /// Default provider for SharePointAcsContext. /// </summary> public class SharePointAcsContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; private const string SPCacheKeyKey = "SPCacheKey"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { string contextTokenString = TokenHelper.GetContextTokenFromRequest(httpRequest); if (string.IsNullOrEmpty(contextTokenString)) { return null; } SharePointContextToken contextToken = null; try { contextToken = TokenHelper.ReadAndValidateContextToken(contextTokenString, httpRequest.Url.Authority); } catch (WebException) { return null; } catch (AudienceUriValidationFailedException) { return null; } return new SharePointAcsContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, contextTokenString, contextToken); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); string contextToken = TokenHelper.GetContextTokenFromRequest(httpContext.Request); HttpCookie spCacheKeyCookie = httpContext.Request.Cookies[SPCacheKeyKey]; string spCacheKey = spCacheKeyCookie != null ? spCacheKeyCookie.Value : null; return spHostUrl == spAcsContext.SPHostUrl && !string.IsNullOrEmpty(spAcsContext.CacheKey) && spCacheKey == spAcsContext.CacheKey && !string.IsNullOrEmpty(spAcsContext.ContextToken) && (string.IsNullOrEmpty(contextToken) || contextToken == spAcsContext.ContextToken); } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointAcsContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointAcsContext spAcsContext = spContext as SharePointAcsContext; if (spAcsContext != null) { HttpCookie spCacheKeyCookie = new HttpCookie(SPCacheKeyKey) { Value = spAcsContext.CacheKey, Secure = true, HttpOnly = true }; httpContext.Response.AppendCookie(spCacheKeyCookie); } httpContext.Session[SPContextKey] = spAcsContext; } } #endregion ACS #region HighTrust /// <summary> /// Encapsulates all the information from SharePoint in HighTrust mode. /// </summary> public class SharePointHighTrustContext : SharePointContext { private readonly WindowsIdentity logonUserIdentity; /// <summary> /// The Windows identity for the current user. /// </summary> public WindowsIdentity LogonUserIdentity { get { return this.logonUserIdentity; } } public override string UserAccessTokenForSPHost { get { return GetAccessTokenString(ref this.userAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, this.LogonUserIdentity)); } } public override string UserAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.userAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, this.LogonUserIdentity)); } } public override string AppOnlyAccessTokenForSPHost { get { return GetAccessTokenString(ref this.appOnlyAccessTokenForSPHost, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPHostUrl, null)); } } public override string AppOnlyAccessTokenForSPAppWeb { get { if (this.SPAppWebUrl == null) { return null; } return GetAccessTokenString(ref this.appOnlyAccessTokenForSPAppWeb, () => TokenHelper.GetS2SAccessTokenWithWindowsIdentity(this.SPAppWebUrl, null)); } } public SharePointHighTrustContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, WindowsIdentity logonUserIdentity) : base(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber) { if (logonUserIdentity == null) { throw new ArgumentNullException("logonUserIdentity"); } this.logonUserIdentity = logonUserIdentity; } /// <summary> /// Ensures the access token is valid and returns it. /// </summary> /// <param name="accessToken">The access token to verify.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> /// <returns>The access token string.</returns> private static string GetAccessTokenString(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { RenewAccessTokenIfNeeded(ref accessToken, tokenRenewalHandler); return IsAccessTokenValid(accessToken) ? accessToken.Item1 : null; } /// <summary> /// Renews the access token if it is not valid. /// </summary> /// <param name="accessToken">The access token to renew.</param> /// <param name="tokenRenewalHandler">The token renewal handler.</param> private static void RenewAccessTokenIfNeeded(ref Tuple<string, DateTime> accessToken, Func<string> tokenRenewalHandler) { if (IsAccessTokenValid(accessToken)) { return; } DateTime expiresOn = DateTime.UtcNow.Add(TokenHelper.HighTrustAccessTokenLifetime); if (TokenHelper.HighTrustAccessTokenLifetime > AccessTokenLifetimeTolerance) { // Make the access token get renewed a bit earlier than the time when it expires // so that the calls to SharePoint with it will have enough time to complete successfully. expiresOn -= AccessTokenLifetimeTolerance; } accessToken = Tuple.Create(tokenRenewalHandler(), expiresOn); } } /// <summary> /// Default provider for SharePointHighTrustContext. /// </summary> public class SharePointHighTrustContextProvider : SharePointContextProvider { private const string SPContextKey = "SPContext"; protected override SharePointContext CreateSharePointContext(Uri spHostUrl, Uri spAppWebUrl, string spLanguage, string spClientTag, string spProductNumber, HttpRequestBase httpRequest) { WindowsIdentity logonUserIdentity = httpRequest.LogonUserIdentity; if (logonUserIdentity == null || !logonUserIdentity.IsAuthenticated || logonUserIdentity.IsGuest || logonUserIdentity.User == null) { return null; } return new SharePointHighTrustContext(spHostUrl, spAppWebUrl, spLanguage, spClientTag, spProductNumber, logonUserIdentity); } protected override bool ValidateSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { SharePointHighTrustContext spHighTrustContext = spContext as SharePointHighTrustContext; if (spHighTrustContext != null) { Uri spHostUrl = SharePointContext.GetSPHostUrl(httpContext.Request); WindowsIdentity logonUserIdentity = httpContext.Request.LogonUserIdentity; return spHostUrl == spHighTrustContext.SPHostUrl && logonUserIdentity != null && logonUserIdentity.IsAuthenticated && !logonUserIdentity.IsGuest && logonUserIdentity.User == spHighTrustContext.LogonUserIdentity.User; } return false; } protected override SharePointContext LoadSharePointContext(HttpContextBase httpContext) { return httpContext.Session[SPContextKey] as SharePointHighTrustContext; } protected override void SaveSharePointContext(SharePointContext spContext, HttpContextBase httpContext) { httpContext.Session[SPContextKey] = spContext as SharePointHighTrustContext; } } #endregion HighTrust }
// * ************************************************************************** // * Copyright (c) McCreary, Veselka, Bragg & Allen, P.C. // * This source code is subject to terms and conditions of the MIT License. // * A copy of the license can be found in the License.txt file // * at the root of this distribution. // * By using this source code in any fashion, you are agreeing to be bound by // * the terms of the MIT License. // * You must not remove this notice from this software. // * ************************************************************************** using System; using System.Linq; using System.Linq.Expressions; using FluentAssert; using JetBrains.Annotations; using NUnit.Framework; using Rhino.Mocks; namespace MvbaCore.Tests { [UsedImplicitly] public class ReflectionTests { private class Address { // ReSharper disable UnusedAutoPropertyAccessor.Local public string City { get; private set; } // ReSharper restore UnusedAutoPropertyAccessor.Local public static class BoundPropertyNames { public static string City { get { return "City"; } } } } // ReSharper disable ClassNeverInstantiated.Local private class Bar // ReSharper restore ClassNeverInstantiated.Local { // ReSharper disable UnusedAutoPropertyAccessor.Local public Office Office { get; private set; } // ReSharper restore UnusedAutoPropertyAccessor.Local public static class BoundPropertyNames { // ReSharper disable MemberHidesStaticFromOuterClass public static string Office // ReSharper restore MemberHidesStaticFromOuterClass { get { return "Office"; } } } } private class Foo { // ReSharper disable UnusedAutoPropertyAccessor.Local public Bar PrimaryBar { get; private set; } // ReSharper restore UnusedAutoPropertyAccessor.Local public static class BoundPropertyNames { public static string PrimaryBar { get { return "PrimaryBar"; } } } } // ReSharper disable ClassNeverInstantiated.Local private class Office // ReSharper restore ClassNeverInstantiated.Local { // ReSharper disable UnusedAutoPropertyAccessor.Local public Address MailingAddress { get; private set; } // ReSharper restore UnusedAutoPropertyAccessor.Local public static class BoundPropertyNames { public static string MailingAddress { get { return "MailingAddress"; } } } } [TestFixture] public class When_asked_for_a_camel_case_property { [Test] public void Should_get_the_name_of_the_property_using_a_lambda() { var address = new Address(); var fullPropertyName = Reflection.GetCamelCasePropertyNameWithPrefix(() => address.City, "prefix"); Assert.AreEqual("prefix." + Address.BoundPropertyNames.City.ToCamelCase(), fullPropertyName); } [Test] public void Should_get_the_name_using_a_parameterized_lambda_to_a_property_multi_level() { var fullPropertyName = Reflection.GetCamelCaseMultiLevelPropertyName(Foo.BoundPropertyNames.PrimaryBar, Bar.BoundPropertyNames.Office); Assert.AreEqual(Foo.BoundPropertyNames.PrimaryBar.ToCamelCase() + "." + Bar.BoundPropertyNames.Office, fullPropertyName); } } [TestFixture] public class When_asked_for_a_formatted_multilevel_property { [Test] public void Should_give_the_full_name_of_the_property() { var fullPropertyName = Reflection.GetCamelCaseMultiLevelPropertyName(Foo.BoundPropertyNames.PrimaryBar, Bar.BoundPropertyNames.Office); Assert.AreEqual(Foo.BoundPropertyNames.PrimaryBar.ToCamelCase() + "." + Bar.BoundPropertyNames.Office, fullPropertyName); } } [TestFixture] public class When_asked_for_a_multilevel_property_with_strings { [Test] public void Should_give_the_full_name_of_the_property() { var fullPropertyName = Reflection.GetMultiLevelPropertyName(Foo.BoundPropertyNames.PrimaryBar, Bar.BoundPropertyNames.Office); Assert.AreEqual(Foo.BoundPropertyNames.PrimaryBar + "." + Bar.BoundPropertyNames.Office, fullPropertyName); } } [TestFixture] public class When_asked_if_a_type_could_be_null { private bool _result; private Type _type; [Test] public void Given_a_nullable_value_type() { Test.Static() .When(asked_if_a_type_could_be_null) .With(a_nullable_value_type) .Should(return_true) .Verify(); } [Test] public void Given_a_reference_type() { Test.Static() .When(asked_if_a_type_could_be_null) .With(a_reference_type) .Should(return_true) .Verify(); } [Test] public void Given_a_value_type() { Test.Static() .When(asked_if_a_type_could_be_null) .With(a_value_type) .Should(return_false) .Verify(); } [Test] public void Given_string_type() { Test.Static() .When(asked_if_a_type_could_be_null) .With(a_string_type) .Should(return_true) .Verify(); } private void a_nullable_value_type() { _type = typeof(int?); } private void a_reference_type() { _type = typeof(When_asked_if_a_type_could_be_null); } private void a_string_type() { _type = typeof(string); } private void a_value_type() { _type = typeof(int); } private void asked_if_a_type_could_be_null() { _result = Reflection.CouldBeNull(_type); } private void return_false() { _result.ShouldBeFalse(); } private void return_true() { _result.ShouldBeTrue(); } } [TestFixture] public class When_asked_if_a_type_is_a_nullable_value_type { private bool _result; private Type _type; [Test] public void Given_a_nullable_value_type() { Test.Static() .When(asked_if_a_type_is_a_nullable_value_type) .With(a_nullable_value_type) .Should(return_true) .Verify(); } [Test] public void Given_a_reference_type() { Test.Static() .When(asked_if_a_type_is_a_nullable_value_type) .With(a_reference_type) .Should(return_false) .Verify(); } [Test] public void Given_a_value_type() { Test.Static() .When(asked_if_a_type_is_a_nullable_value_type) .With(a_value_type) .Should(return_false) .Verify(); } [Test] public void Given_string_type() { Test.Static() .When(asked_if_a_type_is_a_nullable_value_type) .With(a_string_type) .Should(return_false) .Verify(); } private void a_nullable_value_type() { _type = typeof(int?); } private void a_reference_type() { _type = typeof(When_asked_if_a_type_could_be_null); } private void a_string_type() { _type = typeof(string); } private void a_value_type() { _type = typeof(int); } private void asked_if_a_type_is_a_nullable_value_type() { _result = Reflection.IsNullableValueType(_type); } private void return_false() { _result.ShouldBeFalse(); } private void return_true() { _result.ShouldBeTrue(); } } [TestFixture] public class When_asked_if_a_type_is_a_user_type { private bool _result; private Type _type; [Test] public void Given_a_built_in_enum_type() { Test.Static() .When(asked_if_it_is_a_user_type) .With(a_built_in_enum_type) .Should(return_false) .Verify(); } [Test] public void Given_a_datetime_type() { Test.Static() .When(asked_if_it_is_a_user_type) .With(a_datetime_type) .Should(return_false) .Verify(); } [Test] public void Given_a_primitive_type() { Test.Static() .When(asked_if_it_is_a_user_type) .With(a_primitive_type) .Should(return_false) .Verify(); } [Test] public void Given_a_string_type() { Test.Static() .When(asked_if_it_is_a_user_type) .With(a_string_type) .Should(return_false) .Verify(); } [Test] public void Given_a_user_created_enum_type() { Test.Static() .When(asked_if_it_is_a_user_type) .With(a_user_created_enum_type) .Should(return_true) .Verify(); } [Test] public void Given_a_user_created_struct_type() { Test.Static() .When(asked_if_it_is_a_user_type) .With(a_user_created_struct_type) .Should(return_true) .Verify(); } public enum MyEnum { Color = 1 } public struct MyStruct { } private void a_built_in_enum_type() { _type = typeof(StringSplitOptions); } private void a_datetime_type() { _type = typeof(DateTime); } private void a_primitive_type() { _type = typeof(int); } private void a_string_type() { _type = typeof(string); } private void a_user_created_enum_type() { _type = typeof(MyEnum); } private void a_user_created_struct_type() { _type = typeof(MyStruct); } private void asked_if_it_is_a_user_type() { _result = Reflection.IsUserType(_type); } private void return_false() { _result.ShouldBeFalse(); } private void return_true() { _result.ShouldBeTrue(); } } [UsedImplicitly] public class When_asked_to_get_method_call_data { [TestFixture] public class Given_a_method_that_takes_an_int { [Test] public void Should_get_the_correct_class_name() { var methodCallData = Reflection.GetMethodCallData((TestCalculator c) => c.Add(6)); methodCallData.ClassName.ShouldBeEqualTo("TestCalculator"); } [Test] public void Should_get_the_correct_method_name() { var methodCallData = Reflection.GetMethodCallData((TestCalculator c) => c.Add(6)); methodCallData.MethodName.ShouldBeEqualTo("Add"); } [Test] public void Should_get_the_correct_parameter_names() { var methodCallData = Reflection.GetMethodCallData((TestCalculator c) => c.Add(6)); methodCallData.ParameterValues.Count.ShouldBeEqualTo(1); methodCallData.ParameterValues.Keys.First().ShouldBeEqualTo("addend"); } [Test] public void Should_get_the_correct_parameter_values() { const int expected = 6; var methodCallData = Reflection.GetMethodCallData((TestCalculator c) => c.Add(expected)); methodCallData.ParameterValues.Count.ShouldBeEqualTo(1); methodCallData.ParameterValues.Values.First().ShouldBeEqualTo(expected.ToString()); } } [TestFixture] public class Given_a_method_that_takes_an_object { [Test] public void Should_get_the_correct_class_name() { var methodCallData = Reflection.GetMethodCallData((TestCalculator c) => c.GetFor(null)); methodCallData.ClassName.ShouldBeEqualTo("TestCalculator"); } [Test] public void Should_get_the_correct_method_name() { var methodCallData = Reflection.GetMethodCallData((TestCalculator c) => c.GetFor(null)); methodCallData.MethodName.ShouldBeEqualTo("GetFor"); } [Test] public void Should_get_the_correct_parameter_names() { var methodCallData = Reflection.GetMethodCallData((TestCalculator c) => c.GetFor(null)); methodCallData.ParameterValues.Count.ShouldBeEqualTo(1); methodCallData.ParameterValues.Keys.First().ShouldBeEqualTo("input"); } [Test] public void Should_get_the_correct_parameter_value_if_the_value_is_null() { var methodCallData = Reflection.GetMethodCallData((TestCalculator c) => c.GetFor(null)); methodCallData.ParameterValues.Count.ShouldBeEqualTo(1); methodCallData.ParameterValues.Values.First().ShouldBeEqualTo(null); } [Test] public void Should_get_the_correct_parameter_value_if_the_value_is_not_null() { var input = new TestCalculator(); var methodCallData = Reflection.GetMethodCallData((TestCalculator c) => c.GetFor(input)); methodCallData.ParameterValues.Count.ShouldBeEqualTo(1); methodCallData.ParameterValues.Values.First().ShouldBeEqualTo(input.ToString()); } } // ReSharper disable ClassNeverInstantiated.Global public class TestCalculator // ReSharper restore ClassNeverInstantiated.Global { private int _total; public int Add(int addend) { _total += addend; return _total; } // ReSharper disable once UnusedParameter.Global public string GetFor(TestCalculator input) { return "OK"; } } } [TestFixture] public class When_asked_to_get_the_name_of_a_method { [Test] public void Should_get_the_name_using_a_parameterized_lambda_to_a_method() { var name = Reflection.GetMethodName((ISample s) => s.TheProperty()); Assert.AreEqual("TheProperty", name); } private interface ISample { int TheProperty(); } } [TestFixture] public class When_asked_to_get_the_name_of_a_property { [Test] public void Should_be_able_to_get_the_name_if_it_is_being_boxed() { Expression<Func<TestObject, object>> getter = t => t.Id; var fullPropertyName = Reflection.GetPropertyName(getter); fullPropertyName.ShouldBeEqualTo("Id"); } [Test] public void Should_get_the_name_using_a_parameterized_lambda_to_a_property_multi_level() { var fullPropertyName = Reflection.GetPropertyName((Foo jurisdiction) => jurisdiction.PrimaryBar.Office.MailingAddress.City); Assert.AreEqual( Foo.BoundPropertyNames.PrimaryBar + "." + Bar.BoundPropertyNames.Office + "." + Office.BoundPropertyNames.MailingAddress + "." + Address.BoundPropertyNames.City, fullPropertyName); } [Test] public void Should_get_the_name_using_a_parameterized_lambda_to_a_property_single_level() { var name = Reflection.GetPropertyName((ISample s) => s.TheProperty); Assert.AreEqual("TheProperty", name); } [Test] public void Should_get_the_name_using_a_parameterless_lambda_to_a_property_multi_level() { var sample = new Foo(); var name = Reflection.GetPropertyName(() => sample.PrimaryBar.Office.MailingAddress.City); Assert.AreEqual(Foo.BoundPropertyNames.PrimaryBar + "." + Bar.BoundPropertyNames.Office + "." + Office.BoundPropertyNames.MailingAddress + "." + Address.BoundPropertyNames.City, name); } [Test] public void Should_get_the_name_using_a_parameterless_lambda_to_a_property_multi_level_null_input() { // ReSharper disable ConvertToConstant.Local Foo sample = null; // ReSharper restore ConvertToConstant.Local var name = Reflection.GetPropertyName(() => sample.PrimaryBar.Office.MailingAddress.City); Assert.AreEqual(Foo.BoundPropertyNames.PrimaryBar + "." + Bar.BoundPropertyNames.Office + "." + Office.BoundPropertyNames.MailingAddress + "." + Address.BoundPropertyNames.City, name); } [Test] public void Should_get_the_name_using_a_parameterless_lambda_to_a_property_single_level() { var sample = MockRepository.GenerateStub<ISample>(); var name = Reflection.GetPropertyName(() => sample.TheProperty); Assert.AreEqual("TheProperty", name); } [Test] public void Should_get_the_name_using_a_parameterless_lambda_to_a_property_single_level_null_input() { const ISample sample = null; var name = Reflection.GetPropertyName(() => sample.TheProperty); Assert.AreEqual("TheProperty", name); } public interface ISample { int TheProperty { get; } } // ReSharper disable once ClassNeverInstantiated.Global public class TestObject { public int Id { get; set; } } } [TestFixture] public class When_asked_to_get_the_value_of_an_expression { [Test] public void Should_be_able_to_get_the_value_if_it_is_a_constant() { Expression<Func<int>> expr = () => TestClass.Id; Reflection.GetValueAsString(expr.Body).ShouldBeEqualTo(TestClass.Id.ToString()); } [Test] public void Should_be_able_to_get_the_value_if_it_is_a_property() { var testClass = new TestClass(); Expression<Func<int>> expr = () => testClass.MyId; Reflection.GetValueAsString(expr.Body).ShouldBeEqualTo(TestClass.Id.ToString()); } [Test] public void Should_be_able_to_get_the_value_if_it_is_a_static_method() { Expression<Func<int>> expr = () => TestClass.GetId(); Reflection.GetValueAsString(expr.Body).ShouldBeEqualTo(TestClass.Id.ToString()); } public class TestClass { public const int Id = 1234; public int MyId { get { return Id; } } public static int GetId() { return Id; } } } } }
// // 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 Hyak.Common; using Microsoft.Azure.Management.RemoteApp; using Microsoft.Azure.Management.RemoteApp.Model; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.RemoteApp { /// <summary> /// RemoteApp collection operations. /// </summary> internal partial class CollectionOperations : IServiceOperations<RemoteAppManagementClient>, ICollectionOperations { /// <summary> /// Initializes a new instance of the CollectionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal CollectionOperations(RemoteAppManagementClient client) { this._client = client; } private RemoteAppManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.RemoteApp.RemoteAppManagementClient. /// </summary> public RemoteAppManagementClient Client { get { return this._client; } } /// <summary> /// Gets the collection details. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='collectionName'> /// Required. The automation account name. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response for the get collection operation. /// </returns> public async Task<GetCollectionOperationResult> GetAsync(string resourceGroupName, string collectionName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (collectionName == null) { throw new ArgumentNullException("collectionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("collectionName", collectionName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ArmNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ArmNamespace); } url = url + "/collections/"; url = url + Uri.EscapeDataString(collectionName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result GetCollectionOperationResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new GetCollectionOperationResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { Collection collectionInstance = new Collection(); result.Collection = collectionInstance; JToken propertiesValue = responseDoc["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { CollectionProperties propertiesInstance = new CollectionProperties(); collectionInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { ProvisioningState provisioningStateInstance = ((ProvisioningState)Enum.Parse(typeof(ProvisioningState), ((string)provisioningStateValue), true)); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken nameValue = propertiesValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); propertiesInstance.Name = nameInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken goldImageNameValue = propertiesValue["goldImageName"]; if (goldImageNameValue != null && goldImageNameValue.Type != JTokenType.Null) { string goldImageNameInstance = ((string)goldImageNameValue); propertiesInstance.TemplateImageName = goldImageNameInstance; } JToken statusValue = propertiesValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); propertiesInstance.Status = statusInstance; } JToken lastErrorCodeValue = propertiesValue["lastErrorCode"]; if (lastErrorCodeValue != null && lastErrorCodeValue.Type != JTokenType.Null) { string lastErrorCodeInstance = ((string)lastErrorCodeValue); propertiesInstance.LastErrorCode = lastErrorCodeInstance; } JToken vnetNameValue = propertiesValue["vnetName"]; if (vnetNameValue != null && vnetNameValue.Type != JTokenType.Null) { string vnetNameInstance = ((string)vnetNameValue); propertiesInstance.VNetName = vnetNameInstance; } JToken adInfoValue = propertiesValue["adInfo"]; if (adInfoValue != null && adInfoValue.Type != JTokenType.Null) { ActiveDirectoryConfig adInfoInstance = new ActiveDirectoryConfig(); propertiesInstance.AdInfo = adInfoInstance; JToken domainNameValue = adInfoValue["DomainName"]; if (domainNameValue != null && domainNameValue.Type != JTokenType.Null) { string domainNameInstance = ((string)domainNameValue); adInfoInstance.DomainName = domainNameInstance; } JToken organizationalUnitValue = adInfoValue["OrganizationalUnit"]; if (organizationalUnitValue != null && organizationalUnitValue.Type != JTokenType.Null) { string organizationalUnitInstance = ((string)organizationalUnitValue); adInfoInstance.OrganizationalUnit = organizationalUnitInstance; } JToken serviceAccountUserNameValue = adInfoValue["ServiceAccountUserName"]; if (serviceAccountUserNameValue != null && serviceAccountUserNameValue.Type != JTokenType.Null) { string serviceAccountUserNameInstance = ((string)serviceAccountUserNameValue); adInfoInstance.UserName = serviceAccountUserNameInstance; } JToken serviceAccountPasswordValue = adInfoValue["ServiceAccountPassword"]; if (serviceAccountPasswordValue != null && serviceAccountPasswordValue.Type != JTokenType.Null) { string serviceAccountPasswordInstance = ((string)serviceAccountPasswordValue); adInfoInstance.Password = serviceAccountPasswordInstance; } } JToken planNameValue = propertiesValue["planName"]; if (planNameValue != null && planNameValue.Type != JTokenType.Null) { string planNameInstance = ((string)planNameValue); propertiesInstance.PlanName = planNameInstance; } JToken customRdpPropertyValue = propertiesValue["customRdpProperty"]; if (customRdpPropertyValue != null && customRdpPropertyValue.Type != JTokenType.Null) { string customRdpPropertyInstance = ((string)customRdpPropertyValue); propertiesInstance.CustomRdpProperty = customRdpPropertyInstance; } JToken readyForPublishingValue = propertiesValue["readyForPublishing"]; if (readyForPublishingValue != null && readyForPublishingValue.Type != JTokenType.Null) { bool readyForPublishingInstance = ((bool)readyForPublishingValue); propertiesInstance.ReadyForPublishing = readyForPublishingInstance; } JToken lastModifiedTimeUtcValue = propertiesValue["lastModifiedTimeUtc"]; if (lastModifiedTimeUtcValue != null && lastModifiedTimeUtcValue.Type != JTokenType.Null) { DateTime lastModifiedTimeUtcInstance = ((DateTime)lastModifiedTimeUtcValue); propertiesInstance.LastModifiedTimeUtc = lastModifiedTimeUtcInstance; } JToken modeValue = propertiesValue["mode"]; if (modeValue != null && modeValue.Type != JTokenType.Null) { CollectionMode modeInstance = ((CollectionMode)Enum.Parse(typeof(CollectionMode), ((string)modeValue), true)); propertiesInstance.Mode = modeInstance; } JToken locationValue = propertiesValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); propertiesInstance.Location = locationInstance; } JToken maxSessionsValue = propertiesValue["maxSessions"]; if (maxSessionsValue != null && maxSessionsValue.Type != JTokenType.Null) { int maxSessionsInstance = ((int)maxSessionsValue); propertiesInstance.MaxSessions = maxSessionsInstance; } JToken sessionWarningThresholdValue = propertiesValue["sessionWarningThreshold"]; if (sessionWarningThresholdValue != null && sessionWarningThresholdValue.Type != JTokenType.Null) { int sessionWarningThresholdInstance = ((int)sessionWarningThresholdValue); propertiesInstance.SessionWarningThreshold = sessionWarningThresholdInstance; } JToken typeValue = propertiesValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { CollectionType typeInstance = ((CollectionType)Enum.Parse(typeof(CollectionType), ((string)typeValue), true)); propertiesInstance.Type = typeInstance; } JToken officeTypeValue = propertiesValue["officeType"]; if (officeTypeValue != null && officeTypeValue.Type != JTokenType.Null) { OfficeType officeTypeInstance = ((OfficeType)Enum.Parse(typeof(OfficeType), ((string)officeTypeValue), true)); propertiesInstance.OfficeType = officeTypeInstance; } JToken trialOnlyValue = propertiesValue["trialOnly"]; if (trialOnlyValue != null && trialOnlyValue.Type != JTokenType.Null) { bool trialOnlyInstance = ((bool)trialOnlyValue); propertiesInstance.TrialOnly = trialOnlyInstance; } JToken dnsServersArray = propertiesValue["DnsServers"]; if (dnsServersArray != null && dnsServersArray.Type != JTokenType.Null) { foreach (JToken dnsServersValue in ((JArray)dnsServersArray)) { propertiesInstance.DnsServers.Add(((string)dnsServersValue)); } } JToken subnetNameValue = propertiesValue["subnetName"]; if (subnetNameValue != null && subnetNameValue.Type != JTokenType.Null) { string subnetNameInstance = ((string)subnetNameValue); propertiesInstance.SubnetName = subnetNameInstance; } } JToken idValue = responseDoc["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); collectionInstance.Id = idInstance; } JToken nameValue2 = responseDoc["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); collectionInstance.Name = nameInstance2; } JToken locationValue2 = responseDoc["location"]; if (locationValue2 != null && locationValue2.Type != JTokenType.Null) { string locationInstance2 = ((string)locationValue2); collectionInstance.Location = locationInstance2; } JToken tagsSequenceElement = ((JToken)responseDoc["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); collectionInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue2 = responseDoc["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); collectionInstance.Type = typeInstance2; } JToken etagValue = responseDoc["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); collectionInstance.Etag = etagInstance; } JToken nextLinkValue = responseDoc["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); collectionInstance.NextLink = nextLinkInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets the list of collections details in the resource group. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response for the list collection operation. /// </returns> public async Task<ListCollectionOperationResult> ListAsync(string resourceGroupName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; if (this.Client.ArmNamespace != null) { url = url + Uri.EscapeDataString(this.Client.ArmNamespace); } url = url + "/collections"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2014-09-01"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("Accept", "application/json"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result ListCollectionOperationResult result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ListCollectionOperationResult(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken collectionsArray = responseDoc; if (collectionsArray != null && collectionsArray.Type != JTokenType.Null) { foreach (JToken collectionsValue in ((JArray)collectionsArray)) { Collection collectionInstance = new Collection(); result.Collections.Add(collectionInstance); JToken propertiesValue = collectionsValue["properties"]; if (propertiesValue != null && propertiesValue.Type != JTokenType.Null) { CollectionProperties propertiesInstance = new CollectionProperties(); collectionInstance.Properties = propertiesInstance; JToken provisioningStateValue = propertiesValue["provisioningState"]; if (provisioningStateValue != null && provisioningStateValue.Type != JTokenType.Null) { ProvisioningState provisioningStateInstance = ((ProvisioningState)Enum.Parse(typeof(ProvisioningState), ((string)provisioningStateValue), true)); propertiesInstance.ProvisioningState = provisioningStateInstance; } JToken nameValue = propertiesValue["name"]; if (nameValue != null && nameValue.Type != JTokenType.Null) { string nameInstance = ((string)nameValue); propertiesInstance.Name = nameInstance; } JToken descriptionValue = propertiesValue["description"]; if (descriptionValue != null && descriptionValue.Type != JTokenType.Null) { string descriptionInstance = ((string)descriptionValue); propertiesInstance.Description = descriptionInstance; } JToken goldImageNameValue = propertiesValue["goldImageName"]; if (goldImageNameValue != null && goldImageNameValue.Type != JTokenType.Null) { string goldImageNameInstance = ((string)goldImageNameValue); propertiesInstance.TemplateImageName = goldImageNameInstance; } JToken statusValue = propertiesValue["status"]; if (statusValue != null && statusValue.Type != JTokenType.Null) { string statusInstance = ((string)statusValue); propertiesInstance.Status = statusInstance; } JToken lastErrorCodeValue = propertiesValue["lastErrorCode"]; if (lastErrorCodeValue != null && lastErrorCodeValue.Type != JTokenType.Null) { string lastErrorCodeInstance = ((string)lastErrorCodeValue); propertiesInstance.LastErrorCode = lastErrorCodeInstance; } JToken vnetNameValue = propertiesValue["vnetName"]; if (vnetNameValue != null && vnetNameValue.Type != JTokenType.Null) { string vnetNameInstance = ((string)vnetNameValue); propertiesInstance.VNetName = vnetNameInstance; } JToken adInfoValue = propertiesValue["adInfo"]; if (adInfoValue != null && adInfoValue.Type != JTokenType.Null) { ActiveDirectoryConfig adInfoInstance = new ActiveDirectoryConfig(); propertiesInstance.AdInfo = adInfoInstance; JToken domainNameValue = adInfoValue["DomainName"]; if (domainNameValue != null && domainNameValue.Type != JTokenType.Null) { string domainNameInstance = ((string)domainNameValue); adInfoInstance.DomainName = domainNameInstance; } JToken organizationalUnitValue = adInfoValue["OrganizationalUnit"]; if (organizationalUnitValue != null && organizationalUnitValue.Type != JTokenType.Null) { string organizationalUnitInstance = ((string)organizationalUnitValue); adInfoInstance.OrganizationalUnit = organizationalUnitInstance; } JToken serviceAccountUserNameValue = adInfoValue["ServiceAccountUserName"]; if (serviceAccountUserNameValue != null && serviceAccountUserNameValue.Type != JTokenType.Null) { string serviceAccountUserNameInstance = ((string)serviceAccountUserNameValue); adInfoInstance.UserName = serviceAccountUserNameInstance; } JToken serviceAccountPasswordValue = adInfoValue["ServiceAccountPassword"]; if (serviceAccountPasswordValue != null && serviceAccountPasswordValue.Type != JTokenType.Null) { string serviceAccountPasswordInstance = ((string)serviceAccountPasswordValue); adInfoInstance.Password = serviceAccountPasswordInstance; } } JToken planNameValue = propertiesValue["planName"]; if (planNameValue != null && planNameValue.Type != JTokenType.Null) { string planNameInstance = ((string)planNameValue); propertiesInstance.PlanName = planNameInstance; } JToken customRdpPropertyValue = propertiesValue["customRdpProperty"]; if (customRdpPropertyValue != null && customRdpPropertyValue.Type != JTokenType.Null) { string customRdpPropertyInstance = ((string)customRdpPropertyValue); propertiesInstance.CustomRdpProperty = customRdpPropertyInstance; } JToken readyForPublishingValue = propertiesValue["readyForPublishing"]; if (readyForPublishingValue != null && readyForPublishingValue.Type != JTokenType.Null) { bool readyForPublishingInstance = ((bool)readyForPublishingValue); propertiesInstance.ReadyForPublishing = readyForPublishingInstance; } JToken lastModifiedTimeUtcValue = propertiesValue["lastModifiedTimeUtc"]; if (lastModifiedTimeUtcValue != null && lastModifiedTimeUtcValue.Type != JTokenType.Null) { DateTime lastModifiedTimeUtcInstance = ((DateTime)lastModifiedTimeUtcValue); propertiesInstance.LastModifiedTimeUtc = lastModifiedTimeUtcInstance; } JToken modeValue = propertiesValue["mode"]; if (modeValue != null && modeValue.Type != JTokenType.Null) { CollectionMode modeInstance = ((CollectionMode)Enum.Parse(typeof(CollectionMode), ((string)modeValue), true)); propertiesInstance.Mode = modeInstance; } JToken locationValue = propertiesValue["location"]; if (locationValue != null && locationValue.Type != JTokenType.Null) { string locationInstance = ((string)locationValue); propertiesInstance.Location = locationInstance; } JToken maxSessionsValue = propertiesValue["maxSessions"]; if (maxSessionsValue != null && maxSessionsValue.Type != JTokenType.Null) { int maxSessionsInstance = ((int)maxSessionsValue); propertiesInstance.MaxSessions = maxSessionsInstance; } JToken sessionWarningThresholdValue = propertiesValue["sessionWarningThreshold"]; if (sessionWarningThresholdValue != null && sessionWarningThresholdValue.Type != JTokenType.Null) { int sessionWarningThresholdInstance = ((int)sessionWarningThresholdValue); propertiesInstance.SessionWarningThreshold = sessionWarningThresholdInstance; } JToken typeValue = propertiesValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { CollectionType typeInstance = ((CollectionType)Enum.Parse(typeof(CollectionType), ((string)typeValue), true)); propertiesInstance.Type = typeInstance; } JToken officeTypeValue = propertiesValue["officeType"]; if (officeTypeValue != null && officeTypeValue.Type != JTokenType.Null) { OfficeType officeTypeInstance = ((OfficeType)Enum.Parse(typeof(OfficeType), ((string)officeTypeValue), true)); propertiesInstance.OfficeType = officeTypeInstance; } JToken trialOnlyValue = propertiesValue["trialOnly"]; if (trialOnlyValue != null && trialOnlyValue.Type != JTokenType.Null) { bool trialOnlyInstance = ((bool)trialOnlyValue); propertiesInstance.TrialOnly = trialOnlyInstance; } JToken dnsServersArray = propertiesValue["DnsServers"]; if (dnsServersArray != null && dnsServersArray.Type != JTokenType.Null) { foreach (JToken dnsServersValue in ((JArray)dnsServersArray)) { propertiesInstance.DnsServers.Add(((string)dnsServersValue)); } } JToken subnetNameValue = propertiesValue["subnetName"]; if (subnetNameValue != null && subnetNameValue.Type != JTokenType.Null) { string subnetNameInstance = ((string)subnetNameValue); propertiesInstance.SubnetName = subnetNameInstance; } } JToken idValue = collectionsValue["id"]; if (idValue != null && idValue.Type != JTokenType.Null) { string idInstance = ((string)idValue); collectionInstance.Id = idInstance; } JToken nameValue2 = collectionsValue["name"]; if (nameValue2 != null && nameValue2.Type != JTokenType.Null) { string nameInstance2 = ((string)nameValue2); collectionInstance.Name = nameInstance2; } JToken locationValue2 = collectionsValue["location"]; if (locationValue2 != null && locationValue2.Type != JTokenType.Null) { string locationInstance2 = ((string)locationValue2); collectionInstance.Location = locationInstance2; } JToken tagsSequenceElement = ((JToken)collectionsValue["tags"]); if (tagsSequenceElement != null && tagsSequenceElement.Type != JTokenType.Null) { foreach (JProperty property in tagsSequenceElement) { string tagsKey = ((string)property.Name); string tagsValue = ((string)property.Value); collectionInstance.Tags.Add(tagsKey, tagsValue); } } JToken typeValue2 = collectionsValue["type"]; if (typeValue2 != null && typeValue2.Type != JTokenType.Null) { string typeInstance2 = ((string)typeValue2); collectionInstance.Type = typeInstance2; } JToken etagValue = collectionsValue["etag"]; if (etagValue != null && etagValue.Type != JTokenType.Null) { string etagInstance = ((string)etagValue); collectionInstance.Etag = etagInstance; } JToken nextLinkValue = collectionsValue["nextLink"]; if (nextLinkValue != null && nextLinkValue.Type != JTokenType.Null) { string nextLinkInstance = ((string)nextLinkValue); collectionInstance.NextLink = nextLinkInstance; } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
//--------------------------------------------------------------------------- // // Copyright (C) Microsoft Corporation. All rights reserved. // //--------------------------------------------------------------------------- using System; using System.ComponentModel; using System.Diagnostics; using System.Windows; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; namespace System.Windows.Controls { /// <summary> /// A column that displays editable text. /// </summary> public class DataGridTextColumn : DataGridBoundColumn { static DataGridTextColumn() { ElementStyleProperty.OverrideMetadata(typeof(DataGridTextColumn), new FrameworkPropertyMetadata(DefaultElementStyle)); EditingElementStyleProperty.OverrideMetadata(typeof(DataGridTextColumn), new FrameworkPropertyMetadata(DefaultEditingElementStyle)); } #region Styles /// <summary> /// The default value of the ElementStyle property. /// This value can be used as the BasedOn for new styles. /// </summary> public static Style DefaultElementStyle { get { if (_defaultElementStyle == null) { Style style = new Style(typeof(TextBlock)); // Use the same margin used on the TextBox to provide space for the caret style.Setters.Add(new Setter(TextBlock.MarginProperty, new Thickness(2.0, 0.0, 2.0, 0.0))); style.Seal(); _defaultElementStyle = style; } return _defaultElementStyle; } } /// <summary> /// The default value of the EditingElementStyle property. /// This value can be used as the BasedOn for new styles. /// </summary> public static Style DefaultEditingElementStyle { get { if (_defaultEditingElementStyle == null) { Style style = new Style(typeof(TextBox)); style.Setters.Add(new Setter(TextBox.BorderThicknessProperty, new Thickness(0.0))); style.Setters.Add(new Setter(TextBox.PaddingProperty, new Thickness(0.0))); style.Seal(); _defaultEditingElementStyle = style; } return _defaultEditingElementStyle; } } #endregion #region Element Generation /// <summary> /// Creates the visual tree for text based cells. /// </summary> protected override FrameworkElement GenerateElement(DataGridCell cell, object dataItem) { TextBlock textBlock = new TextBlock(); SyncProperties(textBlock); ApplyStyle(/* isEditing = */ false, /* defaultToElementStyle = */ false, textBlock); ApplyBinding(textBlock, TextBlock.TextProperty); DataGridHelper.RestoreFlowDirection(textBlock, cell); return textBlock; } /// <summary> /// Creates the visual tree for text based cells. /// </summary> protected override FrameworkElement GenerateEditingElement(DataGridCell cell, object dataItem) { TextBox textBox = new TextBox(); SyncProperties(textBox); ApplyStyle(/* isEditing = */ true, /* defaultToElementStyle = */ false, textBox); ApplyBinding(textBox, TextBox.TextProperty); DataGridHelper.RestoreFlowDirection(textBox, cell); return textBox; } private void SyncProperties(FrameworkElement e) { DataGridHelper.SyncColumnProperty(this, e, TextElement.FontFamilyProperty, FontFamilyProperty); DataGridHelper.SyncColumnProperty(this, e, TextElement.FontSizeProperty, FontSizeProperty); DataGridHelper.SyncColumnProperty(this, e, TextElement.FontStyleProperty, FontStyleProperty); DataGridHelper.SyncColumnProperty(this, e, TextElement.FontWeightProperty, FontWeightProperty); DataGridHelper.SyncColumnProperty(this, e, TextElement.ForegroundProperty, ForegroundProperty); } protected internal override void RefreshCellContent(FrameworkElement element, string propertyName) { DataGridCell cell = element as DataGridCell; if (cell != null) { FrameworkElement textElement = cell.Content as FrameworkElement; if (textElement != null) { switch (propertyName) { case "FontFamily": DataGridHelper.SyncColumnProperty(this, textElement, TextElement.FontFamilyProperty, FontFamilyProperty); break; case "FontSize": DataGridHelper.SyncColumnProperty(this, textElement, TextElement.FontSizeProperty, FontSizeProperty); break; case "FontStyle": DataGridHelper.SyncColumnProperty(this, textElement, TextElement.FontStyleProperty, FontStyleProperty); break; case "FontWeight": DataGridHelper.SyncColumnProperty(this, textElement, TextElement.FontWeightProperty, FontWeightProperty); break; case "Foreground": DataGridHelper.SyncColumnProperty(this, textElement, TextElement.ForegroundProperty, ForegroundProperty); break; } } } base.RefreshCellContent(element, propertyName); } #endregion #region Editing /// <summary> /// Called when a cell has just switched to edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <param name="editingEventArgs">The event args of the input event that caused the cell to go into edit mode. May be null.</param> /// <returns>The unedited value of the cell.</returns> protected override object PrepareCellForEdit(FrameworkElement editingElement, RoutedEventArgs editingEventArgs) { TextBox textBox = editingElement as TextBox; if (textBox != null) { textBox.Focus(); string originalValue = textBox.Text; TextCompositionEventArgs textArgs = editingEventArgs as TextCompositionEventArgs; if (textArgs != null) { // If text input started the edit, then replace the text with what was typed. string inputText = ConvertTextForEdit(textArgs.Text); textBox.Text = inputText; // Place the caret after the end of the text. textBox.Select(inputText.Length, 0); } else { // If a mouse click started the edit, then place the caret under the mouse. MouseButtonEventArgs mouseArgs = editingEventArgs as MouseButtonEventArgs; if ((mouseArgs == null) || !PlaceCaretOnTextBox(textBox, Mouse.GetPosition(textBox))) { // If the mouse isn't over the textbox or something else started the edit, then select the text. textBox.SelectAll(); } } return originalValue; } return null; } // convert text the user has typed into the appropriate string to enter into the editable TextBox string ConvertTextForEdit(string s) { // Backspace becomes the empty string if (s == "\b") { s = String.Empty; } return s; } /// <summary> /// Called when a cell's value is to be restored to its original value, /// just before it exits edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <param name="uneditedValue">The original, unedited value of the cell.</param> protected override void CancelCellEdit(FrameworkElement editingElement, object uneditedValue) { DataGridHelper.CacheFlowDirection(editingElement, editingElement != null ? editingElement.Parent as DataGridCell : null); base.CancelCellEdit(editingElement, uneditedValue); } /// <summary> /// Called when a cell's value is to be committed, just before it exits edit mode. /// </summary> /// <param name="editingElement">A reference to element returned by GenerateEditingElement.</param> /// <returns>false if there is a validation error. true otherwise.</returns> protected override bool CommitCellEdit(FrameworkElement editingElement) { DataGridHelper.CacheFlowDirection(editingElement, editingElement != null ? editingElement.Parent as DataGridCell : null); return base.CommitCellEdit(editingElement); } private static bool PlaceCaretOnTextBox(TextBox textBox, Point position) { int characterIndex = textBox.GetCharacterIndexFromPoint(position, /* snapToText = */ false); if (characterIndex >= 0) { textBox.Select(characterIndex, 0); return true; } return false; } internal override void OnInput(InputEventArgs e) { // Text input will start an edit. // Escape is meant to be for CancelEdit. But DataGrid // may not handle KeyDown event for Escape if nothing // is cancelable. Such KeyDown if unhandled by others // will ultimately get promoted to TextInput and be handled // here. But BeginEdit on escape could be confusing to the user. // Hence escape key is special case and BeginEdit is performed if // there is atleast one non espace key character. if (DataGridHelper.HasNonEscapeCharacters(e as TextCompositionEventArgs)) { BeginEdit(e, true); } else if (DataGridHelper.IsImeProcessed(e as KeyEventArgs)) { if (DataGridOwner != null) { DataGridCell cell = DataGridOwner.CurrentCellContainer; if (cell != null && !cell.IsEditing) { Debug.Assert(e.RoutedEvent == Keyboard.PreviewKeyDownEvent, "We should only reach here on the PreviewKeyDown event because the TextBox within is expected to handle the preview event and hence trump the successive KeyDown event."); BeginEdit(e, false); // // The TextEditor for the TextBox establishes contact with the IME // engine lazily at background priority. However in this case we // want to IME engine to know about the TextBox in earnest before // PostProcessing this input event. Only then will the IME key be // recorded in the TextBox. Hence the call to synchronously drain // the Dispatcher queue. // Dispatcher.Invoke((Action)delegate(){}, System.Windows.Threading.DispatcherPriority.Background); } } } } #endregion #region Element Properties /// <summary> /// The DependencyProperty for the FontFamily property. /// Flags: Can be used in style rules /// Default Value: System Dialog Font /// </summary> public static readonly DependencyProperty FontFamilyProperty = TextElement.FontFamilyProperty.AddOwner( typeof(DataGridTextColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontFamily, FrameworkPropertyMetadataOptions.Inherits, DataGridColumn.NotifyPropertyChangeForRefreshContent)); /// <summary> /// The font family of the desired font. /// This will only affect controls whose template uses the property /// as a parameter. On other controls, the property will do nothing. /// </summary> public FontFamily FontFamily { get { return (FontFamily)GetValue(FontFamilyProperty); } set { SetValue(FontFamilyProperty, value); } } /// <summary> /// The DependencyProperty for the FontSize property. /// Flags: Can be used in style rules /// Default Value: System Dialog Font Size /// </summary> public static readonly DependencyProperty FontSizeProperty = TextElement.FontSizeProperty.AddOwner( typeof(DataGridTextColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontSize, FrameworkPropertyMetadataOptions.Inherits, DataGridColumn.NotifyPropertyChangeForRefreshContent)); /// <summary> /// The size of the desired font. /// This will only affect controls whose template uses the property /// as a parameter. On other controls, the property will do nothing. /// </summary> [TypeConverter(typeof(FontSizeConverter))] [Localizability(LocalizationCategory.None)] public double FontSize { get { return (double)GetValue(FontSizeProperty); } set { SetValue(FontSizeProperty, value); } } /// <summary> /// The DependencyProperty for the FontStyle property. /// Flags: Can be used in style rules /// Default Value: System Dialog Font Style /// </summary> public static readonly DependencyProperty FontStyleProperty = TextElement.FontStyleProperty.AddOwner( typeof(DataGridTextColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontStyle, FrameworkPropertyMetadataOptions.Inherits, DataGridColumn.NotifyPropertyChangeForRefreshContent)); /// <summary> /// The style of the desired font. /// This will only affect controls whose template uses the property /// as a parameter. On other controls, the property will do nothing. /// </summary> public FontStyle FontStyle { get { return (FontStyle)GetValue(FontStyleProperty); } set { SetValue(FontStyleProperty, value); } } /// <summary> /// The DependencyProperty for the FontWeight property. /// Flags: Can be used in style rules /// Default Value: System Dialog Font Weight /// </summary> public static readonly DependencyProperty FontWeightProperty = TextElement.FontWeightProperty.AddOwner( typeof(DataGridTextColumn), new FrameworkPropertyMetadata(SystemFonts.MessageFontWeight, FrameworkPropertyMetadataOptions.Inherits, DataGridColumn.NotifyPropertyChangeForRefreshContent)); /// <summary> /// The weight or thickness of the desired font. /// This will only affect controls whose template uses the property /// as a parameter. On other controls, the property will do nothing. /// </summary> public FontWeight FontWeight { get { return (FontWeight)GetValue(FontWeightProperty); } set { SetValue(FontWeightProperty, value); } } /// <summary> /// The DependencyProperty for the Foreground property. /// Flags: Can be used in style rules /// Default Value: System Font Color /// </summary> public static readonly DependencyProperty ForegroundProperty = TextElement.ForegroundProperty.AddOwner( typeof(DataGridTextColumn), new FrameworkPropertyMetadata(SystemColors.ControlTextBrush, FrameworkPropertyMetadataOptions.Inherits, DataGridColumn.NotifyPropertyChangeForRefreshContent)); /// <summary> /// An brush that describes the foreground color. /// This will only affect controls whose template uses the property /// as a parameter. On other controls, the property will do nothing. /// </summary> public Brush Foreground { get { return (Brush)GetValue(ForegroundProperty); } set { SetValue(ForegroundProperty, value); } } #endregion #region Data private static Style _defaultElementStyle; private static Style _defaultEditingElementStyle; #endregion } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.ComponentModel.Design; using System.Drawing; using System.Drawing.Design; using System.Windows.Forms; namespace MyCsla.Windows { /// <summary> /// A control that encapsulates a list of radio buttons bindable in much the /// same way as a ComboBox /// </summary> [LookupBindingProperties("DataSource", "DisplayMember", "ValueMember", "SelectedValue")] [DesignerCategory("")] [ToolboxItem(true), ToolboxBitmap(typeof(BindableRadioButtons), "BindableRadioButtons.bmp")] public partial class BindableRadioButtons : UserControl { private readonly Hashtable _controlTable = new Hashtable(); private ArrayList _dataTable = new ArrayList(); /// <summary> /// Creates an instance of the BindableRadioButtons control /// </summary> public BindableRadioButtons() { InitializeComponent(); _buttonCount = 3; DoLayout(); } #region Properties private int _buttonCount = 3; private Point _buttonPadding; private object _dataSource; private FlowDirection _flowDirection = FlowDirection.TopDown; private object _selectedValue; private bool _wrapContents = true; /// <summary> /// Indicates which radiobutton is checked /// </summary> [Category("Data")] [Description("The key of the data item that is selected at any time.")] [Bindable(true)] [Browsable(false)] public object SelectedValue { get { return _selectedValue; } set { if (Select(value)) _selectedValue = value; } } /// <summary> /// Indicates the list that this control will use to get its items /// </summary> [Category("Data")] [AttributeProvider(typeof(IListSource))] //[TypeConverter("System.Windows.Forms.Design.DataSourceConverter, System.Design, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a")] [Description("Indicates the list that this control will use to get its items")] [RefreshProperties(RefreshProperties.Repaint)] public object DataSource { get { return _dataSource; } set { _dataSource = value; PrepareDataSource(); DoLayout(); } } /// <summary> /// Indicates the property to display for the items in this control. /// </summary> //, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a [Category("Data")] [Editor( "System.Windows.Forms.Design.DataMemberFieldEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" , typeof(UITypeEditor)), DefaultValue("")] public string DisplayMember { get; set; } /// <summary> /// Indicates the property to use as the actual value for the items in the control. /// </summary> [Editor( "System.Windows.Forms.Design.DataMemberFieldEditor, System.Design, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a" , typeof(UITypeEditor)), DefaultValue("")] [Category("Data")] public string ValueMember { get; set; } /// <summary> /// Number of controls do display in the designer. Has no /// run-time functionality. /// </summary> [Category("Design"), Bindable(false), Description("Number of controls do display in the designer. Has no run-time functionality.")] public int ButtonCount { get { return _buttonCount; } set { _buttonCount = value; DoLayout(); } } /// <summary> /// Generates lookup-keys automatically if true /// </summary> [DefaultValue(false)] public bool AutogenerateLookupKeys { get; set; } /// <summary> /// List a number of characters here that will be excluded from /// automatic lookup character assignment. /// </summary> [DefaultValue("")] public string UsedLookupCharacters { get; set; } /// <summary> /// The number of pixels to pad between each radio button. /// </summary> [Description("The number of pixels to pad between each radio button.")] [DefaultValue("0;0")] [Category("Layout")] public Point ButtonPadding { get { return _buttonPadding; } set { _buttonPadding = value; DoLayout(); } } /// <summary> /// In what direction the buttons are laid out /// </summary> [DefaultValue(FlowDirection.TopDown)] [Category("Layout")] public FlowDirection FlowDirection { get { return _flowDirection; } set { _flowDirection = value; DoLayout(); } } /// <summary> /// Wrap the controls /// </summary> [DefaultValue(true)] [Category("Layout")] public bool WrapContents { get { return _wrapContents; } set { _wrapContents = value; DoLayout(); } } #endregion #region Business Methods /// <summary> /// Returns a <see cref="T:System.String"/> containing the name of the <see cref="T:System.ComponentModel.Component"/>, if any. This method should not be overridden. /// </summary> /// <returns> /// A <see cref="T:System.String"/> containing the name of the <see cref="T:System.ComponentModel.Component"/>, if any, or null if the <see cref="T:System.ComponentModel.Component"/> is unnamed. /// </returns> public override string ToString() { return Name + " (" + _buttonCount + " buttons)"; } private void DoLayout() { // Init default values _dataTable = new ArrayList(); for (var i = 1; i <= _buttonCount; i++) { _dataTable.Add(new DictionaryEntry(i, "Option " + i)); } // Databind if (_dataSource != null) { var bs = (BindingSource)_dataSource; //object boundEntity = bs.DataSource; // If this is design-time & count=0, render default values instead var skipClear = false; if (bs.Count == 0) { if (GetService(typeof(IDesignerHost)) != null) { skipClear = true; } } // Fetch key-value-data if (!skipClear) _dataTable.Clear(); foreach (var o in bs) { // use reflection to get properties var t = o.GetType(); var text = t.GetProperty(DisplayMember); var value = t.GetProperty(ValueMember); if (text != null && value != null) { var oValue = value.GetValue(o, null); var oText = text.GetValue(o, null); _dataTable.Add(new DictionaryEntry(oValue, oText)); } } } // Create controls Control container = flowLayoutPanel1; flowLayoutPanel1.FlowDirection = _flowDirection; flowLayoutPanel1.WrapContents = _wrapContents; container.Controls.Clear(); _controlTable.Clear(); foreach (DictionaryEntry entry in _dataTable) { var rb = new RadioButton(); rb.Text = entry.Value.ToString(); rb.Tag = entry.Key; rb.Margin = new Padding(3, 0, _buttonPadding.X, _buttonPadding.Y); rb.AutoSize = true; //Size s = rb.Size; rb.CheckedChanged += radioButton_CheckedChanged; if (_selectedValue != null && _selectedValue.Equals(entry.Key)) rb.Checked = true; container.Controls.Add(rb); // Hash the control _controlTable.Add(entry.Key, rb); } } /// <summary> /// Automatically generates lookup keys /// </summary> private void GenerateLookupKeys() { // TODO: Implement GenerateLookupKeys() } /// <summary> /// Add listener to change in datasource or datasource's child datasource /// </summary> private void PrepareDataSource() { if (_dataSource is BindingSource) { var bs = (BindingSource)_dataSource; bs.DataSourceChanged += BindingSource_DataSourceChanged; if (bs.DataSource is BindingSource) { // If datasource's datasource change ((BindingSource)bs.DataSource).DataSourceChanged += BindingSource_DataSourceChanged; } } } /// <summary> /// Selectes the radio button with the specified key. /// If the key cannot be found, false is returned /// </summary> /// <param name="key">The key for the radio button</param> /// <returns>True if selection is performed successfully</returns> private bool Select(object key) { if (key == null || _dataTable == null || _dataTable.Count == 0) return false; var value = _controlTable[key]; if (value != null) { var rb = (RadioButton)value; rb.Checked = true; return true; } return false; } /// <summary> /// Writes to the databound objects /// </summary> private void NotifyDatabindings() { foreach (Binding binding in DataBindings) { binding.WriteValue(); } } /// <summary> /// Returns a Hashtable of the buttons in this group with the key /// set to whatever the databinding specifies in Value /// </summary> /// <returns>A hashtable of the buttons</returns> public Hashtable GetButtonTable() { return (Hashtable)_controlTable.Clone(); // Shallow copy } /// <summary> /// Returns a type-safe list of the buttons in this group /// </summary> /// <returns>a type-safe list of the buttons in this group</returns> public List<RadioButton> GetButtonList() { var list = new List<RadioButton>(); foreach (RadioButton button in _controlTable.Values) { list.Add(button); } return list; } #endregion #region Event listeners private void BindingSource_DataSourceChanged(object sender, EventArgs e) { DoLayout(); } private void radioButton_CheckedChanged(object sender, EventArgs e) { var rSender = (RadioButton)sender; if (rSender.Checked) { _selectedValue = ((RadioButton)sender).Tag; NotifyDatabindings(); DoSelectedIndexChanged(); } } private void DoSelectedIndexChanged() { if (SelectedIndexChanged != null) SelectedIndexChanged.Invoke(this, new EventArgs()); } /// <summary> /// Determines whether the specified key is a regular input key or a special key that requires preprocessing. /// </summary> /// <param name="keyData">One of the <see cref="T:System.Windows.Forms.Keys"/> values.</param> /// <returns> /// true if the specified key is a regular input key; otherwise, false. /// </returns> protected override bool IsInputKey(Keys keyData) { //switch (keyData) //{ // case Keys.Down: // case Keys.Left: // case Keys.Up: // case Keys.Right: // case Keys.Enter: // case Keys.Tab: // case Keys.ShiftKey: // return true; //} return base.IsInputKey(keyData); } //protected override void OnKeyDown(KeyEventArgs e) //{ // KeyPressed(e.KeyCode); //} //private void KeyPressed(Keys key) //{ // if (Parent == null) return; // var bindingSource = DataSource as BindingSource; // if (bindingSource == null) return; // var index = ((BindingSource) DataSource).Position; // switch (key) // { // case Keys.Up: // case Keys.Left: // this.flowLayoutPanel1.SelectNextControl(flowLayoutPanel1, false, false, true, false); // break; // case Keys.Down: // case Keys.Right: // index++; // break; // } // //Debug.Print("FlowBreak: {0}", this.flowLayoutPanel1.); // if (index < 0) index = 0; // if (index >= bindingSource.Count) index = bindingSource.Count - 1; // if (index != bindingSource.Position) // { // bindingSource.Position = index; // } //} #endregion /// <summary> /// Occurs when the selected radio button changes /// </summary> public event EventHandler SelectedIndexChanged; } }
// --------------------------------------------------------------------------- // <copyright file="UserConfiguration.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the UserConfiguration class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Xml; /// <summary> /// Represents an object that can be used to store user-defined configuration settings. /// </summary> public class UserConfiguration : IJsonSerializable { private const ExchangeVersion ObjectVersion = ExchangeVersion.Exchange2010; // For consistency with ServiceObject behavior, access to ItemId is permitted for a new object. private const UserConfigurationProperties PropertiesAvailableForNewObject = UserConfigurationProperties.BinaryData | UserConfigurationProperties.Dictionary | UserConfigurationProperties.XmlData; private const UserConfigurationProperties NoProperties = (UserConfigurationProperties)0; // TODO: Consider using SimplePropertyBag class to store XmlData & BinaryData property values. private ExchangeService service; private string name; private FolderId parentFolderId = null; private ItemId itemId = null; private UserConfigurationDictionary dictionary = null; private byte[] xmlData = null; private byte[] binaryData = null; private UserConfigurationProperties propertiesAvailableForAccess; private UserConfigurationProperties updatedProperties; /// <summary> /// Indicates whether changes trigger an update or create operation. /// </summary> private bool isNew = false; /// <summary> /// Initializes a new instance of <see cref="UserConfiguration"/> class. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> public UserConfiguration(ExchangeService service) : this(service, PropertiesAvailableForNewObject) { } /// <summary> /// Writes a byte array to Xml. /// </summary> /// <param name="writer">The writer.</param> /// <param name="byteArray">Byte array to write.</param> /// <param name="xmlElementName">Name of the Xml element.</param> private static void WriteByteArrayToXml( EwsServiceXmlWriter writer, byte[] byteArray, string xmlElementName) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteByteArrayToXml", "writer is null"); EwsUtilities.Assert( xmlElementName != null, "UserConfiguration.WriteByteArrayToXml", "xmlElementName is null"); writer.WriteStartElement(XmlNamespace.Types, xmlElementName); if (byteArray != null && byteArray.Length > 0) { writer.WriteValue(Convert.ToBase64String(byteArray), xmlElementName); } writer.WriteEndElement(); } /// <summary> /// Writes to Xml. /// </summary> /// <param name="writer">The writer.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="name">The user configuration name.</param> /// <param name="parentFolderId">The Id of the folder containing the user configuration.</param> internal static void WriteUserConfigurationNameToXml( EwsServiceXmlWriter writer, XmlNamespace xmlNamespace, string name, FolderId parentFolderId) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteUserConfigurationNameToXml", "writer is null"); EwsUtilities.Assert( name != null, "UserConfiguration.WriteUserConfigurationNameToXml", "name is null"); EwsUtilities.Assert( parentFolderId != null, "UserConfiguration.WriteUserConfigurationNameToXml", "parentFolderId is null"); writer.WriteStartElement(xmlNamespace, XmlElementNames.UserConfigurationName); writer.WriteAttributeValue(XmlAttributeNames.Name, name); parentFolderId.WriteToXml(writer); writer.WriteEndElement(); } /// <summary> /// Initializes a new instance of <see cref="UserConfiguration"/> class. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> /// <param name="requestedProperties">The properties requested for this user configuration.</param> internal UserConfiguration(ExchangeService service, UserConfigurationProperties requestedProperties) { EwsUtilities.ValidateParam(service, "service"); if (service.RequestedServerVersion < UserConfiguration.ObjectVersion) { throw new ServiceVersionException( string.Format( Strings.ObjectTypeIncompatibleWithRequestVersion, this.GetType().Name, UserConfiguration.ObjectVersion)); } this.service = service; this.isNew = true; this.InitializeProperties(requestedProperties); } /// <summary> /// Gets the name of the user configuration. /// </summary> public string Name { get { return this.name; } internal set { this.name = value; } } /// <summary> /// Gets the Id of the folder containing the user configuration. /// </summary> public FolderId ParentFolderId { get { return this.parentFolderId; } internal set { this.parentFolderId = value; } } /// <summary> /// Gets the Id of the user configuration. /// </summary> public ItemId ItemId { get { return this.itemId; } } /// <summary> /// Gets the dictionary of the user configuration. /// </summary> public UserConfigurationDictionary Dictionary { get { return this.dictionary; } } /// <summary> /// Gets or sets the xml data of the user configuration. /// </summary> public byte[] XmlData { get { this.ValidatePropertyAccess(UserConfigurationProperties.XmlData); return this.xmlData; } set { this.xmlData = value; this.MarkPropertyForUpdate(UserConfigurationProperties.XmlData); } } /// <summary> /// Gets or sets the binary data of the user configuration. /// </summary> public byte[] BinaryData { get { this.ValidatePropertyAccess(UserConfigurationProperties.BinaryData); return this.binaryData; } set { this.binaryData = value; this.MarkPropertyForUpdate(UserConfigurationProperties.BinaryData); } } /// <summary> /// Gets a value indicating whether this user configuration has been modified. /// </summary> public bool IsDirty { get { return (this.updatedProperties != NoProperties) || this.dictionary.IsDirty; } } /// <summary> /// Binds to an existing user configuration and loads the specified properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderId">The Id of the folder containing the user configuration.</param> /// <param name="properties">The properties to load.</param> /// <returns>A user configuration instance.</returns> public static UserConfiguration Bind( ExchangeService service, string name, FolderId parentFolderId, UserConfigurationProperties properties) { UserConfiguration result = service.GetUserConfiguration( name, parentFolderId, properties); result.isNew = false; return result; } /// <summary> /// Binds to an existing user configuration and loads the specified properties. /// Calling this method results in a call to EWS. /// </summary> /// <param name="service">The service to which the user configuration is bound.</param> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderName">The name of the folder containing the user configuration.</param> /// <param name="properties">The properties to load.</param> /// <returns>A user configuration instance.</returns> public static UserConfiguration Bind( ExchangeService service, string name, WellKnownFolderName parentFolderName, UserConfigurationProperties properties) { return UserConfiguration.Bind( service, name, new FolderId(parentFolderName), properties); } /// <summary> /// Saves the user configuration. Calling this method results in a call to EWS. /// </summary> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderId">The Id of the folder in which to save the user configuration.</param> public void Save(string name, FolderId parentFolderId) { EwsUtilities.ValidateParam(name, "name"); EwsUtilities.ValidateParam(parentFolderId, "parentFolderId"); parentFolderId.Validate(this.service.RequestedServerVersion); if (!this.isNew) { throw new InvalidOperationException(Strings.CannotSaveNotNewUserConfiguration); } this.parentFolderId = parentFolderId; this.name = name; this.service.CreateUserConfiguration(this); this.isNew = false; this.ResetIsDirty(); } /// <summary> /// Saves the user configuration. Calling this method results in a call to EWS. /// </summary> /// <param name="name">The name of the user configuration.</param> /// <param name="parentFolderName">The name of the folder in which to save the user configuration.</param> public void Save(string name, WellKnownFolderName parentFolderName) { this.Save(name, new FolderId(parentFolderName)); } /// <summary> /// Updates the user configuration by applying local changes to the Exchange server. /// Calling this method results in a call to EWS. /// </summary> public void Update() { if (this.isNew) { throw new InvalidOperationException(Strings.CannotUpdateNewUserConfiguration); } if (this.IsPropertyUpdated(UserConfigurationProperties.BinaryData) || this.IsPropertyUpdated(UserConfigurationProperties.Dictionary) || this.IsPropertyUpdated(UserConfigurationProperties.XmlData)) { this.service.UpdateUserConfiguration(this); } this.ResetIsDirty(); } /// <summary> /// Deletes the user configuration. Calling this method results in a call to EWS. /// </summary> public void Delete() { if (this.isNew) { throw new InvalidOperationException(Strings.DeleteInvalidForUnsavedUserConfiguration); } else { this.service.DeleteUserConfiguration(this.name, this.parentFolderId); } } /// <summary> /// Loads the specified properties on the user configuration. Calling this method results in a call to EWS. /// </summary> /// <param name="properties">The properties to load.</param> public void Load(UserConfigurationProperties properties) { this.InitializeProperties(properties); this.service.LoadPropertiesForUserConfiguration(this, properties); } /// <summary> /// Writes to XML. /// </summary> /// <param name="writer">The writer.</param> /// <param name="xmlNamespace">The XML namespace.</param> /// <param name="xmlElementName">Name of the XML element.</param> internal void WriteToXml( EwsServiceXmlWriter writer, XmlNamespace xmlNamespace, string xmlElementName) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteToXml", "writer is null"); EwsUtilities.Assert( xmlElementName != null, "UserConfiguration.WriteToXml", "xmlElementName is null"); writer.WriteStartElement(xmlNamespace, xmlElementName); // Write the UserConfigurationName element WriteUserConfigurationNameToXml( writer, XmlNamespace.Types, this.name, this.parentFolderId); // Write the Dictionary element if (this.IsPropertyUpdated(UserConfigurationProperties.Dictionary)) { this.dictionary.WriteToXml(writer, XmlElementNames.Dictionary); } // Write the XmlData element if (this.IsPropertyUpdated(UserConfigurationProperties.XmlData)) { this.WriteXmlDataToXml(writer); } // Write the BinaryData element if (this.IsPropertyUpdated(UserConfigurationProperties.BinaryData)) { this.WriteBinaryDataToXml(writer); } writer.WriteEndElement(); } /// <summary> /// Creates a JSON representation of this object. /// </summary> /// <param name="service">The service.</param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> object IJsonSerializable.ToJson(ExchangeService service) { JsonObject jsonObject = new JsonObject(); jsonObject.Add(XmlElementNames.UserConfigurationName, this.GetJsonUserConfigName(service)); jsonObject.Add(XmlElementNames.ItemId, this.itemId); // Write the Dictionary element if (this.IsPropertyUpdated(UserConfigurationProperties.Dictionary)) { jsonObject.Add(XmlElementNames.Dictionary, ((IJsonSerializable)this.dictionary).ToJson(service)); } // Write the XmlData element if (this.IsPropertyUpdated(UserConfigurationProperties.XmlData)) { jsonObject.Add(XmlElementNames.XmlData, this.GetBase64PropertyValue(this.XmlData)); } // Write the BinaryData element if (this.IsPropertyUpdated(UserConfigurationProperties.BinaryData)) { jsonObject.Add(XmlElementNames.BinaryData, this.GetBase64PropertyValue(this.BinaryData)); } return jsonObject; } /// <summary> /// Gets the name of the user config for json. /// </summary> /// <param name="service">The service.</param> /// <returns></returns> private JsonObject GetJsonUserConfigName(ExchangeService service) { FolderId parentFolderId = this.parentFolderId; string name = this.name; return GetJsonUserConfigName(service, parentFolderId, name); } /// <summary> /// Gets the name of the user config for json. /// </summary> /// <param name="service">The service.</param> /// <param name="parentFolderId">The parent folder id.</param> /// <param name="name">The name.</param> /// <returns></returns> internal static JsonObject GetJsonUserConfigName(ExchangeService service, FolderId parentFolderId, string name) { JsonObject jsonName = new JsonObject(); jsonName.Add(XmlElementNames.BaseFolderId, parentFolderId.InternalToJson(service)); jsonName.Add(XmlElementNames.Name, name); return jsonName; } /// <summary> /// Gets the base64 property value. /// </summary> /// <param name="bytes">The bytes.</param> /// <returns></returns> private string GetBase64PropertyValue(byte[] bytes) { if (bytes == null || bytes.Length == 0) { return String.Empty; } else { return Convert.ToBase64String(bytes); } } /// <summary> /// Determines whether the specified property was updated. /// </summary> /// <param name="property">property to evaluate.</param> /// <returns>Boolean indicating whether to send the property Xml.</returns> private bool IsPropertyUpdated(UserConfigurationProperties property) { bool isPropertyDirty = false; bool isPropertyEmpty = false; switch (property) { case UserConfigurationProperties.Dictionary: isPropertyDirty = this.Dictionary.IsDirty; isPropertyEmpty = this.Dictionary.Count == 0; break; case UserConfigurationProperties.XmlData: isPropertyDirty = (property & this.updatedProperties) == property; isPropertyEmpty = (this.xmlData == null) || (this.xmlData.Length == 0); break; case UserConfigurationProperties.BinaryData: isPropertyDirty = (property & this.updatedProperties) == property; isPropertyEmpty = (this.binaryData == null) || (this.binaryData.Length == 0); break; default: EwsUtilities.Assert( false, "UserConfiguration.IsPropertyUpdated", "property not supported: " + property.ToString()); break; } // Consider the property updated, if it's been modified, and either // . there's a value or // . there's no value but the operation is update. return isPropertyDirty && ((!isPropertyEmpty) || (!this.isNew)); } /// <summary> /// Writes the XmlData property to Xml. /// </summary> /// <param name="writer">The writer.</param> private void WriteXmlDataToXml(EwsServiceXmlWriter writer) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteXmlDataToXml", "writer is null"); WriteByteArrayToXml( writer, this.xmlData, XmlElementNames.XmlData); } /// <summary> /// Writes the BinaryData property to Xml. /// </summary> /// <param name="writer">The writer.</param> private void WriteBinaryDataToXml(EwsServiceXmlWriter writer) { EwsUtilities.Assert( writer != null, "UserConfiguration.WriteBinaryDataToXml", "writer is null"); WriteByteArrayToXml( writer, this.binaryData, XmlElementNames.BinaryData); } /// <summary> /// Loads from XML. /// </summary> /// <param name="reader">The reader.</param> internal void LoadFromXml(EwsServiceXmlReader reader) { EwsUtilities.Assert( reader != null, "UserConfiguration.LoadFromXml", "reader is null"); reader.ReadStartElement(XmlNamespace.Messages, XmlElementNames.UserConfiguration); reader.Read(); // Position at first property element do { if (reader.NodeType == XmlNodeType.Element) { switch (reader.LocalName) { case XmlElementNames.UserConfigurationName: string responseName = reader.ReadAttributeValue(XmlAttributeNames.Name); EwsUtilities.Assert( string.Compare(this.name, responseName, StringComparison.Ordinal) == 0, "UserConfiguration.LoadFromXml", "UserConfigurationName does not match: Expected: " + this.name + " Name in response: " + responseName); reader.SkipCurrentElement(); break; case XmlElementNames.ItemId: this.itemId = new ItemId(); this.itemId.LoadFromXml(reader, XmlElementNames.ItemId); break; case XmlElementNames.Dictionary: this.dictionary.LoadFromXml(reader, XmlElementNames.Dictionary); break; case XmlElementNames.XmlData: this.xmlData = Convert.FromBase64String(reader.ReadElementValue()); break; case XmlElementNames.BinaryData: this.binaryData = Convert.FromBase64String(reader.ReadElementValue()); break; default: EwsUtilities.Assert( false, "UserConfiguration.LoadFromXml", "Xml element not supported: " + reader.LocalName); break; } } // If XmlData was loaded, read is skipped because GetXmlData positions the reader at the next property. reader.Read(); } while (!reader.IsEndElement(XmlNamespace.Messages, XmlElementNames.UserConfiguration)); } /// <summary> /// Loads from json. /// </summary> /// <param name="responseObject">The response object.</param> /// <param name="service">The service.</param> internal void LoadFromJson(JsonObject responseObject, ExchangeService service) { foreach (string key in responseObject.Keys) { switch (key) { case XmlElementNames.UserConfigurationName: JsonObject jsonUserConfigName = responseObject.ReadAsJsonObject(key); string responseName = jsonUserConfigName.ReadAsString(XmlAttributeNames.Name); EwsUtilities.Assert( string.Compare(this.name, responseName, StringComparison.Ordinal) == 0, "UserConfiguration.LoadFromJson", "UserConfigurationName does not match: Expected: " + this.name + " Name in response: " + responseName); break; case XmlElementNames.ItemId: this.itemId = new ItemId(); this.itemId.LoadFromJson(responseObject.ReadAsJsonObject(key), service); break; case XmlElementNames.Dictionary: ((IJsonCollectionDeserializer)this.dictionary).CreateFromJsonCollection(responseObject.ReadAsArray(key), service); break; case XmlElementNames.XmlData: this.xmlData = Convert.FromBase64String(responseObject.ReadAsString(key)); break; case XmlElementNames.BinaryData: this.binaryData = Convert.FromBase64String(responseObject.ReadAsString(key)); break; default: break; } } } /// <summary> /// Initializes properties. /// </summary> /// <param name="requestedProperties">The properties requested for this UserConfiguration.</param> /// <remarks> /// InitializeProperties is called in 3 cases: /// . Create new object: From the UserConfiguration constructor. /// . Bind to existing object: Again from the constructor. The constructor is called eventually by the GetUserConfiguration request. /// . Refresh properties: From the Load method. /// </remarks> private void InitializeProperties(UserConfigurationProperties requestedProperties) { this.itemId = null; this.dictionary = new UserConfigurationDictionary(); this.xmlData = null; this.binaryData = null; this.propertiesAvailableForAccess = requestedProperties; this.ResetIsDirty(); } /// <summary> /// Resets flags to indicate that properties haven't been modified. /// </summary> private void ResetIsDirty() { this.updatedProperties = NoProperties; this.dictionary.IsDirty = false; } /// <summary> /// Determines whether the specified property may be accessed. /// </summary> /// <param name="property">Property to access.</param> private void ValidatePropertyAccess(UserConfigurationProperties property) { if ((property & this.propertiesAvailableForAccess) != property) { throw new PropertyException(Strings.MustLoadOrAssignPropertyBeforeAccess, property.ToString()); } } /// <summary> /// Adds the passed property to updatedProperties. /// </summary> /// <param name="property">Property to update.</param> private void MarkPropertyForUpdate(UserConfigurationProperties property) { this.updatedProperties |= property; this.propertiesAvailableForAccess |= property; } } }
// // DiscService.cs // // Author: // Alex Launi <alex.launi@canonical.com> // // Copyright (C) 2010 Alex Launi // // 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 Mono.Unix; using Hyena; using Banshee.ServiceStack; using Banshee.Configuration; using Banshee.Preferences; using Banshee.Hardware; using Banshee.Gui; namespace Banshee.OpticalDisc { public abstract class DiscService : IExtensionService, IDisposable { private List<DeviceCommand> unhandled_device_commands; public DiscService () { } public virtual void Initialize () { if (ServiceManager.HardwareManager == null) { throw new NotSupportedException ("DiscService cannot work when no HardwareManager is available"); } lock (this) { Sources = new Dictionary<string, DiscSource> (); // This says Cdrom, but really it means Cdrom in the general optical disc device sense. foreach (ICdromDevice device in ServiceManager.HardwareManager.GetAllCdromDevices ()) { MapDiscDevice (device); } ServiceManager.HardwareManager.DeviceAdded += OnHardwareDeviceAdded; ServiceManager.HardwareManager.DeviceRemoved += OnHardwareDeviceRemoved; ServiceManager.HardwareManager.DeviceCommand += OnDeviceCommand; } } public virtual void Dispose () { lock (this) { ServiceManager.HardwareManager.DeviceAdded -= OnHardwareDeviceAdded; ServiceManager.HardwareManager.DeviceRemoved -= OnHardwareDeviceRemoved; ServiceManager.HardwareManager.DeviceCommand -= OnDeviceCommand; foreach (DiscSource source in Sources.Values) { ServiceManager.SourceManager.RemoveSource (source); source.Dispose (); } Sources.Clear (); Sources = null; } } protected Dictionary<string, DiscSource> Sources { get; private set; } protected virtual void MapDiscDevice (ICdromDevice device) { lock (this) { foreach (IVolume volume in device) { if (volume is IDiscVolume) { MapDiscVolume ((IDiscVolume) volume); } } } } protected abstract DiscSource GetDiscSource (IDiscVolume volume); protected virtual void MapDiscVolume (IDiscVolume volume) { DiscSource source = null; lock (this) { if (Sources.ContainsKey (volume.Uuid)) { Log.Debug ("Already mapped"); return; } source = GetDiscSource (volume); if (source == null) return; Sources.Add (volume.Uuid, source); ServiceManager.SourceManager.AddSource (source); // If there are any queued device commands, see if they are to be // handled by this new volume (e.g. --device-activate-play=cdda://sr0/) try { if (unhandled_device_commands != null) { foreach (DeviceCommand command in unhandled_device_commands) { if (DeviceCommandMatchesSource (source, command)) { HandleDeviceCommand (source, command.Action); unhandled_device_commands.Remove (command); if (unhandled_device_commands.Count == 0) { unhandled_device_commands = null; } break; } } } } catch (Exception e) { Log.Error (e); } Log.DebugFormat ("Mapping disc ({0})", volume.Uuid); } } internal void UnmapDiscVolume (string uuid) { lock (this) { if (Sources.ContainsKey (uuid)) { DiscSource source = Sources[uuid]; source.StopPlayingDisc (); ServiceManager.SourceManager.RemoveSource (source); Sources.Remove (uuid); Log.DebugFormat ("Unmapping disc ({0})", uuid); } } } private void OnHardwareDeviceAdded (object o, DeviceAddedArgs args) { lock (this) { if (args.Device is ICdromDevice) { MapDiscDevice ((ICdromDevice)args.Device); } else if (args.Device is IDiscVolume) { MapDiscVolume ((IDiscVolume)args.Device); } } } private void OnHardwareDeviceRemoved (object o, DeviceRemovedArgs args) { lock (this) { UnmapDiscVolume (args.DeviceUuid); } } #region DeviceCommand Handling protected abstract bool DeviceCommandMatchesSource (DiscSource source, DeviceCommand command); protected virtual void OnDeviceCommand (object o, DeviceCommand command) { lock (this) { // Check to see if we have an already mapped disc volume that should // handle this incoming command; if not, queue it for later discs foreach (var source in Sources.Values) { if (DeviceCommandMatchesSource (source, command)) { HandleDeviceCommand (source, command.Action); return; } } if (unhandled_device_commands == null) { unhandled_device_commands = new List<DeviceCommand> (); } unhandled_device_commands.Add (command); } } protected virtual void HandleDeviceCommand (DiscSource source, DeviceCommandAction action) { if ((action & DeviceCommandAction.Activate) != 0) { ServiceManager.SourceManager.SetActiveSource (source); } if ((action & DeviceCommandAction.Play) != 0) { ServiceManager.PlaybackController.NextSource = source; if (!ServiceManager.PlayerEngine.IsPlaying ()) { ServiceManager.PlaybackController.Next (); } } } #endregion string IService.ServiceName { get { return "DiscService"; } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Search { using System; using System.Linq; using System.Collections.Generic; 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 Microsoft.Rest.Azure; using Models; /// <summary> /// ServicesOperations operations. /// </summary> internal partial class ServicesOperations : IServiceOperations<SearchManagementClient>, IServicesOperations { /// <summary> /// Initializes a new instance of the ServicesOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> internal ServicesOperations(SearchManagementClient client) { if (client == null) { throw new ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the SearchManagementClient /// </summary> public SearchManagementClient Client { get; private set; } /// <summary> /// Creates or updates a Search service in the given resource group. If the /// Search service already exists, all properties will be updated with the /// given values. /// <see href="https://msdn.microsoft.com/library/azure/dn832687.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. /// </param> /// <param name='serviceName'> /// The name of the Search service to create or update. /// </param> /// <param name='parameters'> /// The properties to set or update on the Search service. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<SearchServiceResource>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, SearchServiceCreateOrUpdateParameters parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (parameters == null) { throw new ValidationException(ValidationRules.CannotBeNull, "parameters"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "CreateOrUpdate", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{serviceName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", Uri.EscapeDataString(serviceName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("PUT"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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; if(parameters != null) { _requestContent = SafeJsonConvert.SerializeObject(parameters, this.Client.SerializationSettings); _httpRequest.Content = new StringContent(_requestContent, Encoding.UTF8); _httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 201) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SearchServiceResource>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<SearchServiceResource>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } // Deserialize Response if ((int)_statusCode == 201) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<SearchServiceResource>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Deletes a Search service in the given resource group, along with its /// associated resources. /// <see href="https://msdn.microsoft.com/library/azure/dn832692.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. /// </param> /// <param name='serviceName'> /// The name of the Search service to delete. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (serviceName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "serviceName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Delete", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices/{serviceName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{serviceName}", Uri.EscapeDataString(serviceName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("DELETE"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200 && (int)_statusCode != 404 && (int)_statusCode != 204) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); if (_httpResponse.Content != null) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); } else { _responseContent = string.Empty; } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Returns a list of all Search services in the given resource group. /// <see href="https://msdn.microsoft.com/library/azure/dn832688.aspx" /> /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group within the current subscription. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<SearchServiceListResult>> ListWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "List", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Search/searchServices").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", 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) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<SearchServiceListResult>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = SafeJsonConvert.DeserializeObject<SearchServiceListResult>(_responseContent, this.Client.DeserializationSettings); } catch (JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Security.Claims; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Identity; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.Extensions.Logging; using MeasurePortal.Models; using MeasurePortal.Models.AccountViewModels; using MeasurePortal.Services; namespace MeasurePortal.Controllers { [Authorize] public class AccountController : Controller { private readonly UserManager<ApplicationUser> _userManager; private readonly SignInManager<ApplicationUser> _signInManager; private readonly IEmailSender _emailSender; private readonly ISmsSender _smsSender; private readonly ILogger _logger; public AccountController( UserManager<ApplicationUser> userManager, SignInManager<ApplicationUser> signInManager, IEmailSender emailSender, ISmsSender smsSender, ILoggerFactory loggerFactory) { _userManager = userManager; _signInManager = signInManager; _emailSender = emailSender; _smsSender = smsSender; _logger = loggerFactory.CreateLogger<AccountController>(); } // // GET: /Account/Login [HttpGet] [AllowAnonymous] public IActionResult Login(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Login(LoginViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { // This doesn't count login failures towards account lockout // To enable password failures to trigger account lockout, set lockoutOnFailure: true var result = await _signInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, lockoutOnFailure: false); if (result.Succeeded) { _logger.LogInformation(1, "User logged in."); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); } if (result.IsLockedOut) { _logger.LogWarning(2, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid login attempt."); return View(model); } } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/Register [HttpGet] [AllowAnonymous] public IActionResult Register(string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> Register(RegisterViewModel model, string returnUrl = null) { ViewData["ReturnUrl"] = returnUrl; if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user, model.Password); if (result.Succeeded) { // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GenerateEmailConfirmationTokenAsync(user); //var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Confirm your account", // $"Please confirm your account by clicking this link: <a href='{callbackUrl}'>link</a>"); await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(3, "User created a new account with password."); return RedirectToLocal(returnUrl); } AddErrors(result); } // If we got this far, something failed, redisplay form return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> LogOff() { await _signInManager.SignOutAsync(); _logger.LogInformation(4, "User logged out."); return RedirectToAction(nameof(HomeController.Index), "Home"); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public IActionResult ExternalLogin(string provider, string returnUrl = null) { // Request a redirect to the external login provider. var redirectUrl = Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }); var properties = _signInManager.ConfigureExternalAuthenticationProperties(provider, redirectUrl); return Challenge(properties, provider); } // // GET: /Account/ExternalLoginCallback [HttpGet] [AllowAnonymous] public async Task<IActionResult> ExternalLoginCallback(string returnUrl = null, string remoteError = null) { if (remoteError != null) { ModelState.AddModelError(string.Empty, $"Error from external provider: {remoteError}"); return View(nameof(Login)); } var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return RedirectToAction(nameof(Login)); } // Sign in the user with this external login provider if the user already has a login. var result = await _signInManager.ExternalLoginSignInAsync(info.LoginProvider, info.ProviderKey, isPersistent: false); if (result.Succeeded) { _logger.LogInformation(5, "User logged in with {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } if (result.RequiresTwoFactor) { return RedirectToAction(nameof(SendCode), new { ReturnUrl = returnUrl }); } if (result.IsLockedOut) { return View("Lockout"); } else { // If the user does not have an account, then ask the user to create an account. ViewData["ReturnUrl"] = returnUrl; ViewData["LoginProvider"] = info.LoginProvider; var email = info.Principal.FindFirstValue(ClaimTypes.Email); return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl = null) { if (ModelState.IsValid) { // Get the information about the user from the external login provider var info = await _signInManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await _userManager.CreateAsync(user); if (result.Succeeded) { result = await _userManager.AddLoginAsync(user, info); if (result.Succeeded) { await _signInManager.SignInAsync(user, isPersistent: false); _logger.LogInformation(6, "User created an account using {Name} provider.", info.LoginProvider); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewData["ReturnUrl"] = returnUrl; return View(model); } // GET: /Account/ConfirmEmail [HttpGet] [AllowAnonymous] public async Task<IActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var user = await _userManager.FindByIdAsync(userId); if (user == null) { return View("Error"); } var result = await _userManager.ConfirmEmailAsync(user, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [HttpGet] [AllowAnonymous] public IActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await _userManager.FindByNameAsync(model.Email); if (user == null || !(await _userManager.IsEmailConfirmedAsync(user))) { // Don't reveal that the user does not exist or is not confirmed return View("ForgotPasswordConfirmation"); } // For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=532713 // Send an email with this link //var code = await _userManager.GeneratePasswordResetTokenAsync(user); //var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: HttpContext.Request.Scheme); //await _emailSender.SendEmailAsync(model.Email, "Reset Password", // $"Please reset your password by clicking here: <a href='{callbackUrl}'>link</a>"); //return View("ForgotPasswordConfirmation"); } // If we got this far, something failed, redisplay form return View(model); } // // GET: /Account/ForgotPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [HttpGet] [AllowAnonymous] public IActionResult ResetPassword(string code = null) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await _userManager.FindByNameAsync(model.Email); if (user == null) { // Don't reveal that the user does not exist return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } var result = await _userManager.ResetPasswordAsync(user, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction(nameof(AccountController.ResetPasswordConfirmation), "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [HttpGet] [AllowAnonymous] public IActionResult ResetPasswordConfirmation() { return View(); } // // GET: /Account/SendCode [HttpGet] [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl = null, bool rememberMe = false) { var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } var userFactors = await _userManager.GetValidTwoFactorProvidersAsync(user); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } // Generate the token and send it var code = await _userManager.GenerateTwoFactorTokenAsync(user, model.SelectedProvider); if (string.IsNullOrWhiteSpace(code)) { return View("Error"); } var message = "Your security code is: " + code; if (model.SelectedProvider == "Email") { await _emailSender.SendEmailAsync(await _userManager.GetEmailAsync(user), "Security Code", message); } else if (model.SelectedProvider == "Phone") { await _smsSender.SendSmsAsync(await _userManager.GetPhoneNumberAsync(user), message); } return RedirectToAction(nameof(VerifyCode), new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/VerifyCode [HttpGet] [AllowAnonymous] public async Task<IActionResult> VerifyCode(string provider, bool rememberMe, string returnUrl = null) { // Require that the user has already logged in via username/password or external login var user = await _signInManager.GetTwoFactorAuthenticationUserAsync(); if (user == null) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<IActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // The following code protects for brute force attacks against the two factor codes. // If a user enters incorrect codes for a specified amount of time then the user account // will be locked out for a specified amount of time. var result = await _signInManager.TwoFactorSignInAsync(model.Provider, model.Code, model.RememberMe, model.RememberBrowser); if (result.Succeeded) { return RedirectToLocal(model.ReturnUrl); } if (result.IsLockedOut) { _logger.LogWarning(7, "User account locked out."); return View("Lockout"); } else { ModelState.AddModelError(string.Empty, "Invalid code."); return View(model); } } #region Helpers private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError(string.Empty, error.Description); } } private Task<ApplicationUser> GetCurrentUserAsync() { return _userManager.GetUserAsync(HttpContext.User); } private IActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } else { return RedirectToAction(nameof(HomeController.Index), "Home"); } } #endregion } }
/* * Vericred API * * Vericred's API allows you to search for Health Plans that a specific doctor accepts. ## Getting Started Visit our [Developer Portal](https://developers.vericred.com) to create an account. Once you have created an account, you can create one Application for Production and another for our Sandbox (select the appropriate Plan when you create the Application). ## SDKs Our API follows standard REST conventions, so you can use any HTTP client to integrate with us. You will likely find it easier to use one of our [autogenerated SDKs](https://github.com/vericred/?query=vericred-), which we make available for several common programming languages. ## Authentication To authenticate, pass the API Key you created in the Developer Portal as a `Vericred-Api-Key` header. `curl -H 'Vericred-Api-Key: YOUR_KEY' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Versioning Vericred's API default to the latest version. However, if you need a specific version, you can request it with an `Accept-Version` header. The current version is `v3`. Previous versions are `v1` and `v2`. `curl -H 'Vericred-Api-Key: YOUR_KEY' -H 'Accept-Version: v2' "https://api.vericred.com/providers?search_term=Foo&zip_code=11215"` ## Pagination Endpoints that accept `page` and `per_page` parameters are paginated. They expose four additional fields that contain data about your position in the response, namely `Total`, `Per-Page`, `Link`, and `Page` as described in [RFC-5988](https://tools.ietf.org/html/rfc5988). For example, to display 5 results per page and view the second page of a `GET` to `/networks`, your final request would be `GET /networks?....page=2&per_page=5`. ## Sideloading When we return multiple levels of an object graph (e.g. `Provider`s and their `State`s we sideload the associated data. In this example, we would provide an Array of `State`s and a `state_id` for each provider. This is done primarily to reduce the payload size since many of the `Provider`s will share a `State` ``` { providers: [{ id: 1, state_id: 1}, { id: 2, state_id: 1 }], states: [{ id: 1, code: 'NY' }] } ``` If you need the second level of the object graph, you can just match the corresponding id. ## Selecting specific data All endpoints allow you to specify which fields you would like to return. This allows you to limit the response to contain only the data you need. For example, let's take a request that returns the following JSON by default ``` { provider: { id: 1, name: 'John', phone: '1234567890', field_we_dont_care_about: 'value_we_dont_care_about' }, states: [{ id: 1, name: 'New York', code: 'NY', field_we_dont_care_about: 'value_we_dont_care_about' }] } ``` To limit our results to only return the fields we care about, we specify the `select` query string parameter for the corresponding fields in the JSON document. In this case, we want to select `name` and `phone` from the `provider` key, so we would add the parameters `select=provider.name,provider.phone`. We also want the `name` and `code` from the `states` key, so we would add the parameters `select=states.name,staes.code`. The id field of each document is always returned whether or not it is requested. Our final request would be `GET /providers/12345?select=provider.name,provider.phone,states.name,states.code` The response would be ``` { provider: { id: 1, name: 'John', phone: '1234567890' }, states: [{ id: 1, name: 'New York', code: 'NY' }] } ``` ## Benefits summary format Benefit cost-share strings are formatted to capture: * Network tiers * Compound or conditional cost-share * Limits on the cost-share * Benefit-specific maximum out-of-pocket costs **Example #1** As an example, we would represent [this Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/33602TX0780032.pdf) as: * **Hospital stay facility fees**: - Network Provider: `$400 copay/admit plus 20% coinsurance` - Out-of-Network Provider: `$1,500 copay/admit plus 50% coinsurance` - Vericred's format for this benefit: `In-Network: $400 before deductible then 20% after deductible / Out-of-Network: $1,500 before deductible then 50% after deductible` * **Rehabilitation services:** - Network Provider: `20% coinsurance` - Out-of-Network Provider: `50% coinsurance` - Limitations & Exceptions: `35 visit maximum per benefit period combined with Chiropractic care.` - Vericred's format for this benefit: `In-Network: 20% after deductible / Out-of-Network: 50% after deductible | limit: 35 visit(s) per Benefit Period` **Example #2** In [this other Summary of Benefits &amp; Coverage](https://s3.amazonaws.com/vericred-data/SBC/2017/40733CA0110568.pdf), the **specialty_drugs** cost-share has a maximum out-of-pocket for in-network pharmacies. * **Specialty drugs:** - Network Provider: `40% coinsurance up to a $500 maximum for up to a 30 day supply` - Out-of-Network Provider `Not covered` - Vericred's format for this benefit: `In-Network: 40% after deductible, up to $500 per script / Out-of-Network: 100%` **BNF** Here's a description of the benefits summary string, represented as a context-free grammar: ``` <cost-share> ::= <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> <tier-limit> "/" <tier> <opt-num-prefix> <value> <opt-per-unit> <deductible> "|" <benefit-limit> <tier> ::= "In-Network:" | "In-Network-Tier-2:" | "Out-of-Network:" <opt-num-prefix> ::= "first" <num> <unit> | "" <unit> ::= "day(s)" | "visit(s)" | "exam(s)" | "item(s)" <value> ::= <ddct_moop> | <copay> | <coinsurance> | <compound> | "unknown" | "Not Applicable" <compound> ::= <copay> <deductible> "then" <coinsurance> <deductible> | <copay> <deductible> "then" <copay> <deductible> | <coinsurance> <deductible> "then" <coinsurance> <deductible> <copay> ::= "$" <num> <coinsurace> ::= <num> "%" <ddct_moop> ::= <copay> | "Included in Medical" | "Unlimited" <opt-per-unit> ::= "per day" | "per visit" | "per stay" | "" <deductible> ::= "before deductible" | "after deductible" | "" <tier-limit> ::= ", " <limit> | "" <benefit-limit> ::= <limit> | "" ``` * * OpenAPI spec version: 1.0.0 * * Generated by: https://github.com/swagger-api/swagger-codegen.git * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using RestSharp; using IO.Vericred.Client; using IO.Vericred.Model; namespace IO.Vericred.Api { /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public interface IZipCountiesApi : IApiAccessor { #region Synchronous Operations /// <summary> /// Search for Zip Counties /// </summary> /// <remarks> /// Our &#x60;Plan&#x60; endpoints require a zip code and a fips (county) code. This is because plan pricing requires both of these elements. Users are unlikely to know their fips code, so we provide this endpoint to look up a &#x60;ZipCounty&#x60; by zip code and return both the selected zip and fips codes. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="zipPrefix">Partial five-digit Zip</param> /// <returns>ZipCountyResponse</returns> ZipCountyResponse GetZipCounties (string zipPrefix); /// <summary> /// Search for Zip Counties /// </summary> /// <remarks> /// Our &#x60;Plan&#x60; endpoints require a zip code and a fips (county) code. This is because plan pricing requires both of these elements. Users are unlikely to know their fips code, so we provide this endpoint to look up a &#x60;ZipCounty&#x60; by zip code and return both the selected zip and fips codes. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="zipPrefix">Partial five-digit Zip</param> /// <returns>ApiResponse of ZipCountyResponse</returns> ApiResponse<ZipCountyResponse> GetZipCountiesWithHttpInfo (string zipPrefix); #endregion Synchronous Operations #region Asynchronous Operations /// <summary> /// Search for Zip Counties /// </summary> /// <remarks> /// Our &#x60;Plan&#x60; endpoints require a zip code and a fips (county) code. This is because plan pricing requires both of these elements. Users are unlikely to know their fips code, so we provide this endpoint to look up a &#x60;ZipCounty&#x60; by zip code and return both the selected zip and fips codes. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="zipPrefix">Partial five-digit Zip</param> /// <returns>Task of ZipCountyResponse</returns> System.Threading.Tasks.Task<ZipCountyResponse> GetZipCountiesAsync (string zipPrefix); /// <summary> /// Search for Zip Counties /// </summary> /// <remarks> /// Our &#x60;Plan&#x60; endpoints require a zip code and a fips (county) code. This is because plan pricing requires both of these elements. Users are unlikely to know their fips code, so we provide this endpoint to look up a &#x60;ZipCounty&#x60; by zip code and return both the selected zip and fips codes. /// </remarks> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="zipPrefix">Partial five-digit Zip</param> /// <returns>Task of ApiResponse (ZipCountyResponse)</returns> System.Threading.Tasks.Task<ApiResponse<ZipCountyResponse>> GetZipCountiesAsyncWithHttpInfo (string zipPrefix); #endregion Asynchronous Operations } /// <summary> /// Represents a collection of functions to interact with the API endpoints /// </summary> public partial class ZipCountiesApi : IZipCountiesApi { private IO.Vericred.Client.ExceptionFactory _exceptionFactory = (name, response) => null; /// <summary> /// Initializes a new instance of the <see cref="ZipCountiesApi"/> class. /// </summary> /// <returns></returns> public ZipCountiesApi(String basePath) { this.Configuration = new Configuration(new ApiClient(basePath)); ExceptionFactory = IO.Vericred.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Initializes a new instance of the <see cref="ZipCountiesApi"/> class /// using Configuration object /// </summary> /// <param name="configuration">An instance of Configuration</param> /// <returns></returns> public ZipCountiesApi(Configuration configuration = null) { if (configuration == null) // use the default one in Configuration this.Configuration = Configuration.Default; else this.Configuration = configuration; ExceptionFactory = IO.Vericred.Client.Configuration.DefaultExceptionFactory; // ensure API client has configuration ready if (Configuration.ApiClient.Configuration == null) { this.Configuration.ApiClient.Configuration = this.Configuration; } } /// <summary> /// Gets the base path of the API client. /// </summary> /// <value>The base path</value> public String GetBasePath() { return this.Configuration.ApiClient.RestClient.BaseUrl.ToString(); } /// <summary> /// Sets the base path of the API client. /// </summary> /// <value>The base path</value> [Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")] public void SetBasePath(String basePath) { // do nothing } /// <summary> /// Gets or sets the configuration object /// </summary> /// <value>An instance of the Configuration</value> public Configuration Configuration {get; set;} /// <summary> /// Provides a factory method hook for the creation of exceptions. /// </summary> public IO.Vericred.Client.ExceptionFactory ExceptionFactory { get { if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1) { throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported."); } return _exceptionFactory; } set { _exceptionFactory = value; } } /// <summary> /// Gets the default header. /// </summary> /// <returns>Dictionary of HTTP header</returns> [Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")] public Dictionary<String, String> DefaultHeader() { return this.Configuration.DefaultHeader; } /// <summary> /// Add default header. /// </summary> /// <param name="key">Header field name.</param> /// <param name="value">Header field value.</param> /// <returns></returns> [Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")] public void AddDefaultHeader(string key, string value) { this.Configuration.AddDefaultHeader(key, value); } /// <summary> /// Search for Zip Counties Our &#x60;Plan&#x60; endpoints require a zip code and a fips (county) code. This is because plan pricing requires both of these elements. Users are unlikely to know their fips code, so we provide this endpoint to look up a &#x60;ZipCounty&#x60; by zip code and return both the selected zip and fips codes. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="zipPrefix">Partial five-digit Zip</param> /// <returns>ZipCountyResponse</returns> public ZipCountyResponse GetZipCounties (string zipPrefix) { ApiResponse<ZipCountyResponse> localVarResponse = GetZipCountiesWithHttpInfo(zipPrefix); return localVarResponse.Data; } /// <summary> /// Search for Zip Counties Our &#x60;Plan&#x60; endpoints require a zip code and a fips (county) code. This is because plan pricing requires both of these elements. Users are unlikely to know their fips code, so we provide this endpoint to look up a &#x60;ZipCounty&#x60; by zip code and return both the selected zip and fips codes. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="zipPrefix">Partial five-digit Zip</param> /// <returns>ApiResponse of ZipCountyResponse</returns> public ApiResponse< ZipCountyResponse > GetZipCountiesWithHttpInfo (string zipPrefix) { // verify the required parameter 'zipPrefix' is set if (zipPrefix == null) throw new ApiException(400, "Missing required parameter 'zipPrefix' when calling ZipCountiesApi->GetZipCounties"); var localVarPath = "/zip_counties"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (zipPrefix != null) localVarQueryParams.Add("zip_prefix", Configuration.ApiClient.ParameterToString(zipPrefix)); // query parameter // authentication (Vericred-Api-Key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"))) { localVarHeaderParams["Vericred-Api-Key"] = Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetZipCounties", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ZipCountyResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ZipCountyResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ZipCountyResponse))); } /// <summary> /// Search for Zip Counties Our &#x60;Plan&#x60; endpoints require a zip code and a fips (county) code. This is because plan pricing requires both of these elements. Users are unlikely to know their fips code, so we provide this endpoint to look up a &#x60;ZipCounty&#x60; by zip code and return both the selected zip and fips codes. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="zipPrefix">Partial five-digit Zip</param> /// <returns>Task of ZipCountyResponse</returns> public async System.Threading.Tasks.Task<ZipCountyResponse> GetZipCountiesAsync (string zipPrefix) { ApiResponse<ZipCountyResponse> localVarResponse = await GetZipCountiesAsyncWithHttpInfo(zipPrefix); return localVarResponse.Data; } /// <summary> /// Search for Zip Counties Our &#x60;Plan&#x60; endpoints require a zip code and a fips (county) code. This is because plan pricing requires both of these elements. Users are unlikely to know their fips code, so we provide this endpoint to look up a &#x60;ZipCounty&#x60; by zip code and return both the selected zip and fips codes. /// </summary> /// <exception cref="IO.Vericred.Client.ApiException">Thrown when fails to make API call</exception> /// <param name="zipPrefix">Partial five-digit Zip</param> /// <returns>Task of ApiResponse (ZipCountyResponse)</returns> public async System.Threading.Tasks.Task<ApiResponse<ZipCountyResponse>> GetZipCountiesAsyncWithHttpInfo (string zipPrefix) { // verify the required parameter 'zipPrefix' is set if (zipPrefix == null) throw new ApiException(400, "Missing required parameter 'zipPrefix' when calling ZipCountiesApi->GetZipCounties"); var localVarPath = "/zip_counties"; var localVarPathParams = new Dictionary<String, String>(); var localVarQueryParams = new Dictionary<String, String>(); var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader); var localVarFormParams = new Dictionary<String, String>(); var localVarFileParams = new Dictionary<String, FileParameter>(); Object localVarPostBody = null; // to determine the Content-Type header String[] localVarHttpContentTypes = new String[] { }; String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes); // to determine the Accept header String[] localVarHttpHeaderAccepts = new String[] { }; String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts); if (localVarHttpHeaderAccept != null) localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept); // set "format" to json by default // e.g. /pet/{petId}.{format} becomes /pet/{petId}.json localVarPathParams.Add("format", "json"); if (zipPrefix != null) localVarQueryParams.Add("zip_prefix", Configuration.ApiClient.ParameterToString(zipPrefix)); // query parameter // authentication (Vericred-Api-Key) required if (!String.IsNullOrEmpty(Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"))) { localVarHeaderParams["Vericred-Api-Key"] = Configuration.GetApiKeyWithPrefix("Vericred-Api-Key"); } // make the HTTP request IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath, Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams, localVarPathParams, localVarHttpContentType); int localVarStatusCode = (int) localVarResponse.StatusCode; if (ExceptionFactory != null) { Exception exception = ExceptionFactory("GetZipCounties", localVarResponse); if (exception != null) throw exception; } return new ApiResponse<ZipCountyResponse>(localVarStatusCode, localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()), (ZipCountyResponse) Configuration.ApiClient.Deserialize(localVarResponse, typeof(ZipCountyResponse))); } } }
// 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. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // // // A simple coordination data structure that we use for fork/join style parallelism. // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System; using System.Runtime.InteropServices; using System.Threading; using System.Diagnostics; using System.Diagnostics.Contracts; namespace System.Threading { /// <summary> /// Represents a synchronization primitive that is signaled when its count reaches zero. /// </summary> /// <remarks> /// All public and protected members of <see cref="CountdownEvent"/> are thread-safe and may be used /// concurrently from multiple threads, with the exception of Dispose, which /// must only be used when all other operations on the <see cref="CountdownEvent"/> have /// completed, and Reset, which should only be used when no other threads are /// accessing the event. /// </remarks> [DebuggerDisplay("Initial Count={InitialCount}, Current Count={CurrentCount}")] public class CountdownEvent : IDisposable { // CountdownEvent is a simple synchronization primitive used for fork/join parallelism. We create a // latch with a count of N; threads then signal the latch, which decrements N by 1; other threads can // wait on the latch at any point; when the latch count reaches 0, all threads are woken and // subsequent waiters return without waiting. The implementation internally lazily creates a true // Win32 event as needed. We also use some amount of spinning on MP machines before falling back to a // wait. private int m_initialCount; // The original # of signals the latch was instantiated with. private volatile int m_currentCount; // The # of outstanding signals before the latch transitions to a signaled state. private ManualResetEventSlim m_event; // An event used to manage blocking and signaling. private volatile bool m_disposed; // Whether the latch has been disposed. /// <summary> /// Initializes a new instance of <see cref="T:System.Threading.CountdownEvent"/> class with the /// specified count. /// </summary> /// <param name="initialCount">The number of signals required to set the <see /// cref="T:System.Threading.CountdownEvent"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="initialCount"/> is less /// than 0.</exception> public CountdownEvent(int initialCount) { if (initialCount < 0) { throw new ArgumentOutOfRangeException(nameof(initialCount)); } m_initialCount = initialCount; m_currentCount = initialCount; // Allocate a thin event, which internally defers creation of an actual Win32 event. m_event = new ManualResetEventSlim(); // If the latch was created with a count of 0, then it's already in the signaled state. if (initialCount == 0) { m_event.Set(); } } /// <summary> /// Gets the number of remaining signals required to set the event. /// </summary> /// <value> /// The number of remaining signals required to set the event. /// </value> public int CurrentCount { get { int observedCount = m_currentCount; return observedCount < 0 ? 0 : observedCount; } } /// <summary> /// Gets the numbers of signals initially required to set the event. /// </summary> /// <value> /// The number of signals initially required to set the event. /// </value> public int InitialCount { get { return m_initialCount; } } /// <summary> /// Determines whether the event is set. /// </summary> /// <value>true if the event is set; otherwise, false.</value> public bool IsSet { get { // The latch is "completed" if its current count has reached 0. Note that this is NOT // the same thing is checking the event's IsCompleted property. There is a tiny window // of time, after the final decrement of the current count to 0 and before setting the // event, where the two values are out of sync. return (m_currentCount <= 0); } } /// <summary> /// Gets a <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set. /// </summary> /// <value>A <see cref="T:System.Threading.WaitHandle"/> that is used to wait for the event to be set.</value> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been disposed.</exception> /// <remarks> /// <see cref="WaitHandle"/> should only be used if it's needed for integration with code bases /// that rely on having a WaitHandle. If all that's needed is to wait for the <see cref="CountdownEvent"/> /// to be set, the <see cref="Wait()"/> method should be preferred. /// </remarks> public WaitHandle WaitHandle { get { ThrowIfDisposed(); return m_event.WaitHandle; } } /// <summary> /// Releases all resources used by the current instance of <see cref="T:System.Threading.CountdownEvent"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> public void Dispose() { // Gets rid of this latch's associated resources. This can consist of a Win32 event // which is (lazily) allocated by the underlying thin event. This method is not safe to // call concurrently -- i.e. a caller must coordinate to ensure only one thread is using // the latch at the time of the call to Dispose. Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// When overridden in a derived class, releases the unmanaged resources used by the /// <see cref="T:System.Threading.CountdownEvent"/>, 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> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, <see cref="Dispose()"/> is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> protected virtual void Dispose(bool disposing) { if (disposing) { m_event.Dispose(); m_disposed = true; } } /// <summary> /// Registers a signal with the <see cref="T:System.Threading.CountdownEvent"/>, decrementing its /// count. /// </summary> /// <returns>true if the signal caused the count to reach zero and the event was set; otherwise, /// false.</returns> /// <exception cref="T:System.InvalidOperationException">The current instance is already set. /// </exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Signal() { ThrowIfDisposed(); Debug.Assert(m_event != null); if (m_currentCount <= 0) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero")); } #pragma warning disable 0420 int newCount = Interlocked.Decrement(ref m_currentCount); #pragma warning restore 0420 if (newCount == 0) { m_event.Set(); return true; } else if (newCount < 0) { //if the count is decremented below zero, then throw, it's OK to keep the count negative, and we shouldn't set the event here //because there was a thread already which decremented it to zero and set the event throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero")); } return false; } /// <summary> /// Registers multiple signals with the <see cref="T:System.Threading.CountdownEvent"/>, /// decrementing its count by the specified amount. /// </summary> /// <param name="signalCount">The number of signals to register.</param> /// <returns>true if the signals caused the count to reach zero and the event was set; otherwise, /// false.</returns> /// <exception cref="T:System.InvalidOperationException"> /// The current instance is already set. -or- Or <paramref name="signalCount"/> is greater than <see /// cref="CurrentCount"/>. /// </exception> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less /// than 1.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Signal(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException(nameof(signalCount)); } ThrowIfDisposed(); Debug.Assert(m_event != null); int observedCount; SpinWait spin = new SpinWait(); while (true) { observedCount = m_currentCount; // If the latch is already signaled, we will fail. if (observedCount < signalCount) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Decrement_BelowZero")); } // This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning // for this statement. This warning is clearly senseless for Interlocked operations. #pragma warning disable 0420 if (Interlocked.CompareExchange(ref m_currentCount, observedCount - signalCount, observedCount) == observedCount) #pragma warning restore 0420 { break; } // The CAS failed. Spin briefly and try again. spin.SpinOnce(); } // If we were the last to signal, set the event. if (observedCount == signalCount) { m_event.Set(); return true; } Debug.Assert(m_currentCount >= 0, "latch was decremented below zero"); return false; } /// <summary> /// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one. /// </summary> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException"> /// The current instance has already been disposed. /// </exception> public void AddCount() { AddCount(1); } /// <summary> /// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by one. /// </summary> /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is /// already at zero. this will return false.</returns> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool TryAddCount() { return TryAddCount(1); } /// <summary> /// Increments the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a specified /// value. /// </summary> /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less than /// 0.</exception> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void AddCount(int signalCount) { if (!TryAddCount(signalCount)) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Increment_AlreadyZero")); } } /// <summary> /// Attempts to increment the <see cref="T:System.Threading.CountdownEvent"/>'s current count by a /// specified value. /// </summary> /// <param name="signalCount">The value by which to increase <see cref="CurrentCount"/>.</param> /// <returns>true if the increment succeeded; otherwise, false. If <see cref="CurrentCount"/> is /// already at zero this will return false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="signalCount"/> is less /// than 0.</exception> /// <exception cref="T:System.InvalidOperationException">The current instance is already /// set.</exception> /// <exception cref="T:System.InvalidOperationException"><see cref="CurrentCount"/> is equal to <see /// cref="T:System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool TryAddCount(int signalCount) { if (signalCount <= 0) { throw new ArgumentOutOfRangeException(nameof(signalCount)); } ThrowIfDisposed(); // Loop around until we successfully increment the count. int observedCount; SpinWait spin = new SpinWait(); while (true) { observedCount = m_currentCount; if (observedCount <= 0) { return false; } else if (observedCount > (Int32.MaxValue - signalCount)) { throw new InvalidOperationException(Environment.GetResourceString("CountdownEvent_Increment_AlreadyMax")); } // This disables the "CS0420: a reference to a volatile field will not be treated as volatile" warning // for this statement. This warning is clearly senseless for Interlocked operations. #pragma warning disable 0420 if (Interlocked.CompareExchange(ref m_currentCount, observedCount + signalCount, observedCount) == observedCount) #pragma warning restore 0420 { break; } // The CAS failed. Spin briefly and try again. spin.SpinOnce(); } return true; } /// <summary> /// Resets the <see cref="CurrentCount"/> to the value of <see cref="InitialCount"/>. /// </summary> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed..</exception> public void Reset() { Reset(m_initialCount); } /// <summary> /// Resets the <see cref="CurrentCount"/> to a specified value. /// </summary> /// <param name="count">The number of signals required to set the <see /// cref="T:System.Threading.CountdownEvent"/>.</param> /// <remarks> /// Unlike most of the members of <see cref="CountdownEvent"/>, Reset is not /// thread-safe and may not be used concurrently with other members of this instance. /// </remarks> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="count"/> is /// less than 0.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has alread been disposed.</exception> public void Reset(int count) { ThrowIfDisposed(); if (count < 0) { throw new ArgumentOutOfRangeException(nameof(count)); } m_currentCount = count; m_initialCount = count; if (count == 0) { m_event.Set(); } else { m_event.Reset(); } } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set. /// </summary> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. /// </remarks> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void Wait() { Wait(Timeout.Infinite, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, while /// observing a <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <remarks> /// The caller of this method blocks indefinitely until the current instance is set. The caller will /// return immediately if the event is currently in a set state. If the /// <see cref="T:System.Threading.CancellationToken">CancellationToken</see> being observed /// is canceled during the wait operation, an <see cref="T:System.OperationCanceledException"/> /// will be thrown. /// </remarks> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has been /// canceled.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public void Wait(CancellationToken cancellationToken) { Wait(Timeout.Infinite, cancellationToken); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// <see cref="T:System.TimeSpan"/> to measure the time interval. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Wait(TimeSpan timeout) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using /// a <see cref="T:System.TimeSpan"/> to measure the time interval, while observing a /// <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="timeout">A <see cref="T:System.TimeSpan"/> that represents the number of /// milliseconds to wait, or a <see cref="T:System.TimeSpan"/> that represents -1 milliseconds to /// wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="T:System.ArgumentOutOfRangeException"><paramref name="timeout"/> is a negative /// number other than -1 milliseconds, which represents an infinite time-out -or- timeout is greater /// than <see cref="System.Int32.MaxValue"/>.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has /// been canceled.</exception> public bool Wait(TimeSpan timeout, CancellationToken cancellationToken) { long totalMilliseconds = (long)timeout.TotalMilliseconds; if (totalMilliseconds < -1 || totalMilliseconds > int.MaxValue) { throw new ArgumentOutOfRangeException(nameof(timeout)); } return Wait((int)totalMilliseconds, cancellationToken); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// 32-bit signed integer to measure the time interval. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> public bool Wait(int millisecondsTimeout) { return Wait(millisecondsTimeout, new CancellationToken()); } /// <summary> /// Blocks the current thread until the <see cref="T:System.Threading.CountdownEvent"/> is set, using a /// 32-bit signed integer to measure the time interval, while observing a /// <see cref="T:System.Threading.CancellationToken"/>. /// </summary> /// <param name="millisecondsTimeout">The number of milliseconds to wait, or <see /// cref="Timeout.Infinite"/>(-1) to wait indefinitely.</param> /// <param name="cancellationToken">The <see cref="T:System.Threading.CancellationToken"/> to /// observe.</param> /// <returns>true if the <see cref="System.Threading.CountdownEvent"/> was set; otherwise, /// false.</returns> /// <exception cref="ArgumentOutOfRangeException"><paramref name="millisecondsTimeout"/> is a /// negative number other than -1, which represents an infinite time-out.</exception> /// <exception cref="T:System.ObjectDisposedException">The current instance has already been /// disposed.</exception> /// <exception cref="T:System.OperationCanceledException"><paramref name="cancellationToken"/> has /// been canceled.</exception> public bool Wait(int millisecondsTimeout, CancellationToken cancellationToken) { if (millisecondsTimeout < -1) { throw new ArgumentOutOfRangeException(nameof(millisecondsTimeout)); } ThrowIfDisposed(); cancellationToken.ThrowIfCancellationRequested(); bool returnValue = IsSet; // If not completed yet, wait on the event. if (!returnValue) { // ** the actual wait returnValue = m_event.Wait(millisecondsTimeout, cancellationToken); //the Wait will throw OCE itself if the token is canceled. } return returnValue; } // -------------------------------------- // Private methods /// <summary> /// Throws an exception if the latch has been disposed. /// </summary> private void ThrowIfDisposed() { if (m_disposed) { throw new ObjectDisposedException("CountdownEvent"); } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ using System; using System.Collections.Generic; using System.Linq; using Adxstudio.Xrm.Cms; using Adxstudio.Xrm.Resources; using Microsoft.Xrm.Client; using Microsoft.Xrm.Client.Diagnostics; using Microsoft.Xrm.Client.Messages; using Microsoft.Xrm.Client.Metadata; using Microsoft.Xrm.Client.Security; using Microsoft.Xrm.Portal.Web.Data.Services; using Microsoft.Xrm.Sdk; using Microsoft.Xrm.Sdk.Client; namespace Adxstudio.Xrm.Web.Handlers.ElFinder { /// <summary> /// Handler for elFinder "rm" command. /// </summary> /// <remarks> /// Delete file or directory (recursive) (http://elrte.org/redmine/projects/elfinder/wiki/Client-Server_Protocol_EN#rm). /// /// Arguments: /// /// - cmd : rm /// - current : hash of directory from where to delete /// - targets : array of hashes of files/directories to delete /// /// Response: open with directory tree, on errors add error and errorData. /// </remarks> public class RmCommand : ICommand { public CommandResponse GetResponse(ICommandContext commandContext) { var fileSystem = commandContext.CreateFileSystem(); var hash = commandContext.Parameters["current"]; DirectoryContentHash cwd; if (!DirectoryContentHash.TryParse(hash, out cwd)) { return new ErrorCommandResponse { error = ResourceManager.GetString("Unable_To_Retrieve_Current_Directory_Error") }; } bool canWrite; try { canWrite = fileSystem.Using(cwd, fs => fs.Current.CanWrite); } catch (InvalidOperationException) { return new ErrorCommandResponse { error = ResourceManager.GetString("Unable_To_Retrieve_Current_Directory_Error") }; } if (!canWrite) { return new ErrorCommandResponse { error = ResourceManager.GetString("Delete_Permission_Denied_For_Current_Directory_Error") }; } var errors = RemoveFiles(commandContext); try { return fileSystem.Using(cwd, fs => GetResponse(commandContext, fs, errors)); } catch (InvalidOperationException) { return new ErrorCommandResponse { error = ResourceManager.GetString("Unable_To_Retrieve_Current_Directory_Error") }; } } private static CommandResponse GetResponse(ICommandContext commandContext, IFileSystemContext fileSystemContext, List<Tuple<string, string>> errors) { var response = new OpenCommand().GetResponse(commandContext, fileSystemContext, true); if (errors.Any()) { var errorMessages = errors.Select(e => "[{0}: {1}]".FormatWith(e.Item1, e.Item2)); response.error = ResourceManager.GetString("Uploading_Files_Error").FormatWith(string.Join(",", errorMessages)); } return response; } private static List<Tuple<string, string>> RemoveFiles(ICommandContext commandContext) { var errors = new List<Tuple<string, string>>(); var targetHashes = (commandContext.Parameters["targets[]"] ?? string.Empty).Split(','); if (!targetHashes.Any()) { return errors; } var portal = commandContext.CreatePortalContext(); var website = portal.Website.ToEntityReference(); var security = commandContext.CreateSecurityProvider(); var dataServiceProvider = commandContext.CreateDependencyProvider().GetDependency<ICmsDataServiceProvider>(); foreach (var targetHash in targetHashes) { var serviceContext = commandContext.CreateServiceContext(); Entity target; if (!TryGetTargetEntity(serviceContext, targetHash, website, out target)) { errors.Add(new Tuple<string, string>(targetHash, ResourceManager.GetString("Unable_To_Retrieve_Target_Entity_For_Given_Hash_Error"))); continue; } try { OrganizationServiceContextInfo serviceContextInfo; EntitySetInfo entitySetInfo; if (dataServiceProvider != null && OrganizationServiceContextInfo.TryGet(serviceContext.GetType(), out serviceContextInfo) && serviceContextInfo.EntitySetsByEntityLogicalName.TryGetValue(target.LogicalName, out entitySetInfo)) { dataServiceProvider.DeleteEntity(serviceContext, entitySetInfo.Property.Name, target.Id); } else { if (!security.TryAssert(serviceContext, target, CrmEntityRight.Change)) { errors.Add(new Tuple<string, string>(GetDisplayName(target), ResourceManager.GetString("Delete_Permission_Denied_For_Target_Entity_Error"))); continue; } CrmEntityInactiveInfo inactiveInfo; if (CrmEntityInactiveInfo.TryGetInfo(target.LogicalName, out inactiveInfo)) { serviceContext.SetState(inactiveInfo.InactiveState, inactiveInfo.InactiveStatus, target); } else { serviceContext.DeleteObject(target); serviceContext.SaveChanges(); } } } catch (Exception e) { ADXTrace.Instance.TraceError(TraceCategory.Application, string.Format("{0} {1}", ResourceManager.GetString("Deleting_File_Exception"), e.ToString())); errors.Add(new Tuple<string, string>(GetDisplayName(target), e.Message)); } } return errors; } private static string GetDisplayName(Entity entity) { if (entity == null) { throw new ArgumentNullException("entity"); } if (entity.Attributes.Contains("adx_title")) { return entity.GetAttributeValue<string>("adx_title") ?? entity.GetAttributeValue<string>("adx_name"); } return entity.GetAttributeValue<string>("adx_name"); } private static bool TryGetTargetEntity(OrganizationServiceContext serviceContext, string hash, EntityReference website, out Entity target) { target = null; DirectoryContentHash hashInfo; if (!DirectoryContentHash.TryParse(hash, out hashInfo)) { return false; } Tuple<string, string> targetSchema; if (!RmTargetSchemaLookup.TryGetValue(hashInfo.LogicalName, out targetSchema)) { return false; } target = serviceContext.CreateQuery(hashInfo.LogicalName) .FirstOrDefault(e => e.GetAttributeValue<Guid>(targetSchema.Item1) == hashInfo.Id && e.GetAttributeValue<EntityReference>(targetSchema.Item2) == website); return target != null; } private static readonly IDictionary<string, Tuple<string, string>> RmTargetSchemaLookup = new Dictionary<string, Tuple<string, string>>(StringComparer.InvariantCultureIgnoreCase) { { "adx_webfile", new Tuple<string, string>("adx_webfileid", "adx_websiteid") }, }; } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// UsAppToPersonResource /// </summary> using Newtonsoft.Json; using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Clients; using Twilio.Converters; using Twilio.Exceptions; using Twilio.Http; namespace Twilio.Rest.Messaging.V1.Service { public class UsAppToPersonResource : Resource { private static Request BuildCreateRequest(CreateUsAppToPersonOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.Messaging, "/v1/Services/" + options.PathMessagingServiceSid + "/Compliance/Usa2p", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// create /// </summary> /// <param name="options"> Create UsAppToPerson parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UsAppToPerson </returns> public static UsAppToPersonResource Create(CreateUsAppToPersonOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildCreateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="options"> Create UsAppToPerson parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UsAppToPerson </returns> public static async System.Threading.Tasks.Task<UsAppToPersonResource> CreateAsync(CreateUsAppToPersonOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildCreateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// create /// </summary> /// <param name="pathMessagingServiceSid"> The SID of the Messaging Service to create the resource from </param> /// <param name="brandRegistrationSid"> A2P Brand Registration SID </param> /// <param name="description"> A short description of what this SMS campaign does </param> /// <param name="messageSamples"> Message samples </param> /// <param name="usAppToPersonUsecase"> A2P Campaign Use Case. </param> /// <param name="hasEmbeddedLinks"> Indicates that this SMS campaign will send messages that contain links </param> /// <param name="hasEmbeddedPhone"> Indicates that this SMS campaign will send messages that contain phone numbers /// </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UsAppToPerson </returns> public static UsAppToPersonResource Create(string pathMessagingServiceSid, string brandRegistrationSid, string description, List<string> messageSamples, string usAppToPersonUsecase, bool? hasEmbeddedLinks, bool? hasEmbeddedPhone, ITwilioRestClient client = null) { var options = new CreateUsAppToPersonOptions(pathMessagingServiceSid, brandRegistrationSid, description, messageSamples, usAppToPersonUsecase, hasEmbeddedLinks, hasEmbeddedPhone); return Create(options, client); } #if !NET35 /// <summary> /// create /// </summary> /// <param name="pathMessagingServiceSid"> The SID of the Messaging Service to create the resource from </param> /// <param name="brandRegistrationSid"> A2P Brand Registration SID </param> /// <param name="description"> A short description of what this SMS campaign does </param> /// <param name="messageSamples"> Message samples </param> /// <param name="usAppToPersonUsecase"> A2P Campaign Use Case. </param> /// <param name="hasEmbeddedLinks"> Indicates that this SMS campaign will send messages that contain links </param> /// <param name="hasEmbeddedPhone"> Indicates that this SMS campaign will send messages that contain phone numbers /// </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UsAppToPerson </returns> public static async System.Threading.Tasks.Task<UsAppToPersonResource> CreateAsync(string pathMessagingServiceSid, string brandRegistrationSid, string description, List<string> messageSamples, string usAppToPersonUsecase, bool? hasEmbeddedLinks, bool? hasEmbeddedPhone, ITwilioRestClient client = null) { var options = new CreateUsAppToPersonOptions(pathMessagingServiceSid, brandRegistrationSid, description, messageSamples, usAppToPersonUsecase, hasEmbeddedLinks, hasEmbeddedPhone); return await CreateAsync(options, client); } #endif private static Request BuildDeleteRequest(DeleteUsAppToPersonOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Delete, Rest.Domain.Messaging, "/v1/Services/" + options.PathMessagingServiceSid + "/Compliance/Usa2p/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// delete /// </summary> /// <param name="options"> Delete UsAppToPerson parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UsAppToPerson </returns> public static bool Delete(DeleteUsAppToPersonOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="options"> Delete UsAppToPerson parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UsAppToPerson </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(DeleteUsAppToPersonOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildDeleteRequest(options, client)); return response.StatusCode == System.Net.HttpStatusCode.NoContent; } #endif /// <summary> /// delete /// </summary> /// <param name="pathMessagingServiceSid"> The SID of the Messaging Service to delete the resource from </param> /// <param name="pathSid"> The SID that identifies the US A2P Compliance resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UsAppToPerson </returns> public static bool Delete(string pathMessagingServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteUsAppToPersonOptions(pathMessagingServiceSid, pathSid); return Delete(options, client); } #if !NET35 /// <summary> /// delete /// </summary> /// <param name="pathMessagingServiceSid"> The SID of the Messaging Service to delete the resource from </param> /// <param name="pathSid"> The SID that identifies the US A2P Compliance resource to delete </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UsAppToPerson </returns> public static async System.Threading.Tasks.Task<bool> DeleteAsync(string pathMessagingServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new DeleteUsAppToPersonOptions(pathMessagingServiceSid, pathSid); return await DeleteAsync(options, client); } #endif private static Request BuildReadRequest(ReadUsAppToPersonOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Messaging, "/v1/Services/" + options.PathMessagingServiceSid + "/Compliance/Usa2p", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// read /// </summary> /// <param name="options"> Read UsAppToPerson parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UsAppToPerson </returns> public static ResourceSet<UsAppToPersonResource> Read(ReadUsAppToPersonOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildReadRequest(options, client)); var page = Page<UsAppToPersonResource>.FromJson("compliance", response.Content); return new ResourceSet<UsAppToPersonResource>(page, options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="options"> Read UsAppToPerson parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UsAppToPerson </returns> public static async System.Threading.Tasks.Task<ResourceSet<UsAppToPersonResource>> ReadAsync(ReadUsAppToPersonOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildReadRequest(options, client)); var page = Page<UsAppToPersonResource>.FromJson("compliance", response.Content); return new ResourceSet<UsAppToPersonResource>(page, options, client); } #endif /// <summary> /// read /// </summary> /// <param name="pathMessagingServiceSid"> The SID of the Messaging Service to fetch the resource from </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UsAppToPerson </returns> public static ResourceSet<UsAppToPersonResource> Read(string pathMessagingServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadUsAppToPersonOptions(pathMessagingServiceSid){PageSize = pageSize, Limit = limit}; return Read(options, client); } #if !NET35 /// <summary> /// read /// </summary> /// <param name="pathMessagingServiceSid"> The SID of the Messaging Service to fetch the resource from </param> /// <param name="pageSize"> Page size </param> /// <param name="limit"> Record limit </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UsAppToPerson </returns> public static async System.Threading.Tasks.Task<ResourceSet<UsAppToPersonResource>> ReadAsync(string pathMessagingServiceSid, int? pageSize = null, long? limit = null, ITwilioRestClient client = null) { var options = new ReadUsAppToPersonOptions(pathMessagingServiceSid){PageSize = pageSize, Limit = limit}; return await ReadAsync(options, client); } #endif /// <summary> /// Fetch the target page of records /// </summary> /// <param name="targetUrl"> API-generated URL for the requested results page </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The target page of records </returns> public static Page<UsAppToPersonResource> GetPage(string targetUrl, ITwilioRestClient client) { client = client ?? TwilioClient.GetRestClient(); var request = new Request( HttpMethod.Get, targetUrl ); var response = client.Request(request); return Page<UsAppToPersonResource>.FromJson("compliance", response.Content); } /// <summary> /// Fetch the next page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The next page of records </returns> public static Page<UsAppToPersonResource> NextPage(Page<UsAppToPersonResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetNextPageUrl(Rest.Domain.Messaging) ); var response = client.Request(request); return Page<UsAppToPersonResource>.FromJson("compliance", response.Content); } /// <summary> /// Fetch the previous page of records /// </summary> /// <param name="page"> current page of records </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> The previous page of records </returns> public static Page<UsAppToPersonResource> PreviousPage(Page<UsAppToPersonResource> page, ITwilioRestClient client) { var request = new Request( HttpMethod.Get, page.GetPreviousPageUrl(Rest.Domain.Messaging) ); var response = client.Request(request); return Page<UsAppToPersonResource>.FromJson("compliance", response.Content); } private static Request BuildFetchRequest(FetchUsAppToPersonOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.Messaging, "/v1/Services/" + options.PathMessagingServiceSid + "/Compliance/Usa2p/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch UsAppToPerson parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UsAppToPerson </returns> public static UsAppToPersonResource Fetch(FetchUsAppToPersonOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="options"> Fetch UsAppToPerson parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UsAppToPerson </returns> public static async System.Threading.Tasks.Task<UsAppToPersonResource> FetchAsync(FetchUsAppToPersonOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// fetch /// </summary> /// <param name="pathMessagingServiceSid"> The SID of the Messaging Service to fetch the resource from </param> /// <param name="pathSid"> The SID that identifies the US A2P Compliance resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of UsAppToPerson </returns> public static UsAppToPersonResource Fetch(string pathMessagingServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchUsAppToPersonOptions(pathMessagingServiceSid, pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// fetch /// </summary> /// <param name="pathMessagingServiceSid"> The SID of the Messaging Service to fetch the resource from </param> /// <param name="pathSid"> The SID that identifies the US A2P Compliance resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of UsAppToPerson </returns> public static async System.Threading.Tasks.Task<UsAppToPersonResource> FetchAsync(string pathMessagingServiceSid, string pathSid, ITwilioRestClient client = null) { var options = new FetchUsAppToPersonOptions(pathMessagingServiceSid, pathSid); return await FetchAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a UsAppToPersonResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> UsAppToPersonResource object represented by the provided JSON </returns> public static UsAppToPersonResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<UsAppToPersonResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies a US A2P Compliance resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The SID of the Account that created the resource /// </summary> [JsonProperty("account_sid")] public string AccountSid { get; private set; } /// <summary> /// A2P Brand Registration SID /// </summary> [JsonProperty("brand_registration_sid")] public string BrandRegistrationSid { get; private set; } /// <summary> /// The SID of the Messaging Service the resource is associated with /// </summary> [JsonProperty("messaging_service_sid")] public string MessagingServiceSid { get; private set; } /// <summary> /// A short description of what this SMS campaign does /// </summary> [JsonProperty("description")] public string Description { get; private set; } /// <summary> /// Message samples /// </summary> [JsonProperty("message_samples")] public List<string> MessageSamples { get; private set; } /// <summary> /// A2P Campaign Use Case. /// </summary> [JsonProperty("us_app_to_person_usecase")] public string UsAppToPersonUsecase { get; private set; } /// <summary> /// Indicate that this SMS campaign will send messages that contain links /// </summary> [JsonProperty("has_embedded_links")] public bool? HasEmbeddedLinks { get; private set; } /// <summary> /// Indicates that this SMS campaign will send messages that contain phone numbers /// </summary> [JsonProperty("has_embedded_phone")] public bool? HasEmbeddedPhone { get; private set; } /// <summary> /// Campaign status /// </summary> [JsonProperty("campaign_status")] public string CampaignStatus { get; private set; } /// <summary> /// The Campaign Registry (TCR) Campaign ID. /// </summary> [JsonProperty("campaign_id")] public string CampaignId { get; private set; } /// <summary> /// Indicates whether the campaign was registered externally or not /// </summary> [JsonProperty("is_externally_registered")] public bool? IsExternallyRegistered { get; private set; } /// <summary> /// Rate limit and/or classification set by each carrier /// </summary> [JsonProperty("rate_limits")] public object RateLimits { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was created /// </summary> [JsonProperty("date_created")] public DateTime? DateCreated { get; private set; } /// <summary> /// The ISO 8601 date and time in GMT when the resource was last updated /// </summary> [JsonProperty("date_updated")] public DateTime? DateUpdated { get; private set; } /// <summary> /// The absolute URL of the US App to Person resource /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } /// <summary> /// A boolean that specifies whether campaign is a mock or not. /// </summary> [JsonProperty("mock")] public bool? Mock { get; private set; } private UsAppToPersonResource() { } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Xunit; namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.class01.class01 { using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.class01.class01; // <Area> dynamic in unsafe code </Area> // <Title> unsafe type </Title> // <Description> // class // </Description> //<Expects Status=success></Expects> // <Code> public unsafe class C { public static int* p; } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new C(); return 0; } } } namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.codeblock01.codeblock01 { using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.codeblock01.codeblock01; public unsafe class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { unsafe { dynamic d = 1; d = new Test(); } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach01.freach01 { using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach01.freach01; // <Area> dynamic in unsafe code </Area> // <Title> unsafe context </Title> // <Description> // foreach // </Description> //<Expects Status=success></Expects> // <Code> public unsafe class C { public static int* p; } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { C[] arrayC = new C[] { new C(), new C(), new C()} ; foreach (dynamic d in arrayC) // C is an unsafe type { if (d.GetType() != typeof(C)) { return 1; } } return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach02.freach02 { using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach02.freach02; // <Area> dynamic in unsafe code </Area> // <Title> unsafe context </Title> // <Description> // foreach // </Description> //<Expects Status=success></Expects> // <Code> public unsafe class C { public static int* p; } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic arrayC = new C[] { new C(), new C(), new C()} ; foreach (C c in arrayC) // C is an unsafe type { if (c.GetType() != typeof(C)) { return 1; } } return 0; } } } namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach03.freach03 { using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.freach03.freach03; // <Area> dynamic in unsafe code </Area> // <Title> unsafe context </Title> // <Description> // foreach // </Description> //<Expects Status=success></Expects> // <Code> // pointer arrays are not supported //public unsafe class C //{ //public static int* p; //} //[TestClass]public class Test //{ //[Test][Priority(Priority.Priority2)]public void DynamicCSharpRunTest(){Assert.AreEqual(0, MainMethod(null));} public unsafe static int MainMethod(string[] args) //{ //int a = 1, b = 2, c = 3; //dynamic arrayp = new int*[] { &a, &b, &c }; //try //{ //foreach (dynamic d in arrayp) //{ //} //} //catch (Microsoft.CSharp.RuntimeBinder.RuntimeBinderException e) //{ //if (ErrorVerifier.Verify(ErrorMessageId.UnsafeNeeded, e.Message)) //return 0; //} //return 1; //} //} //// </Code> } namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.strct01.strct01 { using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.strct01.strct01; // <Area> dynamic in unsafe code </Area> // <Title> unsafe type</Title> // <Description> // struct // </Description> //<Expects Status=success></Expects> // <Code> public unsafe struct S { public static int* p; } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { dynamic d = new S(); return 0; } } // </Code> } namespace ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.while01.while01 { using ManagedTests.DynamicCSharp.conformance.dynamic.unsfe.context.while01.while01; // <Area> dynamic in unsafe code </Area> // <Title> unsafe context </Title> // <Description> // foreach // </Description> //<Expects Status=success></Expects> // <Code> public unsafe class C { public static int* p; } public class Test { [Fact] public static void DynamicCSharpRunTest() { Assert.Equal(0, MainMethod(null)); } public static int MainMethod(string[] args) { unsafe { int index = 5; do { dynamic d = new C(); int* p = &index; *p = *p - 1; } while (index > 0); } return 0; } } // </Code> }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Internal.FileAppenders { using System; using System.IO; using System.Runtime.InteropServices; using System.Security; using NLog.Common; using NLog.Internal; /// <summary> /// Base class for optimized file appenders. /// </summary> [SecuritySafeCritical] internal abstract class BaseFileAppender : IDisposable { private readonly Random _random = new Random(); /// <summary> /// Initializes a new instance of the <see cref="BaseFileAppender" /> class. /// </summary> /// <param name="fileName">Name of the file.</param> /// <param name="createParameters">The create parameters.</param> protected BaseFileAppender(string fileName, ICreateFileParameters createParameters) { CreateFileParameters = createParameters; FileName = fileName; OpenTimeUtc = DateTime.UtcNow; // to be consistent with timeToKill in FileTarget.AutoClosingTimerCallback LastWriteTimeUtc = DateTime.MinValue; CaptureLastWriteTime = createParameters.CaptureLastWriteTime; } protected bool CaptureLastWriteTime { get; private set; } /// <summary> /// Gets the path of the file, including file extension. /// </summary> /// <value>The name of the file.</value> public string FileName { get; private set; } /// <summary> /// Gets or sets the creation time for a file associated with the appender. The time returned is in Coordinated /// Universal Time [UTC] standard. /// </summary> /// <returns>The creation time of the file.</returns> public DateTime CreationTimeUtc { get => _creationTimeUtc; internal set { _creationTimeUtc = value; CreationTimeSource = Time.TimeSource.Current.FromSystemTime(value); // Performance optimization to skip converting every time } } DateTime _creationTimeUtc; /// <summary> /// Gets or sets the creation time for a file associated with the appender. Synchronized by <see cref="CreationTimeUtc"/> /// The time format is based on <see cref="NLog.Time.TimeSource" /> /// </summary> public DateTime CreationTimeSource { get; private set; } /// <summary> /// Gets the last time the file associated with the appeander is opened. The time returned is in Coordinated /// Universal Time [UTC] standard. /// </summary> /// <returns>The time the file was last opened.</returns> public DateTime OpenTimeUtc { get; private set; } /// <summary> /// Gets the last time the file associated with the appeander is written. The time returned is in /// Coordinated Universal Time [UTC] standard. /// </summary> /// <returns>The time the file was last written to.</returns> public DateTime LastWriteTimeUtc { get; private set; } /// <summary> /// Gets the file creation parameters. /// </summary> /// <value>The file creation parameters.</value> public ICreateFileParameters CreateFileParameters { get; private set; } /// <summary> /// Writes the specified bytes. /// </summary> /// <param name="bytes">The bytes.</param> public void Write(byte[] bytes) { Write(bytes, 0, bytes.Length); } public abstract void Write(byte[] bytes, int offset, int count); /// <summary> /// Flushes this instance. /// </summary> public abstract void Flush(); /// <summary> /// Closes this instance. /// </summary> public abstract void Close(); /// <summary> /// Gets the creation time for a file associated with the appender. The time returned is in Coordinated Universal /// Time [UTC] standard. /// </summary> /// <returns>The file creation time.</returns> public abstract DateTime? GetFileCreationTimeUtc(); /// <summary> /// Gets the last time the file associated with the appeander is written. The time returned is in Coordinated /// Universal Time [UTC] standard. /// </summary> /// <returns>The time the file was last written to.</returns> public abstract DateTime? GetFileLastWriteTimeUtc(); /// <summary> /// Gets the length in bytes of the file associated with the appeander. /// </summary> /// <returns>A long value representing the length of the file in bytes.</returns> public abstract long? GetFileLength(); /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing">True to release both managed and unmanaged resources; <c>false</c> to release only unmanaged resources.</param> protected virtual void Dispose(bool disposing) { if (disposing) { Close(); } } /// <summary> /// Updates the last write time of the file. /// </summary> protected void FileTouched() { if (CaptureLastWriteTime) { FileTouched(DateTime.UtcNow); } } /// <summary> /// Updates the last write time of the file to the specified date. /// </summary> /// <param name="dateTime">Date and time when the last write occurred in UTC.</param> protected void FileTouched(DateTime dateTime) { LastWriteTimeUtc = dateTime; } /// <summary> /// Creates the file stream. /// </summary> /// <param name="allowFileSharedWriting">If set to <c>true</c> sets the file stream to allow shared writing.</param> /// <returns>A <see cref="FileStream"/> object which can be used to write to the file.</returns> protected FileStream CreateFileStream(bool allowFileSharedWriting) { int currentDelay = CreateFileParameters.ConcurrentWriteAttemptDelay; InternalLogger.Trace("Opening {0} with allowFileSharedWriting={1}", FileName, allowFileSharedWriting); for (int i = 0; i < CreateFileParameters.ConcurrentWriteAttempts; ++i) { try { try { return TryCreateFileStream(allowFileSharedWriting); } catch (DirectoryNotFoundException) { //we don't check the directory on beforehand, as that will really slow down writing. if (!CreateFileParameters.CreateDirs) { throw; } var directoryName = Path.GetDirectoryName(FileName); try { Directory.CreateDirectory(directoryName); } catch (DirectoryNotFoundException) { //if creating a directory failed, don't retry for this message (e.g the ConcurrentWriteAttempts below) throw new NLogRuntimeException("Could not create directory {0}", directoryName); } return TryCreateFileStream(allowFileSharedWriting); } } catch (IOException) { if (!CreateFileParameters.ConcurrentWrites || i + 1 == CreateFileParameters.ConcurrentWriteAttempts) { throw; // rethrow } int actualDelay = _random.Next(currentDelay); InternalLogger.Warn("Attempt #{0} to open {1} failed. Sleeping for {2}ms", i, FileName, actualDelay); currentDelay *= 2; AsyncHelpers.WaitForDelay(TimeSpan.FromMilliseconds(actualDelay)); } } throw new InvalidOperationException("Should not be reached."); } #if !SILVERLIGHT && !MONO && !__IOS__ && !__ANDROID__ && !NETSTANDARD [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "Objects are disposed elsewhere")] private FileStream WindowsCreateFile(string fileName, bool allowFileSharedWriting) { int fileShare = Win32FileNativeMethods.FILE_SHARE_READ; if (allowFileSharedWriting) { fileShare |= Win32FileNativeMethods.FILE_SHARE_WRITE; } if (CreateFileParameters.EnableFileDelete && PlatformDetector.CurrentOS != RuntimeOS.Windows) { fileShare |= Win32FileNativeMethods.FILE_SHARE_DELETE; } Microsoft.Win32.SafeHandles.SafeFileHandle handle = null; FileStream fileStream = null; try { handle = Win32FileNativeMethods.CreateFile( fileName, Win32FileNativeMethods.FileAccess.GenericWrite, fileShare, IntPtr.Zero, Win32FileNativeMethods.CreationDisposition.OpenAlways, CreateFileParameters.FileAttributes, IntPtr.Zero); if (handle.IsInvalid) { Marshal.ThrowExceptionForHR(Marshal.GetHRForLastWin32Error()); } fileStream = new FileStream(handle, FileAccess.Write, CreateFileParameters.BufferSize); fileStream.Seek(0, SeekOrigin.End); return fileStream; } catch { fileStream?.Dispose(); if ((handle != null) && (!handle.IsClosed)) handle.Close(); throw; } } #endif private FileStream TryCreateFileStream(bool allowFileSharedWriting) { UpdateCreationTime(); #if !SILVERLIGHT && !MONO && !__IOS__ && !__ANDROID__ && !NETSTANDARD try { if (!CreateFileParameters.ForceManaged && PlatformDetector.IsDesktopWin32 && !PlatformDetector.IsMono) { return WindowsCreateFile(FileName, allowFileSharedWriting); } } catch (SecurityException) { InternalLogger.Debug("Could not use native Windows create file, falling back to managed filestream"); } #endif FileShare fileShare = allowFileSharedWriting ? FileShare.ReadWrite : FileShare.Read; if (CreateFileParameters.EnableFileDelete) { fileShare |= FileShare.Delete; } return new FileStream( FileName, FileMode.Append, FileAccess.Write, fileShare, CreateFileParameters.BufferSize); } private void UpdateCreationTime() { FileInfo fileInfo = new FileInfo(FileName); if (fileInfo.Exists) { CreationTimeUtc = FileCharacteristicsHelper.ValidateFileCreationTime(fileInfo, (f) => f.GetCreationTimeUtc(), (f) => f.GetLastWriteTimeUtc()).Value; } else { File.Create(FileName).Dispose(); CreationTimeUtc = DateTime.UtcNow; #if !SILVERLIGHT // Set the file's creation time to avoid being thwarted by Windows' Tunneling capabilities (https://support.microsoft.com/en-us/kb/172190). File.SetCreationTimeUtc(FileName, CreationTimeUtc); #endif } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Immutable; using System.IO; using System.Linq; using System.Reflection.Internal; using System.Reflection.Metadata; using System.Reflection.Metadata.Tests; using Xunit; namespace System.Reflection.PortableExecutable.Tests { public class DebugDirectoryTests { [Fact] public void NoDebugDirectory() { var peStream = new MemoryStream(Misc.Members); using (var reader = new PEReader(peStream)) { var entries = reader.ReadDebugDirectory(); Assert.Empty(entries); } } [Fact] public void CodeView() { var peStream = new MemoryStream(Misc.Debug); using (var reader = new PEReader(peStream)) { ValidateCodeView(reader); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void CodeView_Loaded() { LoaderUtilities.LoadPEAndValidate(Misc.Debug, ValidateCodeView); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void CodeView_Loaded_FromStream() { LoaderUtilities.LoadPEAndValidate(Misc.Debug, ValidateCodeView, useStream: true); } private void ValidateCodeView(PEReader reader) { // dumpbin: // // Debug Directories // // Time Type Size RVA Pointer // -------------- - ------------------------ // 5670C4E6 cv 11C 0000230C 50C Format: RSDS, { 0C426227-31E6-4EC2-BD5F-712C4D96C0AB}, 1, C:\Temp\Debug.pdb var cvEntry = reader.ReadDebugDirectory().Single(); Assert.Equal(DebugDirectoryEntryType.CodeView, cvEntry.Type); Assert.False(cvEntry.IsPortableCodeView); Assert.Equal(0x050c, cvEntry.DataPointer); Assert.Equal(0x230c, cvEntry.DataRelativeVirtualAddress); Assert.Equal(0x011c, cvEntry.DataSize); // includes NUL padding Assert.Equal(0, cvEntry.MajorVersion); Assert.Equal(0, cvEntry.MinorVersion); Assert.Equal(0x5670c4e6u, cvEntry.Stamp); var cv = reader.ReadCodeViewDebugDirectoryData(cvEntry); Assert.Equal(1, cv.Age); Assert.Equal(new Guid("0C426227-31E6-4EC2-BD5F-712C4D96C0AB"), cv.Guid); Assert.Equal(@"C:\Temp\Debug.pdb", cv.Path); } [Fact] public void Deterministic() { var peStream = new MemoryStream(Misc.Deterministic); using (var reader = new PEReader(peStream)) { ValidateDeterministic(reader); } } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void Deterministic_Loaded() { LoaderUtilities.LoadPEAndValidate(Misc.Deterministic, ValidateDeterministic); } private void ValidateDeterministic(PEReader reader) { // dumpbin: // // Debug Directories // // Time Type Size RVA Pointer // -------- ------- -------- -------- -------- // D2FC74D3 cv 32 00002338 538 Format: RSDS, {814C578F-7676-0263-4F8A-2D3E8528EAF1}, 1, C:\Temp\Deterministic.pdb // 00000000 repro 0 00000000 0 var entries = reader.ReadDebugDirectory(); var cvEntry = entries[0]; Assert.Equal(DebugDirectoryEntryType.CodeView, cvEntry.Type); Assert.False(cvEntry.IsPortableCodeView); Assert.Equal(0x0538, cvEntry.DataPointer); Assert.Equal(0x2338, cvEntry.DataRelativeVirtualAddress); Assert.Equal(0x0032, cvEntry.DataSize); // no NUL padding Assert.Equal(0, cvEntry.MajorVersion); Assert.Equal(0, cvEntry.MinorVersion); Assert.Equal(0xD2FC74D3u, cvEntry.Stamp); var cv = reader.ReadCodeViewDebugDirectoryData(cvEntry); Assert.Equal(1, cv.Age); Assert.Equal(new Guid("814C578F-7676-0263-4F8A-2D3E8528EAF1"), cv.Guid); Assert.Equal(@"C:\Temp\Deterministic.pdb", cv.Path); var detEntry = entries[1]; Assert.Equal(DebugDirectoryEntryType.Reproducible, detEntry.Type); Assert.False(detEntry.IsPortableCodeView); Assert.Equal(0, detEntry.DataPointer); Assert.Equal(0, detEntry.DataRelativeVirtualAddress); Assert.Equal(0, detEntry.DataSize); Assert.Equal(0, detEntry.MajorVersion); Assert.Equal(0, detEntry.MinorVersion); Assert.Equal(0u, detEntry.Stamp); Assert.Equal(2, entries.Length); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void EmbeddedPortablePdb_Loaded() { LoaderUtilities.LoadPEAndValidate(PortablePdbs.DocumentsEmbeddedDll, ValidateEmbeddedPortablePdb); } [Fact] [PlatformSpecific(TestPlatforms.Windows)] // Uses P/Invokes to get module handles public void EmbeddedPortablePdb_Loaded_FromStream() { LoaderUtilities.LoadPEAndValidate(PortablePdbs.DocumentsEmbeddedDll, ValidateEmbeddedPortablePdb, useStream: true); } private void ValidateEmbeddedPortablePdb(PEReader reader) { var entries = reader.ReadDebugDirectory(); Assert.Equal(DebugDirectoryEntryType.CodeView, entries[0].Type); Assert.Equal(DebugDirectoryEntryType.Reproducible, entries[1].Type); Assert.Equal(DebugDirectoryEntryType.EmbeddedPortablePdb, entries[2].Type); using (MetadataReaderProvider provider = reader.ReadEmbeddedPortablePdbDebugDirectoryData(entries[2])) { var pdbReader = provider.GetMetadataReader(); var document = pdbReader.GetDocument(pdbReader.Documents.First()); Assert.Equal(@"C:\Documents.cs", pdbReader.GetString(document.Name)); } } [Fact] public void DebugDirectoryData_Errors() { var reader = new PEReader(new MemoryStream(Misc.Members)); AssertExtensions.Throws<ArgumentException>("entry", () => reader.ReadCodeViewDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.Coff, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => reader.ReadCodeViewDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.CodeView, 0, 0, 0))); AssertExtensions.Throws<ArgumentException>("entry", () => reader.ReadEmbeddedPortablePdbDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.Coff, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => reader.ReadEmbeddedPortablePdbDebugDirectoryData(new DebugDirectoryEntry(0, 0, 0, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); } [Fact] public void ValidateEmbeddedPortablePdbVersion() { // major version (Portable PDB format): PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)); PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0101, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)); PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0xffff, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0)); Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0000, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x00ff, 0x0100, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); // minor version (Embedded blob format): Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0101, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0000, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x00ff, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); Assert.Throws<BadImageFormatException>(() => PEReader.ValidateEmbeddedPortablePdbVersion(new DebugDirectoryEntry(0, 0x0100, 0x0200, DebugDirectoryEntryType.EmbeddedPortablePdb, 0, 0, 0))); } [Fact] public void CodeView_PathPadding() { var bytes = ImmutableArray.Create(new byte[] { (byte)'R', (byte)'S', (byte)'D', (byte)'S', // signature 0x6E, 0xE6, 0x88, 0x3C, 0xB9, 0xE0, 0x08, 0x45, 0x92, 0x90, 0x11, 0xE0, 0xDB, 0x51, 0xA1, 0xC5, // GUID 0x01, 0x00, 0x00, 0x00, // age (byte)'x', 0x00, 0x20, 0xff, // path }); using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length)) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 1)) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 2)) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 3)) { Assert.Equal("x", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 4)) { Assert.Equal("", PEReader.DecodeCodeViewDebugDirectoryData(block).Path); } } [Fact] public void CodeView_Errors() { var bytes = ImmutableArray.Create(new byte[] { (byte)'R', (byte)'S', (byte)'D', (byte)'S', // signature 0x6E, 0xE6, 0x88, 0x3C, 0xB9, 0xE0, 0x08, 0x45, 0x92, 0x90, 0x11, 0xE0, 0xDB, 0x51, 0xA1, 0xC5, // GUID 0x01, 0x00, 0x00, 0x00, // age (byte)'x', 0x00, // path }); using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, 1)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeCodeViewDebugDirectoryData(block)); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, 4)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeCodeViewDebugDirectoryData(block)); } using (var block = new ByteArrayMemoryProvider(bytes).GetMemoryBlock(0, bytes.Length - 3)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeCodeViewDebugDirectoryData(block)); } } [Fact] public void EmbeddedPortablePdb_Errors() { var bytes1 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0xFF, 0xFF, 0xFF, 0xFF, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes1).GetMemoryBlock(0, bytes1.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes2 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0x09, 0x00, 0x00, 0x00, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes2).GetMemoryBlock(0, bytes2.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes3 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0x00, 0x00, 0x00, 0x00, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes3).GetMemoryBlock(0, bytes3.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes4 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0xff, 0xff, 0xff, 0x7f, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes4).GetMemoryBlock(0, bytes4.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes5 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x42, // signature 0x08, 0x00, 0x00, 0x00, // uncompressed size 0xEF, 0xFF, 0x4F, 0xFF, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes4).GetMemoryBlock(0, bytes4.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes6 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, 0x00, // uncompressed size 0xEB, 0x28, 0x4F, 0x0B, 0x75, 0x31, 0x56, 0x12, 0x04, 0x00 // compressed data }); using (var block = new ByteArrayMemoryProvider(bytes6).GetMemoryBlock(0, bytes6.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes7 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, }); using (var block = new ByteArrayMemoryProvider(bytes7).GetMemoryBlock(0, bytes7.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes8 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, }); using (var block = new ByteArrayMemoryProvider(bytes8).GetMemoryBlock(0, bytes8.Length)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } var bytes9 = ImmutableArray.Create(new byte[] { 0x4D, 0x50, 0x44, 0x43, // signature 0x08, 0x00, 0x00, 0x00 }); using (var block = new ByteArrayMemoryProvider(bytes9).GetMemoryBlock(0, 1)) { Assert.Throws<BadImageFormatException>(() => PEReader.DecodeEmbeddedPortablePdbDebugDirectoryData(block)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.ComponentModel; using System.Diagnostics; using System.Drawing.Internal; using System.Globalization; using System.Runtime.InteropServices; namespace System.Drawing { /// <summary> /// Defines a particular format for text, including font face, size, and style attributes. /// </summary> [ComVisible(true)] public sealed partial class Font : MarshalByRefObject, ICloneable, IDisposable { private const int LogFontCharSetOffset = 23; private const int LogFontNameOffset = 28; private IntPtr _nativeFont; private float _fontSize; private FontStyle _fontStyle; private FontFamily _fontFamily; private GraphicsUnit _fontUnit; private byte _gdiCharSet = SafeNativeMethods.DEFAULT_CHARSET; private bool _gdiVerticalFont; private string _systemFontName = ""; private string _originalFontName; ///<summary> /// Creates the GDI+ native font object. ///</summary> private void CreateNativeFont() { Debug.Assert(_nativeFont == IntPtr.Zero, "nativeFont already initialized, this will generate a handle leak."); Debug.Assert(_fontFamily != null, "fontFamily not initialized."); // Note: GDI+ creates singleton font family objects (from the corresponding font file) and reference count them so // if creating the font object from an external FontFamily, this object's FontFamily will share the same native object. int status = SafeNativeMethods.Gdip.GdipCreateFont( new HandleRef(this, _fontFamily.NativeFamily), _fontSize, _fontStyle, _fontUnit, out _nativeFont); // Special case this common error message to give more information if (status == SafeNativeMethods.Gdip.FontStyleNotFound) { throw new ArgumentException(SR.Format(SR.GdiplusFontStyleNotFound, _fontFamily.Name, _fontStyle.ToString())); } else if (status != SafeNativeMethods.Gdip.Ok) { throw SafeNativeMethods.Gdip.StatusException(status); } } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class from the specified existing <see cref='Font'/> /// and <see cref='FontStyle'/>. /// </summary> public Font(Font prototype, FontStyle newStyle) { // Copy over the originalFontName because it won't get initialized _originalFontName = prototype.OriginalFontName; Initialize(prototype.FontFamily, prototype.Size, newStyle, prototype.Unit, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit) { Initialize(family, emSize, style, unit, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet) { Initialize(family, emSize, style, unit, gdiCharSet, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { Initialize(family, emSize, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet) { Initialize(familyName, emSize, style, unit, gdiCharSet, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0) { throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, "emSize", emSize, 0, "System.Single.MaxValue"), "emSize"); } Initialize(familyName, emSize, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, FontStyle style) { Initialize(family, emSize, style, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize, GraphicsUnit unit) { Initialize(family, emSize, FontStyle.Regular, unit, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(FontFamily family, float emSize) { Initialize(family, emSize, FontStyle.Regular, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, false); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style, GraphicsUnit unit) { Initialize(familyName, emSize, style, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, FontStyle style) { Initialize(familyName, emSize, style, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize, GraphicsUnit unit) { Initialize(familyName, emSize, FontStyle.Regular, unit, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Initializes a new instance of the <see cref='Font'/> class with the specified attributes. /// </summary> public Font(string familyName, float emSize) { Initialize(familyName, emSize, FontStyle.Regular, GraphicsUnit.Point, SafeNativeMethods.DEFAULT_CHARSET, IsVerticalName(familyName)); } /// <summary> /// Constructor to initialize fields from an exisiting native GDI+ object reference. Used by ToLogFont. /// </summary> private Font(IntPtr nativeFont, byte gdiCharSet, bool gdiVerticalFont) { Debug.Assert(_nativeFont == IntPtr.Zero, "GDI+ native font already initialized, this will generate a handle leak"); Debug.Assert(nativeFont != IntPtr.Zero, "nativeFont is null"); int status = 0; float size = 0; GraphicsUnit unit = GraphicsUnit.Point; FontStyle style = FontStyle.Regular; IntPtr nativeFamily = IntPtr.Zero; _nativeFont = nativeFont; status = SafeNativeMethods.Gdip.GdipGetFontUnit(new HandleRef(this, nativeFont), out unit); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); status = SafeNativeMethods.Gdip.GdipGetFontSize(new HandleRef(this, nativeFont), out size); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); status = SafeNativeMethods.Gdip.GdipGetFontStyle(new HandleRef(this, nativeFont), out style); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); status = SafeNativeMethods.Gdip.GdipGetFamily(new HandleRef(this, nativeFont), out nativeFamily); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); SetFontFamily(new FontFamily(nativeFamily)); Initialize(_fontFamily, size, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes this object's fields. /// </summary> private void Initialize(string familyName, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { _originalFontName = familyName; SetFontFamily(new FontFamily(StripVerticalName(familyName), true /* createDefaultOnFail */ )); Initialize(_fontFamily, emSize, style, unit, gdiCharSet, gdiVerticalFont); } /// <summary> /// Initializes this object's fields. /// </summary> private void Initialize(FontFamily family, float emSize, FontStyle style, GraphicsUnit unit, byte gdiCharSet, bool gdiVerticalFont) { if (family == null) { throw new ArgumentNullException("family"); } if (float.IsNaN(emSize) || float.IsInfinity(emSize) || emSize <= 0) { throw new ArgumentException(SR.Format(SR.InvalidBoundArgument, "emSize", emSize, 0, "System.Single.MaxValue"), "emSize"); } int status; _fontSize = emSize; _fontStyle = style; _fontUnit = unit; _gdiCharSet = gdiCharSet; _gdiVerticalFont = gdiVerticalFont; if (_fontFamily == null) { // GDI+ FontFamily is a singleton object. SetFontFamily(new FontFamily(family.NativeFamily)); } if (_nativeFont == IntPtr.Zero) { CreateNativeFont(); } // Get actual size. status = SafeNativeMethods.Gdip.GdipGetFontSize(new HandleRef(this, _nativeFont), out _fontSize); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <summary> /// Creates a <see cref='System.Drawing.Font'/> from the specified Windows handle. /// </summary> public static Font FromHfont(IntPtr hfont) { SafeNativeMethods.LOGFONT lf = new SafeNativeMethods.LOGFONT(); SafeNativeMethods.GetObject(new HandleRef(null, hfont), lf); Font result; IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); try { result = Font.FromLogFont(lf, screenDC); } finally { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } return result; } public static Font FromLogFont(object lf) { IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); Font result; try { result = Font.FromLogFont(lf, screenDC); } finally { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } return result; } public static Font FromLogFont(object lf, IntPtr hdc) { IntPtr font = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateFontFromLogfontW(new HandleRef(null, hdc), lf, out font); // Special case this incredibly common error message to give more information if (status == SafeNativeMethods.Gdip.NotTrueTypeFont) throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont_NoName)); else if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); // GDI+ returns font = 0 even though the status is Ok. if (font == IntPtr.Zero) throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont, lf.ToString())); #pragma warning disable 0618 bool gdiVerticalFont = (Marshal.ReadInt16(lf, LogFontNameOffset) == (short)'@'); return new Font(font, Marshal.ReadByte(lf, LogFontCharSetOffset), gdiVerticalFont); #pragma warning restore 0618 } /// <summary> /// Creates a Font from the specified Windows handle to a device context. /// </summary> public static Font FromHdc(IntPtr hdc) { IntPtr font = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCreateFontFromDC(new HandleRef(null, hdc), ref font); // Special case this incredibly common error message to give more information if (status == SafeNativeMethods.Gdip.NotTrueTypeFont) throw new ArgumentException(SR.Format(SR.GdiplusNotTrueTypeFont_NoName)); else if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return new Font(font, 0, false); } /// <summary> /// Creates an exact copy of this <see cref='Font'/>. /// </summary> public object Clone() { IntPtr cloneFont = IntPtr.Zero; int status = SafeNativeMethods.Gdip.GdipCloneFont(new HandleRef(this, _nativeFont), out cloneFont); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); Font newCloneFont = new Font(cloneFont, _gdiCharSet, _gdiVerticalFont); return newCloneFont; } /// <summary> /// Get native GDI+ object pointer. This property triggers the creation of the GDI+ native object if not initialized yet. /// </summary> internal IntPtr NativeFont { get { Debug.Assert(_nativeFont != IntPtr.Zero, "this.nativeFont == IntPtr.Zero."); return _nativeFont; } } /// <summary> /// Gets the <see cref='Drawing.FontFamily'/> of this <see cref='Font'/>. /// </summary> [Browsable(false)] public FontFamily FontFamily { get { Debug.Assert(_fontFamily != null, "fontFamily should never be null"); return _fontFamily; } } private void SetFontFamily(FontFamily family) { _fontFamily = family; // GDI+ creates ref-counted singleton FontFamily objects based on the family name so all managed // objects with same family name share the underlying GDI+ native pointer. The unmanged object is // destroyed when its ref-count gets to zero. // Make sure this.fontFamily is not finalized so the underlying singleton object is kept alive. GC.SuppressFinalize(_fontFamily); } /// <summary> /// Cleans up Windows resources for this <see cref='Font'/>. /// </summary> ~Font() { Dispose(false); } /// <summary> /// Cleans up Windows resources for this <see cref='Font'/>. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } private void Dispose(bool disposing) { if (_nativeFont != IntPtr.Zero) { try { #if DEBUG int status = #endif SafeNativeMethods.Gdip.GdipDeleteFont(new HandleRef(this, _nativeFont)); #if DEBUG Debug.Assert(status == SafeNativeMethods.Gdip.Ok, "GDI+ returned an error status: " + status.ToString(CultureInfo.InvariantCulture)); #endif } catch (Exception ex) { if (ClientUtils.IsCriticalException(ex)) { throw; } Debug.Fail("Exception thrown during Dispose: " + ex.ToString()); } finally { _nativeFont = IntPtr.Zero; } } } private static bool IsVerticalName(string familyName) { return familyName != null && familyName.Length > 0 && familyName[0] == '@'; } /// <summary> /// Gets a value indicating whether this <see cref='System.Drawing.Font'/> is bold. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Bold { get { return (Style & FontStyle.Bold) != 0; } } /// <summary> /// Returns the GDI char set for this instance of a font. This will only /// be valid if this font was created from a classic GDI font definition, /// like a LOGFONT or HFONT, or it was passed into the constructor. /// /// This is here for compatability with native Win32 intrinsic controls /// on non-Unicode platforms. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public byte GdiCharSet { get { return _gdiCharSet; } } /// <summary> /// Determines if this font was created to represt a GDI vertical font. This will only be valid if this font /// was created from a classic GDIfont definition, like a LOGFONT or HFONT, or it was passed into the constructor. /// /// This is here for compatability with native Win32 intrinsic controls on non-Unicode platforms. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool GdiVerticalFont { get { return _gdiVerticalFont; } } /// <summary> /// Gets a value indicating whether this <see cref='Font'/> is Italic. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Italic { get { return (Style & FontStyle.Italic) != 0; } } /// <summary> /// Gets the face name of this <see cref='Font'/> . /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public string Name { get { return FontFamily.Name; } } /// <summary> /// This property is required by the framework and not intended to be used directly. /// </summary> [Browsable(false)] public string OriginalFontName { get { return _originalFontName; } } /// <summary> /// Gets a value indicating whether this <see cref='Font'/> is strikeout (has a line through it). /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Strikeout { get { return (Style & FontStyle.Strikeout) != 0; } } /// <summary> /// Gets a value indicating whether this <see cref='Font'/> is underlined. /// </summary> [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public bool Underline { get { return (Style & FontStyle.Underline) != 0; } } /// <summary> /// Returns a value indicating whether the specified object is a <see cref='Font'/> equivalent to this /// <see cref='Font'/>. /// </summary> public override bool Equals(object obj) { if (obj == this) { return true; } Font font = obj as Font; if (font == null) { return false; } // Note: If this and/or the passed-in font are disposed, this method can still return true since we check for cached properties // here. // We need to call properties on the passed-in object since it could be a proxy in a remoting scenario and proxies don't // have access to private/internal fields. return font.FontFamily.Equals(FontFamily) && font.GdiVerticalFont == GdiVerticalFont && font.GdiCharSet == GdiCharSet && font.Style == Style && font.Size == Size && font.Unit == Unit; } /// <summary> /// Gets the hash code for this <see cref='Font'/>. /// </summary> public override int GetHashCode() { return unchecked((int)((((UInt32)_fontStyle << 13) | ((UInt32)_fontStyle >> 19)) ^ (((UInt32)_fontUnit << 26) | ((UInt32)_fontUnit >> 6)) ^ (((UInt32)_fontSize << 7) | ((UInt32)_fontSize >> 25)))); } private static string StripVerticalName(string familyName) { if (familyName != null && familyName.Length > 1 && familyName[0] == '@') { return familyName.Substring(1); } return familyName; } /// <summary> /// Returns a human-readable string representation of this <see cref='Font'/>. /// </summary> public override string ToString() { return string.Format(CultureInfo.CurrentCulture, "[{0}: Name={1}, Size={2}, Units={3}, GdiCharSet={4}, GdiVerticalFont={5}]", GetType().Name, FontFamily.Name, _fontSize, (int)_fontUnit, _gdiCharSet, _gdiVerticalFont); } public void ToLogFont(object logFont) { IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); try { Graphics graphics = Graphics.FromHdcInternal(screenDC); try { ToLogFont(logFont, graphics); } finally { graphics.Dispose(); } } finally { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } } public unsafe void ToLogFont(object logFont, Graphics graphics) { if (graphics == null) throw new ArgumentNullException("graphics"); int status = SafeNativeMethods.Gdip.GdipGetLogFontW(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), logFont); // Prefix the string with '@' this is a gdiVerticalFont. #pragma warning disable 0618 if (_gdiVerticalFont) { // Copy the Unicode contents of the name. for (int i = 60; i >= 0; i -= 2) { Marshal.WriteInt16(logFont, LogFontNameOffset + i + 2, Marshal.ReadInt16(logFont, LogFontNameOffset + i)); } // Prefix the name with an '@' sign. Marshal.WriteInt16(logFont, LogFontNameOffset, (short)'@'); } if (Marshal.ReadByte(logFont, LogFontCharSetOffset) == 0) { Marshal.WriteByte(logFont, LogFontCharSetOffset, _gdiCharSet); } #pragma warning restore 0618 if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); } /// <summary> /// Returns a handle to this <see cref='Font'/>. /// </summary> public IntPtr ToHfont() { SafeNativeMethods.LOGFONT lf = new SafeNativeMethods.LOGFONT(); ToLogFont(lf); IntPtr handle = IntUnsafeNativeMethods.IntCreateFontIndirect(lf); if (handle == IntPtr.Zero) { throw new Win32Exception(); } return handle; } /// <summary> /// Returns the height of this Font in the specified graphics context. /// </summary> public float GetHeight(Graphics graphics) { if (graphics == null) throw new ArgumentNullException("graphics"); float ht; int status = SafeNativeMethods.Gdip.GdipGetFontHeight(new HandleRef(this, NativeFont), new HandleRef(graphics, graphics.NativeGraphics), out ht); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return ht; } public float GetHeight() { IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); float height = 0.0f; try { using (Graphics graphics = Graphics.FromHdcInternal(screenDC)) { height = GetHeight(graphics); } } finally { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } return height; } public float GetHeight(float dpi) { float ht; int status = SafeNativeMethods.Gdip.GdipGetFontHeightGivenDPI(new HandleRef(this, NativeFont), dpi, out ht); if (status != SafeNativeMethods.Gdip.Ok) throw SafeNativeMethods.Gdip.StatusException(status); return ht; } /// <summary> /// Gets style information for this <see cref='Font'/>. /// </summary> [ Browsable(false) ] public FontStyle Style { get { return _fontStyle; } } // Return value is in Unit (the unit the font was created in) /// <summary> /// Gets the size of this <see cref='Font'/>. /// </summary> public float Size { get { return _fontSize; } } /// <summary> /// Gets the size, in points, of this <see cref='Font'/>. /// </summary> [Browsable(false)] public float SizeInPoints { get { if (Unit == GraphicsUnit.Point) return Size; else { float emHeightInPoints; IntPtr screenDC = UnsafeNativeMethods.GetDC(NativeMethods.NullHandleRef); try { using (Graphics graphics = Graphics.FromHdcInternal(screenDC)) { float pixelsPerPoint = (float)(graphics.DpiY / 72.0); float lineSpacingInPixels = GetHeight(graphics); float emHeightInPixels = lineSpacingInPixels * FontFamily.GetEmHeight(Style) / FontFamily.GetLineSpacing(Style); emHeightInPoints = emHeightInPixels / pixelsPerPoint; } } finally { UnsafeNativeMethods.ReleaseDC(NativeMethods.NullHandleRef, new HandleRef(null, screenDC)); } return emHeightInPoints; } } } /// <summary> /// Gets the unit of measure for this <see cref='Font'/>. /// </summary> public GraphicsUnit Unit { get { return _fontUnit; } } /// <summary> /// Gets the height of this <see cref='Font'/>. /// </summary> [ Browsable(false) ] public int Height { get { return (int)Math.Ceiling(GetHeight()); } } /// <summary> /// Returns true if this <see cref='Font'/> is a SystemFont. /// </summary> [ Browsable(false) ] public bool IsSystemFont { get { return !String.IsNullOrEmpty(_systemFontName); } } /// <summary> /// Gets the name of this <see cref='Drawing.SystemFont'/>. /// </summary> [ Browsable(false) ] public string SystemFontName { get { return _systemFontName; } } // This is used by SystemFonts when constructing a system Font objects. internal void SetSystemFontName(string systemFontName) { _systemFontName = systemFontName; } } }
// Copyright (c) 2013 Krkadoni.com - Released under The MIT License. // Full license text can be found at http://opensource.org/licenses/MIT using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Linq; using System.Runtime.Serialization; using Krkadoni.EnigmaSettings.Interfaces; namespace Krkadoni.EnigmaSettings { [DataContract] public class Service<TFlag> : IService where TFlag : class, IFlag { #region "INotifyPropertyChanged" public event PropertyChangedEventHandler PropertyChanged; protected void OnPropertyChanged(String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion #region "IEditable" private bool _isEditing; private string _mFlags; private bool _mLocked; private string _mName; private string _mProgNumber; private Enums.ServiceSecurity _mServiceSecurity; private string _mSid; private ITransponder _mTransponder; private string _mType; public void BeginEdit() { if (_isEditing) return; _mFlags = _flags; _mLocked = _locked; _mName = _name; _mProgNumber = _progNumber; _mServiceSecurity = _serviceSecurity; _mSid = _sid; _mTransponder = _transponder; _mType = _type; _isEditing = true; } public void EndEdit() { _isEditing = false; } public void CancelEdit() { if (!_isEditing) return; Locked = _mLocked; Name = _mName; ProgNumber = _mProgNumber; ServiceSecurity = _mServiceSecurity; SID = _mSid; Transponder = _mTransponder; Type = _mType; if (_flags != _mFlags) { _flags = _mFlags; OnPropertyChanged("Flags"); OnPropertyChanged("FlagList"); } _isEditing = false; } #endregion #region "ICloneable" /// <summary> /// Performs deep Clone on the object /// </summary> /// <returns></returns> public object Clone() { var s = (IService)MemberwiseClone(); s.Transponder = Transponder != null ? (ITransponder)Transponder.Clone() : null; return s; } #endregion private readonly string _transponderId = string.Empty; private string _flags = "p:"; private bool _locked; private string _name = string.Empty; private string _progNumber = "0"; private Enums.ServiceSecurity _serviceSecurity = Enums.ServiceSecurity.None; private string _sid = "0"; private ITransponder _transponder; private string _type = "0"; /// <summary> /// Initializes service properties from 1st line of service in lamedb /// </summary> /// <param name="serviceData">In format 0xSID:0xNAMESPACE:0xTSID:0xNID:type:prognumber</param> /// <param name="name"></param> /// <param name="flags"></param> /// <remarks>Throws argument null exception and argument exception if ServiceData is null, empty or invalid</remarks> /// <exception cref="ArgumentNullException">Throws argument null exception if serviceData or name is null/empty</exception> /// <exception cref="ArgumentException">Throws argument exception if serviceData is invalid</exception> public Service(string serviceData, string name, string flags) { if (string.IsNullOrEmpty(serviceData)) throw new ArgumentNullException(Resources.Service_ServiceData_Service_data_cannot_be_empty_); if (string.IsNullOrEmpty(name)) //throw new ArgumentNullException(Resources.Service_New_Service_name_cannot_be_empty); name = string.Empty; string[] sData = serviceData.Split(':'); if (sData.Length != 6) throw new ArgumentException(Resources.Service_ServiceData_Invalid_service_data_); SID = sData[0].Trim(); Type = sData[4].Trim(); ProgNumber = sData[5].Trim(); _transponderId = string.Join(":", new[] { sData[1], sData[2], sData[3] }); Name = name; _flags = flags; } /// <summary> /// Service ID /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> [DataMember] public string SID { get { return _sid; } set { if (value == null) value = "0"; if (value == _sid) return; _sid = value; OnPropertyChanged("SID"); OnPropertyChanged("ServiceId"); } } /// <summary> /// Defines type of service (TV,Radio,Data, etc..) /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> /// <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd693747(v=vs.85).aspx">Service types</see> [DataMember] public string Type { get { return _type; } set { if (value == null) value = "0"; if (value.Trim() == _type) return; _type = value.Trim(); OnPropertyChanged("Type"); OnPropertyChanged("ServiceType"); OnPropertyChanged("ServiceId"); } } /// <summary> /// Program number /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> [DataMember] public string ProgNumber { get { return _progNumber; } set { if (value == null) value = "0"; if (value == _progNumber) return; _progNumber = value; OnPropertyChanged("ProgNumber"); } } /// <summary> /// 1 -TV, 2-radio, 3-data /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> /// <see href="http://msdn.microsoft.com/en-us/library/windows/desktop/dd693747(v=vs.85).aspx">Service types</see> [DataMember] public Enums.ServiceType ServiceType { get { switch (Type) { case "1": return Enums.ServiceType.Tv; case "2": return Enums.ServiceType.Radio; case "3": return Enums.ServiceType.Data; case "0": return Enums.ServiceType.Reserved0; case "4": return Enums.ServiceType.NvodMpeg2Sd; case "5": return Enums.ServiceType.NvodTimeShifted; case "6": return Enums.ServiceType.Mosaic; case "7": return Enums.ServiceType.Reserved7; case "8": return Enums.ServiceType.Reserved8; case "9": return Enums.ServiceType.Reserved9; case "10": return Enums.ServiceType.AcRadio; case "11": return Enums.ServiceType.AcMosaic; case "12": return Enums.ServiceType.DataBroadcastService; case "13": return Enums.ServiceType.ReservedCi; case "14": return Enums.ServiceType.RcsMap; case "15": return Enums.ServiceType.RcsFls; case "16": return Enums.ServiceType.DVBMhp; case "17": return Enums.ServiceType.Mpeg2Hd; case "18": return Enums.ServiceType.Reserved18; case "19": return Enums.ServiceType.Reserved19; case "20": return Enums.ServiceType.Reserved20; case "21": return Enums.ServiceType.Reserved21; case "22": return Enums.ServiceType.AcSdtv; case "23": return Enums.ServiceType.AcSdNvodTimeShifted; case "24": return Enums.ServiceType.AcSdNvodReference; case "25": return Enums.ServiceType.AcHdtv; case "26": return Enums.ServiceType.AcHdNvodTimeShifted; case "27": return Enums.ServiceType.AcHdNvodReference; case "134": return Enums.ServiceType.UserDefined134Bskyb; case "135": return Enums.ServiceType.UserDefined135Bskyb; default: return Enums.ServiceType.Unknown; } } } /// <summary> /// Service name (2nd line in settings file) /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> [DataMember] public string Name { get { return _name; } set { if (value == _name) return; if (value == null) value = string.Empty; _name = value; OnPropertyChanged("Name"); } } /// <summary> /// Flags for Audio, Video, Subtitles, Provider etc.. /// </summary> /// <value>Returns 'p:' if empty</value> /// <returns></returns> /// <remarks></remarks> [DataMember] public string Flags { get { if (string.IsNullOrEmpty(_flags)) return "p:"; return _flags; } } /// <summary> /// Service information in format Type:0xSID:0xTSID:0xNID,0xNAMESPACE /// </summary> /// <value></value> /// <returns></returns> /// <remarks>Used to match service from bouquets</remarks> [DataMember] public string ServiceId { get { if (Transponder == null) { string mSid = SID.TrimStart('0'); if (mSid.Length == 0) mSid = "0"; return string.Join(":", new[] {"0", mSid, "0", "0", "0"}).ToLower(); } else { string mSid = SID.TrimStart('0'); if (mSid.Length == 0) mSid = "0"; string mTSID = Transponder.TSID.TrimStart('0'); if (mTSID.Length == 0) mTSID = "0"; string mNid = Transponder.NID.TrimStart('0'); if (mNid.Length == 0) mNid = "0"; string mNameSpc = Transponder.NameSpc.TrimStart('0'); if (mNameSpc.Length == 0) mNameSpc = "0"; return string.Join(":", new[] {Convert.ToInt32(Type).ToString("X"), mSid, mTSID, mNid, mNameSpc}).ToLower(); } } } /// <summary> /// 0xNAMESPACE:0xTSID:0xNID /// </summary> /// <value></value> /// <returns> /// If Transponder is set returns its TransponderID, otherwise returns value from service data it has been /// initialized with /// </returns> /// <remarks></remarks> [DataMember] public string TransponderId { get { if (Transponder == null) { return _transponderId.ToLower(); } return Transponder.TransponderId; } } [DataMember] public ITransponder Transponder { get { return _transponder; } set { if (value != _transponder) { _transponder = value; OnPropertyChanged("Transponder"); OnPropertyChanged("TransponderId"); OnPropertyChanged("ServiceId"); } } } /// <summary> /// Determines if service is in Whitelist or Blacklist file /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> [DataMember] public Enums.ServiceSecurity ServiceSecurity { get { return _serviceSecurity; } set { if (value == _serviceSecurity) return; _serviceSecurity = value; OnPropertyChanged("ServiceSecurity"); } } /// <summary> /// List of flag objects /// </summary> /// <value></value> /// <returns></returns> /// <remarks>Use UpdateFlags method to update flags</remarks> [DataMember] public ReadOnlyCollection<IFlag> FlagList { get { string[] fStrings = _flags.Split(','); var mFlagList = new List<IFlag>(); // ReSharper disable once LoopCanBeConvertedToQuery foreach (string fString in fStrings) { if (fString.IndexOf(":", StringComparison.CurrentCulture) > -1 && fString.Split(':').Length >= 2) { IFlag f = Activator.CreateInstance(typeof (TFlag), new object[] {fString}) as TFlag; if (f == null) continue; mFlagList.Add(f); } } return new ReadOnlyCollection<IFlag>(mFlagList); } } /// <summary> /// Determines if service is locked for updates /// </summary> /// <value></value> /// <returns></returns> /// <remarks></remarks> [DataMember] public bool Locked { get { return _locked; } set { if (value != Locked) { _locked = value; OnPropertyChanged("Locked"); } } } /// <summary> /// Syncs Flags string from the list of flags /// </summary> /// <remarks></remarks> public void UpdateFlags(IList<IFlag> flagsList) { _flags = string.Join(",", FlagList.Select(x => x.FlagString).ToArray()); OnPropertyChanged("Flags"); OnPropertyChanged("FlagList"); } public override string ToString() { string sData; if (Transponder == null) { sData = string.Join(":", new[] {SID, "00000000", "0000", "0000", Type, ProgNumber}); } else { sData = string.Join(":", new[] { SID.PadLeft(4, '0'), Transponder.NameSpc.PadRight(8, '0'), Transponder.TSID.PadLeft(4, '0'), Transponder.NID.PadLeft(4, '0'), Type, ProgNumber }); } return string.Join("\t", new[] { sData, Name, Flags }); } /// <summary> /// Performs MemberwiseClone on current object /// </summary> /// <returns></returns> public object ShallowCopy() { return MemberwiseClone(); } } }
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. #pragma warning disable 1634, 1691 #pragma warning disable 56523 using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Globalization; using System.Management.Automation.Configuration; using System.Management.Automation.Internal; using System.Management.Automation.Security; using System.Runtime.InteropServices; using System.Security.Cryptography; using System.Security.Cryptography.X509Certificates; using System.Text; using Microsoft.PowerShell; using Microsoft.PowerShell.Commands; using DWORD = System.UInt32; namespace Microsoft.PowerShell { /// <summary> /// Defines the different Execution Policies supported by the /// PSAuthorizationManager class. /// </summary> public enum ExecutionPolicy { /// Unrestricted - No files must be signed. If a file originates from the /// internet, Monad provides a warning prompt to alert the user. To /// suppress this warning message, right-click on the file in File Explorer, /// select "Properties," and then "Unblock." Unrestricted = 0, /// RemoteSigned - Only .msh and .mshxml files originating from the internet /// must be digitally signed. If remote, signed, and executed, Monad /// prompts to determine if files from the signing publisher should be /// run or not. This is the default setting. RemoteSigned = 1, /// AllSigned - All .msh and .mshxml files must be digitally signed. If /// signed and executed, Monad prompts to determine if files from the /// signing publisher should be run or not. AllSigned = 2, /// Restricted - All .msh files are blocked. Mshxml files must be digitally /// signed, and by a trusted publisher. If you haven't made a trust decision /// on the publisher yet, prompting is done as in AllSigned mode. Restricted = 3, /// Bypass - No files must be signed, and internet origin is not verified Bypass = 4, /// Undefined - Not specified at this scope Undefined = 5, /// <summary> /// Default - The most restrictive policy available. /// </summary> Default = Restricted } /// <summary> /// Defines the available configuration scopes for an execution /// policy. They are in the following priority, with successive /// elements overriding the items that precede them: /// LocalMachine -> CurrentUser -> Runspace. /// </summary> public enum ExecutionPolicyScope { /// Execution policy is retrieved from the /// PSExecutionPolicyPreference environment variable. Process = 0, /// Execution policy is retrieved from the HKEY_CURRENT_USER /// registry hive for the current ShellId. CurrentUser = 1, /// Execution policy is retrieved from the HKEY_LOCAL_MACHINE /// registry hive for the current ShellId. LocalMachine = 2, /// Execution policy is retrieved from the current user's /// group policy setting. UserPolicy = 3, /// Execution policy is retrieved from the machine-wide /// group policy setting. MachinePolicy = 4 } } namespace System.Management.Automation.Internal { /// <summary> /// The SAFER policy associated with this file. /// </summary> internal enum SaferPolicy { /// Explicitly allowed through an Allow rule ExplicitlyAllowed = 0, /// Allowed because it has not been explicitly disallowed Allowed = 1, /// Disallowed by a rule or policy. Disallowed = 2 } /// <summary> /// Security Support APIs. /// </summary> public static class SecuritySupport { #region execution policy internal static ExecutionPolicyScope[] ExecutionPolicyScopePreferences { get { return new ExecutionPolicyScope[] { ExecutionPolicyScope.MachinePolicy, ExecutionPolicyScope.UserPolicy, ExecutionPolicyScope.Process, ExecutionPolicyScope.CurrentUser, ExecutionPolicyScope.LocalMachine }; } } internal static void SetExecutionPolicy(ExecutionPolicyScope scope, ExecutionPolicy policy, string shellId) { #if UNIX throw new PlatformNotSupportedException(); #else string executionPolicy = "Restricted"; switch (policy) { case ExecutionPolicy.Restricted: executionPolicy = "Restricted"; break; case ExecutionPolicy.AllSigned: executionPolicy = "AllSigned"; break; case ExecutionPolicy.RemoteSigned: executionPolicy = "RemoteSigned"; break; case ExecutionPolicy.Unrestricted: executionPolicy = "Unrestricted"; break; case ExecutionPolicy.Bypass: executionPolicy = "Bypass"; break; } // Set the execution policy switch (scope) { case ExecutionPolicyScope.Process: if (policy == ExecutionPolicy.Undefined) executionPolicy = null; Environment.SetEnvironmentVariable("PSExecutionPolicyPreference", executionPolicy); break; case ExecutionPolicyScope.CurrentUser: // They want to remove it if (policy == ExecutionPolicy.Undefined) { PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.CurrentUser, shellId); } else { PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.CurrentUser, shellId, executionPolicy); } break; case ExecutionPolicyScope.LocalMachine: // They want to remove it if (policy == ExecutionPolicy.Undefined) { PowerShellConfig.Instance.RemoveExecutionPolicy(ConfigScope.AllUsers, shellId); } else { PowerShellConfig.Instance.SetExecutionPolicy(ConfigScope.AllUsers, shellId, executionPolicy); } break; } #endif } internal static ExecutionPolicy GetExecutionPolicy(string shellId) { foreach (ExecutionPolicyScope scope in ExecutionPolicyScopePreferences) { ExecutionPolicy policy = GetExecutionPolicy(shellId, scope); if (policy != ExecutionPolicy.Undefined) return policy; } return ExecutionPolicy.Restricted; } private static bool? _hasGpScriptParent; /// <summary> /// A value indicating that the current process was launched by GPScript.exe /// Used to determine execution policy when group policies are in effect. /// </summary> /// <remarks> /// This is somewhat expensive to determine and does not change within the lifetime of the current process /// </remarks> private static bool HasGpScriptParent { get { if (!_hasGpScriptParent.HasValue) { _hasGpScriptParent = IsCurrentProcessLaunchedByGpScript(); } return _hasGpScriptParent.Value; } } private static bool IsCurrentProcessLaunchedByGpScript() { Process currentProcess = Process.GetCurrentProcess(); string gpScriptPath = IO.Path.Combine( Environment.GetFolderPath(Environment.SpecialFolder.System), "gpscript.exe"); bool foundGpScriptParent = false; try { while (currentProcess != null) { if (string.Equals(gpScriptPath, currentProcess.MainModule.FileName, StringComparison.OrdinalIgnoreCase)) { foundGpScriptParent = true; break; } else { currentProcess = PsUtils.GetParentProcess(currentProcess); } } } catch (System.ComponentModel.Win32Exception) { // If you attempt to retrieve the MainModule of a 64-bit process // from a WOW64 (32-bit) process, the Win32 API has a fatal // flaw that causes this to return the error: // "Only part of a ReadProcessMemory or WriteProcessMemory // request was completed." // In this case, we just catch the exception and eat it. // The implication is that logon / logoff scripts that somehow // launch the Wow64 version of PowerShell will be subject // to the execution policy deployed by Group Policy (where // our goal here is to not have the Group Policy execution policy // affect logon / logoff scripts. } return foundGpScriptParent; } internal static ExecutionPolicy GetExecutionPolicy(string shellId, ExecutionPolicyScope scope) { #if UNIX return ExecutionPolicy.Unrestricted; #else switch (scope) { case ExecutionPolicyScope.Process: { string policy = Environment.GetEnvironmentVariable("PSExecutionPolicyPreference"); if (!string.IsNullOrEmpty(policy)) return ParseExecutionPolicy(policy); else return ExecutionPolicy.Undefined; } case ExecutionPolicyScope.CurrentUser: case ExecutionPolicyScope.LocalMachine: { string policy = GetLocalPreferenceValue(shellId, scope); if (!string.IsNullOrEmpty(policy)) return ParseExecutionPolicy(policy); else return ExecutionPolicy.Undefined; } // TODO: Group Policy is only supported on Full systems, but !LINUX && CORECLR // will run there as well, so I don't think we should remove it. case ExecutionPolicyScope.UserPolicy: case ExecutionPolicyScope.MachinePolicy: { string groupPolicyPreference = GetGroupPolicyValue(shellId, scope); // Be sure we aren't being called by Group Policy // itself. A group policy should never block a logon / // logoff script. if (string.IsNullOrEmpty(groupPolicyPreference) || HasGpScriptParent) { return ExecutionPolicy.Undefined; } return ParseExecutionPolicy(groupPolicyPreference); } } return ExecutionPolicy.Restricted; #endif } internal static ExecutionPolicy ParseExecutionPolicy(string policy) { if (string.Equals(policy, "Bypass", StringComparison.OrdinalIgnoreCase)) { return ExecutionPolicy.Bypass; } else if (string.Equals(policy, "Unrestricted", StringComparison.OrdinalIgnoreCase)) { return ExecutionPolicy.Unrestricted; } else if (string.Equals(policy, "RemoteSigned", StringComparison.OrdinalIgnoreCase)) { return ExecutionPolicy.RemoteSigned; } else if (string.Equals(policy, "AllSigned", StringComparison.OrdinalIgnoreCase)) { return ExecutionPolicy.AllSigned; } else if (string.Equals(policy, "Restricted", StringComparison.OrdinalIgnoreCase)) { return ExecutionPolicy.Restricted; } else { return ExecutionPolicy.Default; } } internal static string GetExecutionPolicy(ExecutionPolicy policy) { switch (policy) { case ExecutionPolicy.Bypass: return "Bypass"; case ExecutionPolicy.Unrestricted: return "Unrestricted"; case ExecutionPolicy.RemoteSigned: return "RemoteSigned"; case ExecutionPolicy.AllSigned: return "AllSigned"; case ExecutionPolicy.Restricted: return "Restricted"; default: return "Restricted"; } } /// <summary> /// Returns true if file has product binary signature. /// </summary> /// <param name="file">Name of file to check.</param> /// <returns>True when file has product binary signature.</returns> public static bool IsProductBinary(string file) { if (string.IsNullOrEmpty(file) || (!IO.File.Exists(file))) { return false; } // Check if it is in the product folder, if not, skip checking the catalog // and any other checks. var isUnderProductFolder = Utils.IsUnderProductFolder(file); if (!isUnderProductFolder) { return false; } #if UNIX // There is no signature support on non-Windows platforms (yet), when // execution reaches here, we are sure the file is under product folder return true; #else // Check the file signature Signature fileSignature = SignatureHelper.GetSignature(file, null); if ((fileSignature != null) && (fileSignature.IsOSBinary)) { return true; } // WTGetSignatureInfo is used to verify catalog signature. // On Win7, catalog API is not available. // On OneCore SKUs like NanoServer/IoT, the API has a bug that makes it not able to find the // corresponding catalog file for a given product file, so it doesn't work properly. // In these cases, we just trust the 'isUnderProductFolder' check. if (Signature.CatalogApiAvailable.HasValue && !Signature.CatalogApiAvailable.Value) { // When execution reaches here, we are sure the file is under product folder return true; } return false; #endif } /// <summary> /// Returns the value of the Execution Policy as retrieved /// from group policy. /// </summary> /// <returns>NULL if it is not defined at this level.</returns> private static string GetGroupPolicyValue(string shellId, ExecutionPolicyScope scope) { ConfigScope[] scopeKey = null; switch (scope) { case ExecutionPolicyScope.MachinePolicy: scopeKey = Utils.SystemWideOnlyConfig; break; case ExecutionPolicyScope.UserPolicy: scopeKey = Utils.CurrentUserOnlyConfig; break; } var scriptExecutionSetting = Utils.GetPolicySetting<ScriptExecution>(scopeKey); if (scriptExecutionSetting != null) { if (scriptExecutionSetting.EnableScripts == false) { // Script execution is explicitly disabled return "Restricted"; } else if (scriptExecutionSetting.EnableScripts == true) { // Script execution is explicitly enabled return scriptExecutionSetting.ExecutionPolicy; } } return null; } /// <summary> /// Returns the value of the Execution Policy as retrieved /// from the local preference. /// </summary> /// <returns>NULL if it is not defined at this level.</returns> private static string GetLocalPreferenceValue(string shellId, ExecutionPolicyScope scope) { switch (scope) { // 1: Look up the current-user preference case ExecutionPolicyScope.CurrentUser: return PowerShellConfig.Instance.GetExecutionPolicy(ConfigScope.CurrentUser, shellId); // 2: Look up the system-wide preference case ExecutionPolicyScope.LocalMachine: return PowerShellConfig.Instance.GetExecutionPolicy(ConfigScope.AllUsers, shellId); } return null; } #endregion execution policy private static bool _saferIdentifyLevelApiSupported = true; /// <summary> /// Get the pass / fail result of calling the SAFER API. /// </summary> /// <param name="path">The path to the file in question.</param> /// <param name="handle">A file handle to the file in question, if available.</param> [ArchitectureSensitive] [SuppressMessage("Microsoft.Reliability", "CA2001:AvoidCallingProblematicMethods")] internal static SaferPolicy GetSaferPolicy(string path, SafeHandle handle) { SaferPolicy status = SaferPolicy.Allowed; if (!_saferIdentifyLevelApiSupported) { return status; } SAFER_CODE_PROPERTIES codeProperties = new SAFER_CODE_PROPERTIES(); IntPtr hAuthzLevel; // Prepare the code properties struct. codeProperties.cbSize = (uint)Marshal.SizeOf(typeof(SAFER_CODE_PROPERTIES)); codeProperties.dwCheckFlags = ( NativeConstants.SAFER_CRITERIA_IMAGEPATH | NativeConstants.SAFER_CRITERIA_IMAGEHASH | NativeConstants.SAFER_CRITERIA_AUTHENTICODE); codeProperties.ImagePath = path; if (handle != null) { codeProperties.hImageFileHandle = handle.DangerousGetHandle(); } // turn off WinVerifyTrust UI codeProperties.dwWVTUIChoice = NativeConstants.WTD_UI_NONE; // Identify the level associated with the code if (NativeMethods.SaferIdentifyLevel(1, ref codeProperties, out hAuthzLevel, NativeConstants.SRP_POLICY_SCRIPT)) { // We found an Authorization Level applicable to this application. IntPtr hRestrictedToken = IntPtr.Zero; try { if (!NativeMethods.SaferComputeTokenFromLevel( hAuthzLevel, // Safer Level IntPtr.Zero, // Test current process' token ref hRestrictedToken, // target token NativeConstants.SAFER_TOKEN_NULL_IF_EQUAL, IntPtr.Zero)) { int lastError = Marshal.GetLastWin32Error(); if ((lastError == NativeConstants.ERROR_ACCESS_DISABLED_BY_POLICY) || (lastError == NativeConstants.ERROR_ACCESS_DISABLED_NO_SAFER_UI_BY_POLICY)) { status = SaferPolicy.Disallowed; } else { throw new System.ComponentModel.Win32Exception(); } } else { if (hRestrictedToken == IntPtr.Zero) { // This is not necessarily the "fully trusted" level, // it means that the thread token is complies with the requested level status = SaferPolicy.Allowed; } else { status = SaferPolicy.Disallowed; NativeMethods.CloseHandle(hRestrictedToken); } } } finally { NativeMethods.SaferCloseLevel(hAuthzLevel); } } else { int lastError = Marshal.GetLastWin32Error(); if (lastError == NativeConstants.FUNCTION_NOT_SUPPORTED) { _saferIdentifyLevelApiSupported = false; } else { throw new System.ComponentModel.Win32Exception(lastError); } } return status; } /// <summary> /// Throw if file does not exist. /// </summary> /// <param name="filePath">Path to file.</param> /// <returns>Does not return a value.</returns> internal static void CheckIfFileExists(string filePath) { if (!File.Exists(filePath)) { throw new FileNotFoundException(filePath); } } /// <summary> /// Check to see if the specified cert is suitable to be /// used as a code signing cert. /// </summary> /// <param name="c">Certificate object.</param> /// <returns>True on success, false otherwise.</returns> internal static bool CertIsGoodForSigning(X509Certificate2 c) { if (!c.HasPrivateKey) { return false; } return CertHasOid(c, CertificateFilterInfo.CodeSigningOid); } /// <summary> /// Check to see if the specified cert is suitable to be /// used as an encryption cert for PKI encryption. Note /// that this cert doesn't require the private key. /// </summary> /// <param name="c">Certificate object.</param> /// <returns>True on success, false otherwise.</returns> internal static bool CertIsGoodForEncryption(X509Certificate2 c) { return ( CertHasOid(c, CertificateFilterInfo.DocumentEncryptionOid) && (CertHasKeyUsage(c, X509KeyUsageFlags.DataEncipherment) || CertHasKeyUsage(c, X509KeyUsageFlags.KeyEncipherment))); } /// <summary> /// Check to see if the specified cert is expiring by the time. /// </summary> /// <param name="c">Certificate object.</param> /// <param name="expiring">Certificate expire time.</param> /// <returns>True on success, false otherwise.</returns> internal static bool CertExpiresByTime(X509Certificate2 c, DateTime expiring) { return c.NotAfter < expiring; } private static bool CertHasOid(X509Certificate2 c, string oid) { foreach (var extension in c.Extensions) { if (extension is X509EnhancedKeyUsageExtension ext) { foreach (Oid ekuOid in ext.EnhancedKeyUsages) { if (ekuOid.Value == oid) { return true; } } break; } } return false; } private static bool CertHasKeyUsage(X509Certificate2 c, X509KeyUsageFlags keyUsage) { foreach (X509Extension extension in c.Extensions) { X509KeyUsageExtension keyUsageExtension = extension as X509KeyUsageExtension; if (keyUsageExtension != null) { if ((keyUsageExtension.KeyUsages & keyUsage) == keyUsage) { return true; } break; } } return false; } /// <summary> /// Get the EKUs of a cert. /// </summary> /// <param name="cert">Certificate object.</param> /// <returns>A collection of cert eku strings.</returns> [ArchitectureSensitive] internal static Collection<string> GetCertEKU(X509Certificate2 cert) { Collection<string> ekus = new Collection<string>(); IntPtr pCert = cert.Handle; int structSize = 0; IntPtr dummy = IntPtr.Zero; if (Security.NativeMethods.CertGetEnhancedKeyUsage(pCert, 0, dummy, out structSize)) { if (structSize > 0) { IntPtr ekuBuffer = Marshal.AllocHGlobal(structSize); try { if (Security.NativeMethods.CertGetEnhancedKeyUsage(pCert, 0, ekuBuffer, out structSize)) { Security.NativeMethods.CERT_ENHKEY_USAGE ekuStruct = Marshal.PtrToStructure<Security.NativeMethods.CERT_ENHKEY_USAGE>(ekuBuffer); IntPtr ep = ekuStruct.rgpszUsageIdentifier; IntPtr ekuptr; for (int i = 0; i < ekuStruct.cUsageIdentifier; i++) { ekuptr = Marshal.ReadIntPtr(ep, i * Marshal.SizeOf(ep)); string eku = Marshal.PtrToStringAnsi(ekuptr); ekus.Add(eku); } } else { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } } finally { Marshal.FreeHGlobal(ekuBuffer); } } } else { throw new System.ComponentModel.Win32Exception(Marshal.GetLastWin32Error()); } return ekus; } /// <summary> /// Convert an int to a DWORD. /// </summary> /// <param name="n">Signed int number.</param> /// <returns>DWORD.</returns> internal static DWORD GetDWORDFromInt(int n) { UInt32 result = BitConverter.ToUInt32(BitConverter.GetBytes(n), 0); return (DWORD)result; } /// <summary> /// Convert a DWORD to int. /// </summary> /// <param name="n">Number.</param> /// <returns>Int.</returns> internal static int GetIntFromDWORD(DWORD n) { Int64 n64 = n - 0x100000000L; return (int)n64; } } /// <summary> /// Information used for filtering a set of certs. /// </summary> internal sealed class CertificateFilterInfo { internal CertificateFilterInfo() { } /// <summary> /// Gets or sets purpose of a certificate. /// </summary> internal CertificatePurpose Purpose { get; set; } = CertificatePurpose.NotSpecified; /// <summary> /// Gets or sets SSL Server Authentication. /// </summary> internal bool SSLServerAuthentication { get; set; } /// <summary> /// Gets or sets DNS name of a certificate. /// </summary> internal WildcardPattern DnsName { get; set; } /// <summary> /// Gets or sets EKU OID list of a certificate. /// </summary> internal List<WildcardPattern> Eku { get; set; } /// <summary> /// Gets or sets validity time for a certificate. /// </summary> internal DateTime Expiring { get; set; } = DateTime.MinValue; internal const string CodeSigningOid = "1.3.6.1.5.5.7.3.3"; internal const string OID_PKIX_KP_SERVER_AUTH = "1.3.6.1.5.5.7.3.1"; // The OID arc 1.3.6.1.4.1.311.80 is assigned to PowerShell. If we need // new OIDs, we can assign them under this branch. internal const string DocumentEncryptionOid = "1.3.6.1.4.1.311.80.1"; } } namespace Microsoft.PowerShell.Commands { /// <summary> /// Defines the valid purposes by which /// we can filter certificates. /// </summary> internal enum CertificatePurpose { /// <summary> /// Certificates where a purpose has not been specified. /// </summary> NotSpecified = 0, /// <summary> /// Certificates that can be used to sign /// code and scripts. /// </summary> CodeSigning = 0x1, /// <summary> /// Certificates that can be used to encrypt /// data. /// </summary> DocumentEncryption = 0x2, /// <summary> /// Certificates that can be used for any /// purpose. /// </summary> All = 0xffff } } namespace System.Management.Automation { using System.Security.Cryptography.Pkcs; /// <summary> /// Utility class for CMS (Cryptographic Message Syntax) related operations. /// </summary> internal static class CmsUtils { internal static string Encrypt(byte[] contentBytes, CmsMessageRecipient[] recipients, SessionState sessionState, out ErrorRecord error) { error = null; if ((contentBytes == null) || (contentBytes.Length == 0)) { return string.Empty; } // After review with the crypto board, NIST_AES256_CBC is more appropriate // than .NET's default 3DES. Also, when specified, uses szOID_RSAES_OAEP for key // encryption to prevent padding attacks. const string szOID_NIST_AES256_CBC = "2.16.840.1.101.3.4.1.42"; ContentInfo content = new ContentInfo(contentBytes); EnvelopedCms cms = new EnvelopedCms(content, new AlgorithmIdentifier( Oid.FromOidValue(szOID_NIST_AES256_CBC, OidGroup.EncryptionAlgorithm))); CmsRecipientCollection recipientCollection = new CmsRecipientCollection(); foreach (CmsMessageRecipient recipient in recipients) { // Resolve the recipient, if it hasn't been done yet. if ((recipient.Certificates != null) && (recipient.Certificates.Count == 0)) { recipient.Resolve(sessionState, ResolutionPurpose.Encryption, out error); } if (error != null) { return null; } foreach (X509Certificate2 certificate in recipient.Certificates) { recipientCollection.Add(new CmsRecipient(certificate)); } } cms.Encrypt(recipientCollection); byte[] encodedBytes = cms.Encode(); string encodedContent = CmsUtils.GetAsciiArmor(encodedBytes); return encodedContent; } internal static readonly string BEGIN_CMS_SIGIL = "-----BEGIN CMS-----"; internal static readonly string END_CMS_SIGIL = "-----END CMS-----"; internal static readonly string BEGIN_CERTIFICATE_SIGIL = "-----BEGIN CERTIFICATE-----"; internal static readonly string END_CERTIFICATE_SIGIL = "-----END CERTIFICATE-----"; /// <summary> /// Adds Ascii armour to a byte stream in Base64 format. /// </summary> /// <param name="bytes">The bytes to encode.</param> internal static string GetAsciiArmor(byte[] bytes) { StringBuilder output = new StringBuilder(); output.AppendLine(BEGIN_CMS_SIGIL); string encodedString = Convert.ToBase64String(bytes, Base64FormattingOptions.InsertLineBreaks); output.AppendLine(encodedString); output.Append(END_CMS_SIGIL); return output.ToString(); } /// <summary> /// Removes Ascii armour from a byte stream. /// </summary> /// <param name="actualContent">The Ascii armored content.</param> /// <param name="beginMarker">The marker of the start of the Base64 content.</param> /// <param name="endMarker">The marker of the end of the Base64 content.</param> /// <param name="startIndex">The beginning of where the Ascii armor was detected.</param> /// <param name="endIndex">The end of where the Ascii armor was detected.</param> internal static byte[] RemoveAsciiArmor(string actualContent, string beginMarker, string endMarker, out int startIndex, out int endIndex) { byte[] messageBytes = null; startIndex = -1; endIndex = -1; startIndex = actualContent.IndexOf(beginMarker, StringComparison.OrdinalIgnoreCase); if (startIndex < 0) { return null; } endIndex = actualContent.IndexOf(endMarker, startIndex, StringComparison.OrdinalIgnoreCase) + endMarker.Length; if (endIndex < endMarker.Length) { return null; } int startContent = startIndex + beginMarker.Length; int endContent = endIndex - endMarker.Length; string encodedContent = actualContent.Substring(startContent, endContent - startContent); encodedContent = System.Text.RegularExpressions.Regex.Replace(encodedContent, "\\s", string.Empty); messageBytes = Convert.FromBase64String(encodedContent); return messageBytes; } } /// <summary> /// Represents a message recipient for the Cms cmdlets. /// </summary> public class CmsMessageRecipient { /// <summary> /// Creates an instance of the CmsMessageRecipient class. /// </summary> internal CmsMessageRecipient() { } /// <summary> /// Creates an instance of the CmsMessageRecipient class. /// </summary> /// <param name="identifier"> /// The identifier of the CmsMessageRecipient. /// Can be either: /// - The path to a file containing the certificate /// - The path to a directory containing the certificate /// - The thumbprint of the certificate, used to find the certificate in the certificate store /// - The Subject name of the recipient, used to find the certificate in the certificate store /// </param> public CmsMessageRecipient(string identifier) { _identifier = identifier; this.Certificates = new X509Certificate2Collection(); } private readonly string _identifier; /// <summary> /// Creates an instance of the CmsMessageRecipient class. /// </summary> /// <param name="certificate">The certificate to use.</param> public CmsMessageRecipient(X509Certificate2 certificate) { _pendingCertificate = certificate; this.Certificates = new X509Certificate2Collection(); } private readonly X509Certificate2 _pendingCertificate; /// <summary> /// Gets the certificate associated with this recipient. /// </summary> public X509Certificate2Collection Certificates { get; internal set; } /// <summary> /// Resolves the provided identifier into a collection of certificates. /// </summary> /// <param name="sessionState">A reference to an instance of Powershell's SessionState class.</param> /// <param name="purpose">The purpose for which this identifier is being resolved (Encryption / Decryption.</param> /// <param name="error">The error generated (if any) for this resolution.</param> public void Resolve(SessionState sessionState, ResolutionPurpose purpose, out ErrorRecord error) { error = null; // Process the certificate if that was supplied exactly if (_pendingCertificate != null) { ProcessResolvedCertificates( purpose, new X509Certificate2Collection(_pendingCertificate), out error); if ((error != null) || (Certificates.Count != 0)) { return; } } if (_identifier != null) { // First try to resolve assuming that the cert was Base64 encoded. ResolveFromBase64Encoding(purpose, out error); if ((error != null) || (Certificates.Count != 0)) { return; } // Then try to resolve by path. ResolveFromPath(sessionState, purpose, out error); if ((error != null) || (Certificates.Count != 0)) { return; } // Then by cert store ResolveFromStoreById(purpose, out error); if ((error != null) || (Certificates.Count != 0)) { return; } } // Generate an error if no cert was found (and this is an encryption attempt). // If it is only decryption, then the system will always look in the 'My' store anyways, so // don't generate an error if they used wildcards. If they did not use wildcards, // then generate an error because they were expecting something specific. if ((purpose == ResolutionPurpose.Encryption) || (!WildcardPattern.ContainsWildcardCharacters(_identifier))) { error = new ErrorRecord( new ArgumentException( string.Format(CultureInfo.InvariantCulture, SecuritySupportStrings.NoCertificateFound, _identifier)), "NoCertificateFound", ErrorCategory.ObjectNotFound, _identifier); } return; } private void ResolveFromBase64Encoding(ResolutionPurpose purpose, out ErrorRecord error) { error = null; int startIndex, endIndex; byte[] messageBytes = null; try { messageBytes = CmsUtils.RemoveAsciiArmor(_identifier, CmsUtils.BEGIN_CERTIFICATE_SIGIL, CmsUtils.END_CERTIFICATE_SIGIL, out startIndex, out endIndex); } catch (FormatException) { // Not Base-64 encoded return; } // Didn't have the sigil if (messageBytes == null) { return; } var certificatesToProcess = new X509Certificate2Collection(); try { X509Certificate2 newCertificate = new X509Certificate2(messageBytes); certificatesToProcess.Add(newCertificate); } catch (Exception) { // User call-out, catch-all OK // Wasn't certificate data return; } // Now validate the certificate ProcessResolvedCertificates(purpose, certificatesToProcess, out error); } private void ResolveFromPath(SessionState sessionState, ResolutionPurpose purpose, out ErrorRecord error) { error = null; ProviderInfo pathProvider = null; Collection<string> resolvedPaths = null; try { resolvedPaths = sessionState.Path.GetResolvedProviderPathFromPSPath(_identifier, out pathProvider); } catch (SessionStateException) { // If we got an ItemNotFound / etc., then this didn't represent a valid path. } // If we got a resolved path, try to load certs from that path. if ((resolvedPaths != null) && (resolvedPaths.Count != 0)) { // Ensure the path is from the file system provider if (!string.Equals(pathProvider.Name, "FileSystem", StringComparison.OrdinalIgnoreCase)) { error = new ErrorRecord( new ArgumentException( string.Format(CultureInfo.InvariantCulture, SecuritySupportStrings.CertificatePathMustBeFileSystemPath, _identifier)), "CertificatePathMustBeFileSystemPath", ErrorCategory.ObjectNotFound, pathProvider); return; } // If this is a directory, add all certificates in it. This will be the primary // scenario for decryption via Group Protected PFX files // (http://social.technet.microsoft.com/wiki/contents/articles/13922.certificate-pfx-export-and-import-using-ad-ds-account-protection.aspx) List<string> pathsToAdd = new List<string>(); List<string> pathsToRemove = new List<string>(); foreach (string resolvedPath in resolvedPaths) { if (System.IO.Directory.Exists(resolvedPath)) { // It would be nice to limit this to *.pfx, *.cer, etc., but // the crypto APIs support extracting certificates from arbitrary file types. pathsToAdd.AddRange(System.IO.Directory.GetFiles(resolvedPath)); pathsToRemove.Add(resolvedPath); } } // Update resolved paths foreach (string path in pathsToAdd) { resolvedPaths.Add(path); } foreach (string path in pathsToRemove) { resolvedPaths.Remove(path); } var certificatesToProcess = new X509Certificate2Collection(); foreach (string path in resolvedPaths) { X509Certificate2 certificate = null; try { certificate = new X509Certificate2(path); } catch (Exception) { // User call-out, catch-all OK continue; } certificatesToProcess.Add(certificate); } ProcessResolvedCertificates(purpose, certificatesToProcess, out error); } } private void ResolveFromStoreById(ResolutionPurpose purpose, out ErrorRecord error) { error = null; WildcardPattern subjectNamePattern = WildcardPattern.Get(_identifier, WildcardOptions.IgnoreCase); try { var certificatesToProcess = new X509Certificate2Collection(); using (var storeCU = new X509Store("my", StoreLocation.CurrentUser)) { storeCU.Open(OpenFlags.ReadOnly); X509Certificate2Collection storeCerts = storeCU.Certificates; if (Platform.IsWindows) { using (var storeLM = new X509Store("my", StoreLocation.LocalMachine)) { storeLM.Open(OpenFlags.ReadOnly); storeCerts.AddRange(storeLM.Certificates); } } certificatesToProcess.AddRange(storeCerts.Find(X509FindType.FindByThumbprint, _identifier, validOnly: false)); if (certificatesToProcess.Count == 0) { foreach (var cert in storeCerts) { if (subjectNamePattern.IsMatch(cert.Subject) || subjectNamePattern.IsMatch(cert.GetNameInfo(X509NameType.SimpleName, forIssuer: false))) { certificatesToProcess.Add(cert); } } } ProcessResolvedCertificates(purpose, certificatesToProcess, out error); } } catch (SessionStateException) { } } private void ProcessResolvedCertificates(ResolutionPurpose purpose, X509Certificate2Collection certificatesToProcess, out ErrorRecord error) { error = null; HashSet<string> processedThumbprints = new HashSet<string>(); foreach (X509Certificate2 certificate in certificatesToProcess) { if (!SecuritySupport.CertIsGoodForEncryption(certificate)) { // If they specified a specific cert, generate an error if it isn't good // for encryption. if (!WildcardPattern.ContainsWildcardCharacters(_identifier)) { error = new ErrorRecord( new ArgumentException( string.Format( CultureInfo.InvariantCulture, SecuritySupportStrings.CertificateCannotBeUsedForEncryption, certificate.Thumbprint, CertificateFilterInfo.DocumentEncryptionOid)), "CertificateCannotBeUsedForEncryption", ErrorCategory.InvalidData, certificate); return; } else { continue; } } // When decrypting, only look for certs that have the private key if (purpose == ResolutionPurpose.Decryption) { if (!certificate.HasPrivateKey) { continue; } } if (processedThumbprints.Contains(certificate.Thumbprint)) { continue; } else { processedThumbprints.Add(certificate.Thumbprint); } if (purpose == ResolutionPurpose.Encryption) { // Only let wildcards expand to one recipient. Otherwise, data // may be encrypted to the wrong person on accident. if (Certificates.Count > 0) { error = new ErrorRecord( new ArgumentException( string.Format( CultureInfo.InvariantCulture, SecuritySupportStrings.IdentifierMustReferenceSingleCertificate, _identifier, arg1: "To")), "IdentifierMustReferenceSingleCertificate", ErrorCategory.LimitsExceeded, certificatesToProcess); Certificates.Clear(); return; } } Certificates.Add(certificate); } } } /// <summary> /// Defines the purpose for resolution of a CmsMessageRecipient. /// </summary> public enum ResolutionPurpose { /// <summary> /// This message recipient is intended to be used for message encryption. /// </summary> Encryption, /// <summary> /// This message recipient is intended to be used for message decryption. /// </summary> Decryption } internal static class AmsiUtils { internal static int Init() { Diagnostics.Assert(s_amsiContext == IntPtr.Zero, "Init should be called just once"); lock (s_amsiLockObject) { string appName; try { appName = string.Concat("PowerShell_", Environment.ProcessPath, "_", PSVersionInfo.ProductVersion); } catch (Exception) { // Fall back to 'Process.ProcessName' in case 'Environment.ProcessPath' throws exception. Process currentProcess = Process.GetCurrentProcess(); appName = string.Concat("PowerShell_", currentProcess.ProcessName, ".exe_", PSVersionInfo.ProductVersion); } AppDomain.CurrentDomain.ProcessExit += CurrentDomain_ProcessExit; var hr = AmsiNativeMethods.AmsiInitialize(appName, ref s_amsiContext); if (!Utils.Succeeded(hr)) { s_amsiInitFailed = true; } return hr; } } /// <summary> /// Scans a string buffer for malware using the Antimalware Scan Interface (AMSI). /// Caller is responsible for calling AmsiCloseSession when a "session" (script) /// is complete, and for calling AmsiUninitialize when the runspace is being torn down. /// </summary> /// <param name="content">The string to be scanned.</param> /// <param name="sourceMetadata">Information about the source (filename, etc.).</param> /// <returns>AMSI_RESULT_DETECTED if malware was detected in the sample.</returns> internal static AmsiNativeMethods.AMSI_RESULT ScanContent(string content, string sourceMetadata) { #if UNIX return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; #else return WinScanContent(content, sourceMetadata, warmUp: false); #endif } internal static AmsiNativeMethods.AMSI_RESULT WinScanContent( string content, string sourceMetadata, bool warmUp) { if (string.IsNullOrEmpty(sourceMetadata)) { sourceMetadata = string.Empty; } const string EICAR_STRING = "X5O!P%@AP[4\\PZX54(P^)7CC)7}$EICAR-STANDARD-ANTIVIRUS-TEST-FILE!$H+H*"; if (InternalTestHooks.UseDebugAmsiImplementation) { if (content.Contains(EICAR_STRING, StringComparison.Ordinal)) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_DETECTED; } } // If we had a previous initialization failure, just return the neutral result. if (s_amsiInitFailed) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } lock (s_amsiLockObject) { if (s_amsiInitFailed) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } try { if (!CheckAmsiInit()) { return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } if (warmUp) { // We are warming up the AMSI component in console startup, and that means we initialize AMSI // and create a AMSI session, but don't really scan anything. return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } AmsiNativeMethods.AMSI_RESULT result = AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_CLEAN; // Run AMSI content scan int hr; unsafe { fixed (char* buffer = content) { var buffPtr = new IntPtr(buffer); hr = AmsiNativeMethods.AmsiScanBuffer( s_amsiContext, buffPtr, (uint)(content.Length * sizeof(char)), sourceMetadata, s_amsiSession, ref result); } } if (!Utils.Succeeded(hr)) { // If we got a failure, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } return result; } catch (DllNotFoundException) { s_amsiInitFailed = true; return AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; } } } /// <Summary> /// Reports provided content to AMSI (Antimalware Scan Interface). /// </Summary> /// <param name="name">Name of content being reported.</param> /// <param name="content">Content being reported.</param> /// <returns>True if content was successfully reported.</returns> internal static bool ReportContent( string name, string content) { #if UNIX return false; #else return WinReportContent(name, content); #endif } private static bool WinReportContent( string name, string content) { if (string.IsNullOrEmpty(name) || string.IsNullOrEmpty(content) || s_amsiInitFailed || s_amsiNotifyFailed) { return false; } lock (s_amsiLockObject) { if (s_amsiNotifyFailed) { return false; } try { if (!CheckAmsiInit()) { return false; } int hr; AmsiNativeMethods.AMSI_RESULT result = AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_NOT_DETECTED; unsafe { fixed (char* buffer = content) { var buffPtr = new IntPtr(buffer); hr = AmsiNativeMethods.AmsiNotifyOperation( amsiContext: s_amsiContext, buffer: buffPtr, length: (uint)(content.Length * sizeof(char)), contentName: name, ref result); } } if (Utils.Succeeded(hr)) { if (result == AmsiNativeMethods.AMSI_RESULT.AMSI_RESULT_DETECTED) { // If malware is detected, throw to prevent method invoke expression from running. throw new PSSecurityException(ParserStrings.ScriptContainedMaliciousContent); } return true; } return false; } catch (DllNotFoundException) { s_amsiNotifyFailed = true; return false; } catch (System.EntryPointNotFoundException) { s_amsiNotifyFailed = true; return false; } } } private static bool CheckAmsiInit() { // Initialize AntiMalware Scan Interface, if not already initialized. // If we failed to initialize previously, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") if (s_amsiContext == IntPtr.Zero) { int hr = Init(); if (!Utils.Succeeded(hr)) { s_amsiInitFailed = true; return false; } } // Initialize the session, if one isn't already started. // If we failed to initialize previously, just return the neutral result ("AMSI_RESULT_NOT_DETECTED") if (s_amsiSession == IntPtr.Zero) { int hr = AmsiNativeMethods.AmsiOpenSession(s_amsiContext, ref s_amsiSession); AmsiInitialized = true; if (!Utils.Succeeded(hr)) { s_amsiInitFailed = true; return false; } } return true; } internal static void CurrentDomain_ProcessExit(object sender, EventArgs e) { if (AmsiInitialized && !AmsiUninitializeCalled) { Uninitialize(); } } [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private static IntPtr s_amsiContext = IntPtr.Zero; [SuppressMessage("Microsoft.Reliability", "CA2006:UseSafeHandleToEncapsulateNativeResources")] private static IntPtr s_amsiSession = IntPtr.Zero; private static bool s_amsiInitFailed = false; private static bool s_amsiNotifyFailed = false; private static readonly object s_amsiLockObject = new object(); /// <summary> /// Reset the AMSI session (used to track related script invocations) /// </summary> internal static void CloseSession() { #if !UNIX WinCloseSession(); #endif } internal static void WinCloseSession() { if (!s_amsiInitFailed) { if ((s_amsiContext != IntPtr.Zero) && (s_amsiSession != IntPtr.Zero)) { lock (s_amsiLockObject) { // Clean up the session if one was open. if ((s_amsiContext != IntPtr.Zero) && (s_amsiSession != IntPtr.Zero)) { AmsiNativeMethods.AmsiCloseSession(s_amsiContext, s_amsiSession); s_amsiSession = IntPtr.Zero; } } } } } /// <summary> /// Uninitialize the AMSI interface. /// </summary> internal static void Uninitialize() { #if !UNIX WinUninitialize(); #endif } internal static void WinUninitialize() { AmsiUninitializeCalled = true; if (!s_amsiInitFailed) { lock (s_amsiLockObject) { if (s_amsiContext != IntPtr.Zero) { CloseSession(); // Unregister the event handler. AppDomain.CurrentDomain.ProcessExit -= CurrentDomain_ProcessExit; // Uninitialize the AMSI interface. AmsiCleanedUp = true; AmsiNativeMethods.AmsiUninitialize(s_amsiContext); s_amsiContext = IntPtr.Zero; } } } } public static bool AmsiUninitializeCalled = false; public static bool AmsiInitialized = false; public static bool AmsiCleanedUp = false; internal static class AmsiNativeMethods { internal enum AMSI_RESULT { /// AMSI_RESULT_CLEAN -> 0 AMSI_RESULT_CLEAN = 0, /// AMSI_RESULT_NOT_DETECTED -> 1 AMSI_RESULT_NOT_DETECTED = 1, /// Certain policies set by administrator blocked this content on this machine AMSI_RESULT_BLOCKED_BY_ADMIN_BEGIN = 0x4000, AMSI_RESULT_BLOCKED_BY_ADMIN_END = 0x4fff, /// AMSI_RESULT_DETECTED -> 32768 AMSI_RESULT_DETECTED = 32768, } /// Return Type: HRESULT->LONG->int ///appName: LPCWSTR->WCHAR* ///amsiContext: HAMSICONTEXT* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiInitialize", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiInitialize( [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string appName, ref System.IntPtr amsiContext); /// Return Type: void ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiUninitialize", CallingConvention = CallingConvention.StdCall)] internal static extern void AmsiUninitialize(System.IntPtr amsiContext); /// Return Type: HRESULT->LONG->int ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///amsiSession: HAMSISESSION* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiOpenSession", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiOpenSession(System.IntPtr amsiContext, ref System.IntPtr amsiSession); /// Return Type: void ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///amsiSession: HAMSISESSION->HAMSISESSION__* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiCloseSession", CallingConvention = CallingConvention.StdCall)] internal static extern void AmsiCloseSession(System.IntPtr amsiContext, System.IntPtr amsiSession); /// Return Type: HRESULT->LONG->int ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///buffer: PVOID->void* ///length: ULONG->unsigned int ///contentName: LPCWSTR->WCHAR* ///amsiSession: HAMSISESSION->HAMSISESSION__* ///result: AMSI_RESULT* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiScanBuffer", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiScanBuffer( System.IntPtr amsiContext, System.IntPtr buffer, uint length, [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string contentName, System.IntPtr amsiSession, ref AMSI_RESULT result); /// Return Type: HRESULT->LONG->int /// amsiContext: HAMSICONTEXT->HAMSICONTEXT__* /// buffer: PVOID->void* /// length: ULONG->unsigned int /// contentName: LPCWSTR->WCHAR* /// result: AMSI_RESULT* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiNotifyOperation", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiNotifyOperation( System.IntPtr amsiContext, System.IntPtr buffer, uint length, [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string contentName, ref AMSI_RESULT result); /// Return Type: HRESULT->LONG->int ///amsiContext: HAMSICONTEXT->HAMSICONTEXT__* ///string: LPCWSTR->WCHAR* ///contentName: LPCWSTR->WCHAR* ///amsiSession: HAMSISESSION->HAMSISESSION__* ///result: AMSI_RESULT* [DefaultDllImportSearchPathsAttribute(DllImportSearchPath.System32)] [DllImportAttribute("amsi.dll", EntryPoint = "AmsiScanString", CallingConvention = CallingConvention.StdCall)] internal static extern int AmsiScanString( System.IntPtr amsiContext, [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string @string, [InAttribute()][MarshalAsAttribute(UnmanagedType.LPWStr)] string contentName, System.IntPtr amsiSession, ref AMSI_RESULT result); } } } #pragma warning restore 56523
//----------------------------------------------------------------------------- // Copyright (c) 2012 GarageGames, LLC // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to // deal in the Software without restriction, including without limitation the // rights to use, copy, modify, merge, publish, distribute, sublicense, and/or // sell copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS // IN THE SOFTWARE. //----------------------------------------------------------------------------- // Open the particle editor to spawn a test emitter in front of the player. // Edit the sliders, check boxes, and text fields and see the results in // realtime. Switch between emitters and particles with the buttons in the // top left corner. When in particle mode, the only particles available will // be those assigned to the current emitter to avoid confusion. In the top // right corner, there is a button marked "Drop Emitter", which will spawn the // test emitter in front of the player again, and a button marked "Restart // Emitter", which will play the particle animation again. //============================================================================================= // ParticleEditor. //============================================================================================= //--------------------------------------------------------------------------------------------- function ParticleEditor::initEditor( %this ) { echo( "Initializing ParticleEmitterData and ParticleData DataBlocks..." ); datablock ParticleEmitterData(PE_EmitterEditor_NotDirtyEmitter) { particles = "DefaultParticle"; }; datablock ParticleData(PE_ParticleEditor_NotDirtyParticle) { textureName = "art/particles/defaultParticle"; }; PE_UnlistedEmitters.add( PE_EmitterEditor_NotDirtyEmitter ); PE_UnlistedEmitters.add( PE_ParticleEditor_NotDirtyParticle ); PEE_EmitterSelector.clear(); PEE_EmitterParticleSelector1.clear(); PEE_EmitterParticleSelector2.clear(); PEE_EmitterParticleSelector3.clear(); PEE_EmitterParticleSelector4.clear(); PEP_ParticleSelector.clear(); ParticleEditor.createParticleList(); PEE_EmitterParticleSelector2.add( "None", 0 ); PEE_EmitterParticleSelector3.add( "None", 0 ); PEE_EmitterParticleSelector4.add( "None", 0 ); PEE_EmitterParticleSelector1.sort(); PEE_EmitterParticleSelector2.sort(); PEE_EmitterParticleSelector3.sort(); PEE_EmitterParticleSelector4.sort(); PE_EmitterEditor-->PEE_blendType.clear(); PE_EmitterEditor-->PEE_blendType.add( "NORMAL", 0 ); PE_EmitterEditor-->PEE_blendType.add( "ADDITIVE", 1 ); PE_EmitterEditor-->PEE_blendType.add( "SUBTRACTIVE", 2 ); PE_EmitterEditor-->PEE_blendType.add( "PREMULTALPHA", 3 ); PEE_EmitterSelector.setFirstSelected(); PE_Window-->EditorTabBook.selectPage( 0 ); } function ParticleEditor::createParticleList( %this ) { // This function creates the list of all particles and particle emitters %emitterCount = 0; %particleCount = 0; foreach( %obj in DatablockGroup ) { if( %obj.isMemberOfClass( "ParticleEmitterData" ) ) { // Filter out emitters on the PE_UnlistedEmitters list. %unlistedFound = false; foreach( %unlisted in PE_UnlistedEmitters ) if( %unlisted.getId() == %obj.getId() ) { %unlistedFound = true; break; } if( %unlistedFound ) continue; // To prevent our default emitters from getting changed, // prevent them from populating the list. Default emitters // should only be used as a template for creating new ones. if ( %obj.getName() $= "DefaultEmitter") continue; PEE_EmitterSelector.add( %obj.getName(), %obj.getId() ); %emitterCount ++; } else if( %obj.isMemberOfClass( "ParticleData" ) ) { %unlistedFound = false; foreach( %unlisted in PE_UnlistedParticles ) if( %unlisted.getId() == %obj.getId() ) { %unlistedFound = true; break; } if( %unlistedFound ) continue; %name = %obj.getName(); %id = %obj.getId(); if ( %name $= "DefaultParticle") continue; // Add to particle dropdown selectors. PEE_EmitterParticleSelector1.add( %name, %id ); PEE_EmitterParticleSelector2.add( %name, %id ); PEE_EmitterParticleSelector3.add( %name, %id ); PEE_EmitterParticleSelector4.add( %name, %id ); %particleCount ++; } } PEE_EmitterSelector.sort(); PEE_EmitterParticleSelector1.sort(); PEE_EmitterParticleSelector2.sort(); PEE_EmitterParticleSelector3.sort(); PEE_EmitterParticleSelector4.sort(); echo( "Found" SPC %emitterCount SPC "emitters and" SPC %particleCount SPC "particles." ); } //--------------------------------------------------------------------------------------------- function ParticleEditor::openEmitterPane( %this ) { PE_Window.text = "Particle Editor - Emitters"; PE_EmitterEditor.guiSync(); ParticleEditor.activeEditor = PE_EmitterEditor; if( !PE_EmitterEditor.dirty ) PE_EmitterEditor.setEmitterNotDirty(); } //--------------------------------------------------------------------------------------------- function ParticleEditor::openParticlePane( %this ) { PE_Window.text = "Particle Editor - Particles"; PE_ParticleEditor.guiSync(); ParticleEditor.activeEditor = PE_ParticleEditor; if( !PE_ParticleEditor.dirty ) PE_ParticleEditor.setParticleNotDirty(); } //--------------------------------------------------------------------------------------------- function ParticleEditor::resetEmitterNode( %this ) { %tform = ServerConnection.getControlObject().getEyeTransform(); %vec = VectorNormalize( ServerConnection.getControlObject().getForwardVector() ); %vec = VectorScale( %vec, 4 ); %tform = setWord( %tform, 0, getWord( %tform, 0 ) + getWord( %vec, 0 ) ); %tform = setWord( %tform, 1, getWord( %tform, 1 ) + getWord( %vec, 1 ) ); %tform = setWord( %tform, 2, getWord( %tform, 2 ) + getWord( %vec, 2 ) ); if( !isObject( $ParticleEditor::emitterNode ) ) { if( !isObject( TestEmitterNodeData ) ) { datablock ParticleEmitterNodeData( TestEmitterNodeData ) { timeMultiple = 1; }; } $ParticleEditor::emitterNode = new ParticleEmitterNode() { emitter = PEE_EmitterSelector.getText(); velocity = 1; position = getWords( %tform, 0, 2 ); rotation = getWords( %tform, 3, 6 ); datablock = TestEmitterNodeData; parentGroup = MissionCleanup; }; } else { $ParticleEditor::emitterNode.setTransform( %tform ); %clientObject = $ParticleEditor::emitterNode.getClientObject(); if( isObject( %clientObject ) ) %clientObject.setTransform( %tform ); ParticleEditor.updateEmitterNode(); } } //--------------------------------------------------------------------------------------------- function ParticleEditor::updateEmitterNode( %this ) { if( isObject( $ParticleEditor::emitterNode ) ) { %id = PEE_EmitterSelector_Control-->PopUpMenu.getSelected(); %clientObject = $ParticleEditor::emitterNode.getClientObject(); if( isObject( %clientObject ) ) %clientObject.setEmitterDataBlock( %id ); } else %this.resetEmitterNode(); } //============================================================================================= // PE_TabBook. //============================================================================================= //--------------------------------------------------------------------------------------------- function PE_TabBook::onTabSelected( %this, %text, %idx ) { if( %idx == 0 ) ParticleEditor.openEmitterPane(); else ParticleEditor.openParticlePane(); }
using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using System.Reflection; using System.Diagnostics; using HtmlHelp; namespace HtmlHelpViewer { /// <summary> /// This class implements the help-about dialog /// </summary> public class AboutDlg : System.Windows.Forms.Form { private System.Windows.Forms.Label label1; private System.Windows.Forms.Label lblLibVersion; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label lblviewerVersion; private System.Windows.Forms.Label label3; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.PictureBox pictureBox2; private System.Windows.Forms.Label label4; private System.Windows.Forms.Label label5; private System.Windows.Forms.LinkLabel linkLabel1; private System.Windows.Forms.Button btnOk; HtmlHelpSystem _hlpSystem = null; private System.Windows.Forms.Button btnLoadedFiles; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; /// <summary> /// Constructor of the class /// </summary> public AboutDlg() { InitializeComponent(); btnLoadedFiles.Enabled = false; } /// <summary> /// Constructor of the class /// </summary> public AboutDlg(HtmlHelpSystem system) { _hlpSystem = system; InitializeComponent(); if(_hlpSystem != null) { if(_hlpSystem.FileList.Length > 0) btnLoadedFiles.Enabled = true; else btnLoadedFiles.Enabled = false; } else { btnLoadedFiles.Enabled = false; } } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(AboutDlg)); this.label1 = new System.Windows.Forms.Label(); this.lblLibVersion = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.lblviewerVersion = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.pictureBox2 = new System.Windows.Forms.PictureBox(); this.label4 = new System.Windows.Forms.Label(); this.label5 = new System.Windows.Forms.Label(); this.linkLabel1 = new System.Windows.Forms.LinkLabel(); this.btnOk = new System.Windows.Forms.Button(); this.btnLoadedFiles = new System.Windows.Forms.Button(); this.SuspendLayout(); // // label1 // this.label1.Location = new System.Drawing.Point(8, 16); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(128, 16); this.label1.TabIndex = 0; this.label1.Text = "HtmlHelp library version:"; this.label1.TextAlign = System.Drawing.ContentAlignment.TopRight; // // lblLibVersion // this.lblLibVersion.Location = new System.Drawing.Point(144, 16); this.lblLibVersion.Name = "lblLibVersion"; this.lblLibVersion.Size = new System.Drawing.Size(256, 16); this.lblLibVersion.TabIndex = 1; // // label2 // this.label2.Location = new System.Drawing.Point(8, 40); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(128, 16); this.label2.TabIndex = 2; this.label2.Text = "Viewer version:"; this.label2.TextAlign = System.Drawing.ContentAlignment.TopRight; // // lblviewerVersion // this.lblviewerVersion.Location = new System.Drawing.Point(144, 40); this.lblviewerVersion.Name = "lblviewerVersion"; this.lblviewerVersion.Size = new System.Drawing.Size(256, 16); this.lblviewerVersion.TabIndex = 3; // // label3 // this.label3.Location = new System.Drawing.Point(16, 72); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(376, 32); this.label3.TabIndex = 4; this.label3.Text = "You can freely reuse the library or parts of its code in non commercial applicati" + "ons. "; this.label3.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // pictureBox1 // this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.Location = new System.Drawing.Point(8, 64); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(392, 2); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox1.TabIndex = 5; this.pictureBox1.TabStop = false; // // pictureBox2 // this.pictureBox2.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox2.Image"))); this.pictureBox2.Location = new System.Drawing.Point(8, 168); this.pictureBox2.Name = "pictureBox2"; this.pictureBox2.Size = new System.Drawing.Size(392, 2); this.pictureBox2.SizeMode = System.Windows.Forms.PictureBoxSizeMode.StretchImage; this.pictureBox2.TabIndex = 6; this.pictureBox2.TabStop = false; // // label4 // this.label4.Location = new System.Drawing.Point(16, 112); this.label4.Name = "label4"; this.label4.Size = new System.Drawing.Size(376, 16); this.label4.TabIndex = 7; this.label4.Text = "Copyright (c) 2004 by Klaus Weisser"; this.label4.TextAlign = System.Drawing.ContentAlignment.TopCenter; // // label5 // this.label5.Location = new System.Drawing.Point(77, 136); this.label5.Name = "label5"; this.label5.Size = new System.Drawing.Size(96, 23); this.label5.TabIndex = 8; this.label5.Text = "Special thanks to:"; // // linkLabel1 // this.linkLabel1.Location = new System.Drawing.Point(173, 136); this.linkLabel1.Name = "linkLabel1"; this.linkLabel1.Size = new System.Drawing.Size(160, 23); this.linkLabel1.TabIndex = 9; this.linkLabel1.TabStop = true; this.linkLabel1.Text = "Pabs\' CHM specification page"; this.linkLabel1.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabel1_LinkClicked); // // btnOk // this.btnOk.DialogResult = System.Windows.Forms.DialogResult.OK; this.btnOk.Location = new System.Drawing.Point(272, 184); this.btnOk.Name = "btnOk"; this.btnOk.Size = new System.Drawing.Size(128, 23); this.btnOk.TabIndex = 10; this.btnOk.Text = "&OK"; // // btnLoadedFiles // this.btnLoadedFiles.Location = new System.Drawing.Point(8, 184); this.btnLoadedFiles.Name = "btnLoadedFiles"; this.btnLoadedFiles.Size = new System.Drawing.Size(152, 23); this.btnLoadedFiles.TabIndex = 11; this.btnLoadedFiles.Text = "File info of loaded files..."; this.btnLoadedFiles.Click += new System.EventHandler(this.btnLoadedFiles_Click); // // AboutDlg // this.AcceptButton = this.btnOk; this.AutoScaleBaseSize = new System.Drawing.Size(5, 13); this.ClientSize = new System.Drawing.Size(410, 213); this.Controls.Add(this.btnLoadedFiles); this.Controls.Add(this.btnOk); this.Controls.Add(this.linkLabel1); this.Controls.Add(this.label5); this.Controls.Add(this.label4); this.Controls.Add(this.pictureBox2); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.label3); this.Controls.Add(this.lblviewerVersion); this.Controls.Add(this.label2); this.Controls.Add(this.lblLibVersion); this.Controls.Add(this.label1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedDialog; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.MinimizeBox = false; this.Name = "AboutDlg"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "About ..."; this.Load += new System.EventHandler(this.AboutDlg_Load); this.ResumeLayout(false); } #endregion /// <summary> /// Called if the form is loaded /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void AboutDlg_Load(object sender, System.EventArgs e) { AssemblyName libName = typeof(HtmlHelpSystem).Assembly.GetName(); lblLibVersion.Text = libName.Version.Major + "." + libName.Version.Minor + "." + libName.Version.Build + " (Rev: " + libName.Version.Revision + ") - Technology Preview"; libName = this.GetType().Assembly.GetName(); lblviewerVersion.Text = libName.Version.Major + "." + libName.Version.Minor + "." + libName.Version.Build + " (Rev: " + libName.Version.Revision + ") - Technology Preview"; } /// <summary> /// Called if the user clicks the link label /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void linkLabel1_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { BrowseUrlWithShellWebBrowser( "http://bonedaddy.net/pabs3/chmspec/0.1.2" ); } /// <summary> /// Browse an url with the default shell browser /// </summary> /// <param name="url">url to browse</param> /// <returns>true if succeeded</returns> private bool BrowseUrlWithShellWebBrowser(string url) { if (url == null || url.Length == 0) { return false; } Process process = new Process(); process.StartInfo.FileName = url; process.StartInfo.Verb = "open"; process.StartInfo.UseShellExecute = true; bool bRet = false; try { bRet = process.Start(); } catch (Exception e) { Debug.WriteLine("AboutDlg.BrowseUrlWithShellWebBrowser() - Failed with error: " + e.Message); } return bRet; } /// <summary> /// Called if the user clicks on the loaded files button /// </summary> /// <param name="sender">sender of the event</param> /// <param name="e">event parameter</param> private void btnLoadedFiles_Click(object sender, System.EventArgs e) { FileInfo fiDlg = new FileInfo(_hlpSystem); fiDlg.ShowDialog(); } } }
using System; using System.Collections.Generic; using System.Reflection; using AutoMapper; using BellRichM.Api.Models; using BellRichM.Helpers.Test; using BellRichM.Logging; using BellRichM.Service.Data; using BellRichM.Weather.Api.Controllers; using BellRichM.Weather.Api.Data; using BellRichM.Weather.Api.Filters; using BellRichM.Weather.Api.Models; using BellRichM.Weather.Api.Services; using FluentAssertions; using Machine.Specifications; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Moq; using IT = Moq.It; using It = Machine.Specifications.It; namespace BellRichM.Weather.Api.Test.Controllers { internal abstract class ConditionControllerSpecs { protected const string ErrorCode = "errorCode"; protected const string ErrorMessage = "errorMessage"; protected static LoggingData loggingData; protected static ConditionsController conditionsController; protected static Mock<ILoggerAdapter<ConditionsController>> loggerMock; protected static Mock<IMapper> mapperMock; protected static Mock<IConditionService> conditionServiceMock; protected static int offset; protected static int limit; protected static ConditionPageModel conditionPageModel; Establish context = () => { // default to no logging loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData>(), ErrorLoggingMessages = new List<string>() }; loggerMock = new Mock<ILoggerAdapter<ConditionsController>>(); mapperMock = new Mock<IMapper>(); conditionServiceMock = new Mock<IConditionService>(); offset = 0; limit = 3; var conditionModels = new List<ConditionModel> { new ConditionModel { Year = 2018, Month = 9, Day = 1, Hour = 1, WindGustDirection = 61.8725771445071, WindGust = 4.00000994196379, WindDirection = 59.8725771445071, WindSpeed = 2.00000994196379, OutsideTemperature = 67.2, HeatIndex = 65.6, Windchill = 83.0, DewPoint = 60.8725771445071, Barometer = 29.694, RainRate = 0.0, Rain = 4.00000994196379, OutsideHumidity = 29.687 } }; var conditions = new List<Condition> { new Condition { Year = 2018, Month = 9, Day = 1, Hour = 1, WindGustDirection = 61.8725771445071, WindGust = 4.00000994196379, WindDirection = 59.8725771445071, WindSpeed = 2.00000994196379, OutsideTemperature = 67.2, HeatIndex = 65.6, Windchill = 83.0, DewPoint = 60.8725771445071, Barometer = 29.694, RainRate = 0.0, Rain = 4.00000994196379, OutsideHumidity = 29.687 } }; var paging = new Paging { Offset = offset, Limit = limit, TotalCount = 1 }; var conditionPage = new ConditionPage { Paging = paging, Conditions = conditions }; var pagingModel = new PagingModel { Offset = offset, Limit = limit, TotalCount = 1 }; conditionPageModel = new ConditionPageModel { Paging = pagingModel, Conditions = conditionModels }; mapperMock.Setup(x => x.Map<ConditionPageModel>(conditionPage)).Returns(conditionPageModel); conditionServiceMock.Setup(x => x.GetConditionsByDay(offset, limit, IT.IsAny<TimePeriodModel>())).ReturnsAsync(conditionPage); conditionsController = new ConditionsController(loggerMock.Object, mapperMock.Object, conditionServiceMock.Object); conditionsController.ControllerContext.HttpContext = new DefaultHttpContext(); conditionsController.ControllerContext.HttpContext.TraceIdentifier = "traceIdentifier"; }; Cleanup after = () => conditionsController.Dispose(); } internal class When_GetConditionsByDay_decorating_method : ConditionControllerSpecs { private static MethodInfo methodInfo; Because of = () => methodInfo = typeof(ConditionsController).GetMethod("GetConditionsByDay"); It should_have_ValidateConditionLimitAttribute_attribute = () => methodInfo.Should().BeDecoratedWith<ValidateConditionLimitAttribute>(); } internal class When_GetConditionsByDay_model_state_is_not_valid : ConditionControllerSpecs { private static ObjectResult result; Establish context = () => { loggingData = new LoggingData { InformationTimes = 1, EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ConditionsController_GetConditionsByDay, "{@startDateTime} {@endDateTime} {@offset} {@limit} {@timePeriod}") }, ErrorLoggingMessages = new List<string>() }; conditionsController.ModelState.AddModelError(ErrorCode, ErrorMessage); }; Behaves_like<LoggingBehaviors<ConditionsController>> correct_logging = () => { }; Cleanup after = () => conditionsController.ModelState.Clear(); Because of = () => result = (ObjectResult)conditionsController.GetConditionsByDay(0, 0, offset, limit).Await(); It should_return_correct_result_type = () => result.Should().BeOfType<BadRequestObjectResult>(); It should_return_correct_status_code = () => result.StatusCode.ShouldEqual(400); It should_return_a_ErrorResponseModel = () => result.Value.Should().BeOfType<ErrorResponseModel>(); } internal class When_GetConditionsByDay_is_successful : ConditionControllerSpecs { private static ObjectResult result; Establish context = () => { loggingData = new LoggingData { EventLoggingData = new List<EventLoggingData> { new EventLoggingData( EventId.ConditionsController_GetConditionsByDay, "{@startDateTime} {@endDateTime} {@offset} {@limit} {@timePeriod}") }, ErrorLoggingMessages = new List<string>() }; }; Because of = () => result = (ObjectResult)conditionsController.GetConditionsByDay(0, 0, offset, limit).Await(); Behaves_like<LoggingBehaviors<ConditionsController>> correct_logging = () => { }; It should_return_success_status_code = () => result.StatusCode.ShouldEqual(200); It should_return_a_conditionPageModel = () => result.Value.ShouldNotBeNull(); It should_return_an_object_of_type_ConditionPageModel = () => result.Value.Should().BeOfType<ConditionPageModel>(); It should_return_the_conditionPageModel = () => { var conditionPage = (ConditionPageModel)result.Value; conditionPage.Should().Equals(conditionPageModel); }; } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.IO; using System.Runtime.InteropServices; using Microsoft.Protocols.TestTools.StackSdk; using Microsoft.Protocols.TestTools.StackSdk.Messages; namespace Microsoft.Protocols.TestTools.StackSdk.FileAccessService.Cifs { /// <summary> /// Packets for SmbLockingAndx Request /// </summary> public class SmbLockingAndxRequestPacket : SmbBatchedRequestPacket { #region Fields private SMB_COM_LOCKING_ANDX_Request_SMB_Parameters smbParameters; private SMB_COM_LOCKING_ANDX_Request_SMB_Data smbData; #endregion #region Properties /// <summary> /// get or set the Smb_Parameters:SMB_COM_LOCKING_ANDX_Request_SMB_Parameters /// </summary> public SMB_COM_LOCKING_ANDX_Request_SMB_Parameters SmbParameters { get { return this.smbParameters; } set { this.smbParameters = value; } } /// <summary> /// get or set the Smb_Data:SMB_COM_LOCKING_ANDX_Request_SMB_Data /// </summary> public SMB_COM_LOCKING_ANDX_Request_SMB_Data SmbData { get { return this.smbData; } set { this.smbData = value; } } /// <summary> /// the SmbCommand of the andx packet. /// </summary> protected override SmbCommand AndxCommand { get { return this.SmbParameters.AndXCommand; } } /// <summary> /// Set the AndXOffset from batched request /// </summary> protected override ushort AndXOffset { get { return this.smbParameters.AndXOffset; } set { this.smbParameters.AndXOffset = value; } } #endregion #region Constructor /// <summary> /// Constructor. /// </summary> public SmbLockingAndxRequestPacket() : base() { this.InitDefaultValue(); } /// <summary> /// Constructor: Create a request directly from a buffer. /// </summary> public SmbLockingAndxRequestPacket(byte[] data) : base(data) { } /// <summary> /// Deep copy constructor. /// </summary> public SmbLockingAndxRequestPacket(SmbLockingAndxRequestPacket packet) : base(packet) { this.InitDefaultValue(); this.smbParameters.WordCount = packet.SmbParameters.WordCount; this.smbParameters.AndXCommand = packet.SmbParameters.AndXCommand; this.smbParameters.AndXReserved = packet.SmbParameters.AndXReserved; this.smbParameters.AndXOffset = packet.SmbParameters.AndXOffset; this.smbParameters.FID = packet.SmbParameters.FID; this.smbParameters.TypeOfLock = packet.SmbParameters.TypeOfLock; this.smbParameters.NewOplockLevel = packet.SmbParameters.NewOplockLevel; this.smbParameters.Timeout = packet.SmbParameters.Timeout; this.smbParameters.NumberOfRequestedUnlocks = packet.SmbParameters.NumberOfRequestedUnlocks; this.smbParameters.NumberOfRequestedLocks = packet.SmbParameters.NumberOfRequestedLocks; this.smbData.ByteCount = packet.SmbData.ByteCount; if (packet.smbData.Unlocks != null) { this.smbData.Unlocks = new Object[packet.smbData.Unlocks.Length]; for (int i = 0; i < packet.smbData.Unlocks.Length; i++) { this.smbData.Unlocks[i] = packet.smbData.Unlocks[i]; } } if (packet.smbData.Locks != null) { this.smbData.Locks = new Object[packet.smbData.Locks.Length]; for (int i = 0; i < packet.smbData.Locks.Length; i++) { this.smbData.Locks[i] = packet.smbData.Locks[i]; } } } #endregion #region override methods /// <summary> /// to create an instance of the StackPacket class that is identical to the current StackPacket. /// </summary> /// <returns>a new Packet cloned from this.</returns> public override StackPacket Clone() { return new SmbLockingAndxRequestPacket(this); } /// <summary> /// Encode the struct of SMB_COM_LOCKING_ANDX_Request_SMB_Parameters into the struct of SmbParameters /// </summary> protected override void EncodeParameters() { this.smbParametersBlock = TypeMarshal.ToStruct<SmbParameters>( CifsMessageUtils.ToBytes<SMB_COM_LOCKING_ANDX_Request_SMB_Parameters>(this.smbParameters)); } /// <summary> /// Encode the struct of SMB_COM_LOCKING_ANDX_Request_SMB_Data into the struct of SmbData /// </summary> protected override void EncodeData() { this.smbDataBlock.ByteCount = this.SmbData.ByteCount; this.smbDataBlock.Bytes = new byte[this.smbDataBlock.ByteCount]; bool largeFiles = (this.smbParameters.TypeOfLock & LockingAndxTypeOfLock.LARGE_FILES) == LockingAndxTypeOfLock.LARGE_FILES; using (MemoryStream memoryStream = new MemoryStream(this.smbDataBlock.Bytes)) { using (Channel channel = new Channel(null, memoryStream)) { channel.BeginWriteGroup(); if (this.smbData.Unlocks != null) { foreach (object unlocking in this.smbData.Unlocks) { if (largeFiles) { channel.Write((LOCKING_ANDX_RANGE64)unlocking); } else { channel.Write((LOCKING_ANDX_RANGE32)unlocking); } } } if (this.smbData.Locks != null) { foreach (object locking in this.smbData.Locks) { if (largeFiles) { channel.Write((LOCKING_ANDX_RANGE64)locking); } else { channel.Write((LOCKING_ANDX_RANGE32)locking); } } } channel.EndWriteGroup(); } } } /// <summary> /// to decode the smb parameters: from the general SmbParameters to the concrete Smb Parameters. /// </summary> protected override void DecodeParameters() { this.smbParameters = TypeMarshal.ToStruct<SMB_COM_LOCKING_ANDX_Request_SMB_Parameters>( TypeMarshal.ToBytes(this.smbParametersBlock)); } /// <summary> /// to decode the smb data: from the general SmbDada to the concrete Smb Data. /// </summary> protected override void DecodeData() { using (MemoryStream memoryStream = new MemoryStream(CifsMessageUtils.ToBytes<SmbData>(this.smbDataBlock))) { using (Channel channel = new Channel(null, memoryStream)) { this.smbData.ByteCount = channel.Read<ushort>(); if ((this.smbParameters.TypeOfLock & LockingAndxTypeOfLock.LARGE_FILES) == LockingAndxTypeOfLock.LARGE_FILES) { this.smbData.Unlocks = new object[this.smbParameters.NumberOfRequestedUnlocks]; for (int i = 0; i < this.smbParameters.NumberOfRequestedUnlocks; i++) { this.smbData.Unlocks[i] = channel.Read<LOCKING_ANDX_RANGE64>(); } this.smbData.Locks = new object[this.smbParameters.NumberOfRequestedLocks]; for (int i = 0; i < this.smbParameters.NumberOfRequestedLocks; i++) { this.smbData.Locks[i] = channel.Read<LOCKING_ANDX_RANGE64>(); } } else { this.smbData.Unlocks = new object[this.smbParameters.NumberOfRequestedUnlocks]; for (int i = 0; i < this.smbParameters.NumberOfRequestedUnlocks; i++) { this.smbData.Unlocks[i] = channel.Read<LOCKING_ANDX_RANGE32>(); } this.smbData.Locks = new object[this.smbParameters.NumberOfRequestedLocks]; for (int i = 0; i < this.smbParameters.NumberOfRequestedLocks; i++) { this.smbData.Locks[i] = channel.Read<LOCKING_ANDX_RANGE32>(); } } } } } #endregion #region initialize fields with default value /// <summary> /// init packet, set default field data /// </summary> private void InitDefaultValue() { } #endregion } }