context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.Collections.Generic; using System.Linq; using DotVVM.Framework.Compilation.Parser; using DotVVM.Framework.Compilation.Parser.Dothtml.Tokenizer; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Diagnostics; namespace DotVVM.Framework.Tests.Parser.Dothtml { [TestClass] public class DothtmlTokenizerHtmlSpecialElementsTests : DothtmlTokenizerTestsBase { [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid() { var input = @"test <!DOCTYPE html> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid_Begin() { var input = @"<!DOCTYPE html> test"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid_End() { var input = @"test <!DOCTYPE html>"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Valid_Empty() { var input = @"<!DOCTYPE>"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual("", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Invalid_Incomplete_WithValue() { var input = @"<!DOCTYPE html"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.AreEqual(" html", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_DoctypeParsing_Invalid_Incomplete_NoValue() { var input = @"<!DOCTYPE"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("<!DOCTYPE", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenDoctype, tokenizer.Tokens[i++].Type); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.AreEqual(DothtmlTokenType.DoctypeBody, tokenizer.Tokens[i++].Type); Assert.IsTrue(tokenizer.Tokens[i].HasError); Assert.AreEqual(0, tokenizer.Tokens[i].Length); Assert.AreEqual(DothtmlTokenType.CloseDoctype, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_XmlProcessingInstructionParsing_Valid() { var input = @"test <?xml version=""1.0"" encoding=""utf-8"" ?> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<?", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenXmlProcessingInstruction, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"xml version=""1.0"" encoding=""utf-8"" ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.XmlProcessingInstructionBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("?>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseXmlProcessingInstruction, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_CDataParsing_Valid() { var input = @"test <![CDATA[ this is a text < > "" ' ]]> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<![CDATA[", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenCData, tokenizer.Tokens[i++].Type); Assert.AreEqual(@" this is a text < > "" ' ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CDataBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("]]>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseCData, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_CommentParsing_Valid() { var input = @"test <!-- this is a text < > "" ' --> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!--", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(@" this is a text < > "" ' ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("-->", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_CommentParsing_Valid_2() { var input = @"test <!--<a href=""test1"">test2</a>--> test3 <img />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<!--", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"<a href=""test1"">test2</a>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("-->", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test3 ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual("img", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(" ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual("/", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Slash, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_ServerCommentParsing_Valid() { var input = @"test <%-- this is a text < > "" ' --%> test2"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<%--", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(@" this is a text < > "" ' ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("--%>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test2", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_ServerCommentParsing_Valid_2() { var input = @"test <%--<a href=""test1"">test2</a>--%> test3 <img />"; // parse var tokenizer = new DothtmlTokenizer(); tokenizer.Tokenize(input); CheckForErrors(tokenizer, input.Length); // first line var i = 0; Assert.AreEqual("test ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<%--", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(@"<a href=""test1"">test2</a>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokenizer.Tokens[i++].Type); Assert.AreEqual("--%>", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokenizer.Tokens[i++].Type); Assert.AreEqual(" test3 ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual("<", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.OpenTag, tokenizer.Tokens[i++].Type); Assert.AreEqual("img", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Text, tokenizer.Tokens[i++].Type); Assert.AreEqual(" ", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokenizer.Tokens[i++].Type); Assert.AreEqual("/", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.Slash, tokenizer.Tokens[i++].Type); Assert.AreEqual(">", tokenizer.Tokens[i].Text); Assert.AreEqual(DothtmlTokenType.CloseTag, tokenizer.Tokens[i++].Type); } [TestMethod] public void DothtmlTokenizer_CommentInsideElement() { var input = "<a <!-- comment --> href='so'>"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.OpenTag, tokens[0].Type); Assert.AreEqual(@"<", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[1].Type); Assert.AreEqual(@"a", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[2].Type); Assert.AreEqual(@" ", tokens[2].Text); Assert.AreEqual(DothtmlTokenType.OpenComment, tokens[3].Type); Assert.AreEqual(@"<!--", tokens[3].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[4].Type); Assert.AreEqual(@" comment ", tokens[4].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[5].Type); Assert.AreEqual(@"-->", tokens[5].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[6].Type); Assert.AreEqual(@" ", tokens[6].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[7].Type); Assert.AreEqual(@"href", tokens[7].Text); Assert.AreEqual(DothtmlTokenType.Equals, tokens[8].Type); Assert.AreEqual(@"=", tokens[8].Text); Assert.AreEqual(DothtmlTokenType.SingleQuote, tokens[9].Type); Assert.AreEqual(@"'", tokens[9].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[10].Type); Assert.AreEqual(@"so", tokens[10].Text); Assert.AreEqual(DothtmlTokenType.SingleQuote, tokens[11].Type); Assert.AreEqual(@"'", tokens[11].Text); Assert.AreEqual(DothtmlTokenType.CloseTag, tokens[12].Type); Assert.AreEqual(@">", tokens[12].Text); } [TestMethod] public void DothtmlTokenizer_ServerCommentInsideElement() { var input = "<a <%-- comment --%> href=''>"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.OpenTag, tokens[0].Type); Assert.AreEqual(@"<", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[1].Type); Assert.AreEqual(@"a", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[2].Type); Assert.AreEqual(@" ", tokens[2].Text); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokens[3].Type); Assert.AreEqual(@"<%--", tokens[3].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[4].Type); Assert.AreEqual(@" comment ", tokens[4].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[5].Type); Assert.AreEqual(@"--%>", tokens[5].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[6].Type); Assert.AreEqual(@" ", tokens[6].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[7].Type); Assert.AreEqual(@"href", tokens[7].Text); Assert.AreEqual(DothtmlTokenType.Equals, tokens[8].Type); Assert.AreEqual(@"=", tokens[8].Text); Assert.AreEqual(DothtmlTokenType.SingleQuote, tokens[9].Type); Assert.AreEqual(@"'", tokens[9].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[10].Type); Assert.AreEqual(@"", tokens[10].Text); Assert.AreEqual(DothtmlTokenType.SingleQuote, tokens[11].Type); Assert.AreEqual(@"'", tokens[11].Text); Assert.AreEqual(DothtmlTokenType.CloseTag, tokens[12].Type); Assert.AreEqual(@">", tokens[12].Text); } [TestMethod] public void DothtmlTokenizer_Valid_CommentBeforeDirective() { var input = "<!-- my comment --> @viewModel TestDirective\r\nTest"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.OpenComment, tokens[0].Type); Assert.AreEqual(@"<!--", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[1].Type); Assert.AreEqual(@" my comment ", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[2].Type); Assert.AreEqual(@"-->", tokens[2].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[3].Type); Assert.AreEqual(@" ", tokens[3].Text); Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokens[4].Type); Assert.AreEqual(@"@", tokens[4].Text); Assert.AreEqual(DothtmlTokenType.DirectiveName, tokens[5].Type); Assert.AreEqual(@"viewModel", tokens[5].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[6].Type); Assert.AreEqual(@" ", tokens[6].Text); Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokens[7].Type); Assert.AreEqual(@"TestDirective", tokens[7].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[8].Type); Assert.AreEqual("\r\n", tokens[8].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[9].Type); Assert.AreEqual(@"Test", tokens[9].Text); } [TestMethod] public void DothtmlTokenizer_NestedServerComment() { var input = "<%-- my <div> <%-- <p> </p> --%> comment --%>"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokens[0].Type); Assert.AreEqual(@"<%--", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[1].Type); Assert.AreEqual(@" my <div> <%-- <p> </p> --%> comment ", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[2].Type); Assert.AreEqual(@"--%>", tokens[2].Text); } [TestMethod] public void DothtmlTokenizer_CommentWithMoreMinuses() { var input = "<!-- my comment ---> @viewModel TestDirective\r\nTest"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.OpenComment, tokens[0].Type); Assert.AreEqual(@"<!--", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[1].Type); Assert.AreEqual(@" my comment -", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[2].Type); Assert.AreEqual(@"-->", tokens[2].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[3].Type); Assert.AreEqual(@" ", tokens[3].Text); Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokens[4].Type); Assert.AreEqual(@"@", tokens[4].Text); Assert.AreEqual(DothtmlTokenType.DirectiveName, tokens[5].Type); Assert.AreEqual(@"viewModel", tokens[5].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[6].Type); Assert.AreEqual(@" ", tokens[6].Text); Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokens[7].Type); Assert.AreEqual(@"TestDirective", tokens[7].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[8].Type); Assert.AreEqual("\r\n", tokens[8].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[9].Type); Assert.AreEqual(@"Test", tokens[9].Text); } [TestMethod] public void DothtmlTokenizer_Valid_ServerCommentBeforeDirective() { var input = " <%-- my comment --%>@viewModel TestDirective\r\nTest"; var tokens = Tokenize(input); Assert.AreEqual(DothtmlTokenType.Text, tokens[0].Type); Assert.AreEqual(@" ", tokens[0].Text); Assert.AreEqual(DothtmlTokenType.OpenServerComment, tokens[1].Type); Assert.AreEqual(@"<%--", tokens[1].Text); Assert.AreEqual(DothtmlTokenType.CommentBody, tokens[2].Type); Assert.AreEqual(@" my comment ", tokens[2].Text); Assert.AreEqual(DothtmlTokenType.CloseComment, tokens[3].Type); Assert.AreEqual(@"--%>", tokens[3].Text); Assert.AreEqual(DothtmlTokenType.DirectiveStart, tokens[4].Type); Assert.AreEqual(@"@", tokens[4].Text); Assert.AreEqual(DothtmlTokenType.DirectiveName, tokens[5].Type); Assert.AreEqual(@"viewModel", tokens[5].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[6].Type); Assert.AreEqual(@" ", tokens[6].Text); Assert.AreEqual(DothtmlTokenType.DirectiveValue, tokens[7].Type); Assert.AreEqual(@"TestDirective", tokens[7].Text); Assert.AreEqual(DothtmlTokenType.WhiteSpace, tokens[8].Type); Assert.AreEqual("\r\n", tokens[8].Text); Assert.AreEqual(DothtmlTokenType.Text, tokens[9].Type); Assert.AreEqual(@"Test", tokens[9].Text); } } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.ComponentModel; using System.Diagnostics; using System.IO; using System.Linq; using System.Management.Automation; using System.Runtime.InteropServices; using System.Text; using System.Threading; using Microsoft.Azure.Commands.Common.Authentication; using Microsoft.Azure.Commands.Kubernetes.Generated; using Microsoft.Azure.Commands.Kubernetes.Models; using Microsoft.Azure.Commands.Kubernetes.Properties; using Microsoft.Azure.Commands.ResourceManager.Common.ArgumentCompleters; using Microsoft.Azure.Management.Internal.Resources.Utilities.Models; using Microsoft.WindowsAzure.Commands.Utilities.Common; #if NETSTANDARD using Microsoft.Extensions.DependencyInjection; #endif namespace Microsoft.Azure.Commands.Kubernetes { [Cmdlet("Start", KubeNounStr + "Dashboard")] [OutputType(typeof(KubeTunnelJob))] public class StartAzureRmKubernetesDashboard : KubeCmdletBase { private const string IdParameterSet = "IdParameterSet"; private const string GroupNameParameterSet = "GroupNameParameterSet"; private const string InputObjectParameterSet = "InputObjectParameterSet"; private const string ProxyUrl = "http://127.0.0.1:8001"; [Parameter(Mandatory = true, ParameterSetName = InputObjectParameterSet, ValueFromPipeline = true, HelpMessage = "A PSKubernetesCluster object, normally passed through the pipeline.", Position = 0)] [ValidateNotNullOrEmpty] public PSKubernetesCluster InputObject { get; set; } /// <summary> /// Cluster name /// </summary> [Parameter(Mandatory = true, ParameterSetName = IdParameterSet, Position = 0, ValueFromPipelineByPropertyName = true, HelpMessage = "Id of a managed Kubernetes cluster")] [ValidateNotNullOrEmpty] [Alias("ResourceId")] public string Id { get; set; } /// <summary> /// Cluster name /// </summary> [Parameter( Mandatory = true, Position = 0, ParameterSetName = GroupNameParameterSet, HelpMessage = "Name of your managed Kubernetes cluster")] [ValidateNotNullOrEmpty] public string Name { get; set; } /// <summary> /// Resource group name /// </summary> [Parameter( Position = 1, Mandatory = true, ParameterSetName = GroupNameParameterSet, HelpMessage = "Resource group name")] [ResourceGroupCompleter()] [ValidateNotNullOrEmpty] public string ResourceGroupName { get; set; } [Parameter(Mandatory = false, HelpMessage = "Do not pop open a browser after establising the kubectl port-forward.")] public SwitchParameter DisableBrowser { get; set; } [Parameter(Mandatory = false)] public SwitchParameter PassThru { get; set; } public override void ExecuteCmdlet() { base.ExecuteCmdlet(); switch (ParameterSetName) { case IdParameterSet: { var resource = new ResourceIdentifier(Id); ResourceGroupName = resource.ResourceGroupName; Name = resource.ResourceName; break; } case InputObjectParameterSet: { var resource = new ResourceIdentifier(InputObject.Id); ResourceGroupName = resource.ResourceGroupName; Name = resource.ResourceName; break; } } RunCmdLet(() => { if (!GeneralUtilities.Probe("kubectl")) throw new CmdletInvocationException(Resources.KubectlIsRequriedToBeInstalledAndOnYourPathToExecute); var tmpFileName = Path.GetTempFileName(); var encoded = Client.ManagedClusters.GetAccessProfiles(ResourceGroupName, Name, "clusterUser") .KubeConfig; AzureSession.Instance.DataStore.WriteFile( tmpFileName, Encoding.UTF8.GetString(Convert.FromBase64String(encoded))); WriteVerbose(string.Format( Resources.RunningKubectlGetPodsKubeconfigNamespaceSelector, tmpFileName)); var proc = new Process { StartInfo = new ProcessStartInfo { FileName = "kubectl", Arguments = $"get pods --kubeconfig {tmpFileName} --namespace kube-system --output name --selector k8s-app=kubernetes-dashboard", UseShellExecute = false, RedirectStandardOutput = true, CreateNoWindow = true } }; proc.Start(); var dashPodName = proc.StandardOutput.ReadToEnd(); proc.WaitForExit(); // remove "pods/" dashPodName = dashPodName.Substring(5).TrimEnd('\r', '\n'); WriteVerbose(string.Format( Resources.RunningInBackgroundJobKubectlTunnel, tmpFileName, dashPodName)); var exitingJob = JobRepository.Jobs.FirstOrDefault(j => j.Name == "Kubectl-Tunnel"); if (exitingJob != null) { WriteVerbose(Resources.StoppingExistingKubectlTunnelJob); exitingJob.StopJob(); JobRepository.Remove(exitingJob); } var job = new KubeTunnelJob(tmpFileName, dashPodName); if (!DisableBrowser) { WriteVerbose(Resources.SettingUpBrowserPop); job.StartJobCompleted += (sender, evt) => { WriteVerbose(string.Format(Resources.StartingBrowser, ProxyUrl)); PopBrowser(ProxyUrl); }; } JobRepository.Add(job); job.StartJob(); WriteObject(job); }); } private void PopBrowser(string uri) { #if NETSTANDARD var browserProcess = new Process { StartInfo = new ProcessStartInfo { UseShellExecute = true, Arguments = uri } }; if (RuntimeInformation.IsOSPlatform(OSPlatform.OSX)) { WriteVerbose("Starting on OSX with open"); browserProcess.StartInfo.FileName = "open"; browserProcess.Start(); return; } else if (RuntimeInformation.IsOSPlatform(OSPlatform.Linux)) { WriteVerbose("Starting on Unix with xdg-open"); browserProcess.StartInfo.FileName = "xdg-open"; browserProcess.Start(); return; } #endif WriteVerbose(Resources.StartingOnDefault); Process.Start(uri); } } public class KubeTunnelJob : Job2 { private readonly string _credFilePath; private int _pid; private readonly string _dashPod; private string _statusMsg = "Initializing"; public KubeTunnelJob(string credFilePath, string dashPod) : base("Start-AzureRmKubernetesDashboard", "Kubectl-Tunnel") { _credFilePath = credFilePath; _dashPod = dashPod; } public override string StatusMessage => _statusMsg; public override bool HasMoreData { get; } public override string Location { get; } public int Pid => _pid; public override void StopJob() { _statusMsg = string.Format(Resources.StoppingProcessWithId, _pid); SetJobState(JobState.Stopping); try { Process.GetProcessById(_pid).Kill(); } catch (Exception) { _statusMsg = Resources.PidDoesntExistOrJobIsAlreadyDead; } SetJobState(JobState.Stopped); _statusMsg = string.Format(Resources.StoppedProcesWithId, _pid); OnStopJobCompleted(new AsyncCompletedEventArgs(null, false, _statusMsg)); } public override void StartJob() { var kubectlCmd = $"--kubeconfig {_credFilePath} --namespace kube-system port-forward {_dashPod} 8001:9090"; _statusMsg = string.Format(Resources.StartingKubectl, kubectlCmd); var process = new Process { StartInfo = new ProcessStartInfo { FileName = "kubectl", Arguments = kubectlCmd, UseShellExecute = false, RedirectStandardOutput = true, RedirectStandardError = true, CreateNoWindow = true } }; process.Start(); TestMockSupport.Delay(1500); _pid = process.Id; SetJobState(JobState.Running); _statusMsg = string.Format(Resources.StartedKubectl, kubectlCmd); OnStartJobCompleted(new AsyncCompletedEventArgs(null, false, string.Format(Resources.ProcessStartedWithId, _pid))); } public override void StartJobAsync() { StartJob(); } public override void StopJobAsync() { StopJob(); } public override void SuspendJob() { StopJob(); } public override void SuspendJobAsync() { StopJob(); } public override void ResumeJob() { StartJob(); } public override void ResumeJobAsync() { StartJob(); } public override void UnblockJob() { // noop } public override void UnblockJobAsync() { UnblockJob(); } public override void StopJob(bool force, string reason) { StopJob(); } public override void StopJobAsync(bool force, string reason) { StopJob(); } public override void SuspendJob(bool force, string reason) { StopJob(); } public override void SuspendJobAsync(bool force, string reason) { StopJob(); } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.TargetModel.ArmProcessor { public abstract class EncodingDefinition_VFP { // // +---------+-------+---+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | 3 3 2 2 | 2 2 2 | 2 | 2 | 2 | 2 2 | 1 1 1 1 | 1 1 1 1 | 1 1 9 8 | 7 | 6 | 5 | 4 | 3 2 1 0 | // | 1 0 9 8 | 7 6 5 | 4 | 3 | 2 | 1 0 | 9 8 7 6 | 5 4 3 2 | 1 0 | | | | | | // +---------+-----------+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 1 0 | Op | D | Op | Fn | Fd | 1 0 1 0 | N | Op | M | 0 | Fm | Addressing Mode 1 - Single-precision vectors (binary) // +---------+-----------+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 1 0 | Op | 0 | Op | Dn | Dd | 1 0 1 1 | 0 | Op | 0 | 0 | Dm | Addressing Mode 2 - Double-precision vectors (binary) // +---------+-----------+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 1 0 1 | D | 1 1 | Op | Fd | 1 0 1 0 | Op | 1 | M | 0 | Fm | Addressing Mode 3 - Single-precision vectors (unary) // +---------+----------------+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 1 0 1 | 0 | 1 1 | Op | Dd | 1 0 1 1 | Op | 1 | 0 | 0 | Dm | Addressing Mode 4 - Double-precision vectors (unary) // +---------+-------+---+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 0 | P | U | D | W L | Rn | Fd | 1 0 1 0 | Offset | Addressing Mode 5 - VFP load/store multiple // +---------+-------+---+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // | Cond | 1 1 0 | P | U | 0 | W L | Rn | Dd | 1 0 1 1 | Offset | Addressing Mode 5 - VFP load/store multiple // +---------+-------+---+----+---+-----+---------+---------+---------+----+----+---+---+---------+ // // 31 28 27 26 25 24 23 22 21 20 19 18 17 16 15 12 11 10 9 8 7 6 5 4 3 0 // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 1 U | 0 | 0 L | Rn | Dd | 1 0 1 1 | offset | FSTD/FLDD Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 P U | 0 | W L | Rn | Dd | 1 0 1 1 | offset | FSTMD/FLDMD Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 0 0 | 1 | 0 Dr| Rn | Rd | 1 0 1 1 | 0 | 0 | 0 | 1 | Dm | FMDRR/FMRRD Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 Dr| Dn | Rd | 1 0 1 1 | 0 | 0 | 0 | 1 | 0 | FMDLR/FMRDL Coprocessor Register Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 1 Dr| Dn | Rd | 1 0 1 1 | 0 | 0 | 0 | 1 | 0 | FMDHR/FMRDH Coprocessor Register Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 0 | Dn | Dd | 1 0 1 1 | 0 | 0 | 0 | 0 | Dm | FMACD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 0 | Dn | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FNMACD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 1 | Dn | Dd | 1 0 1 1 | 0 | 0 | 0 | 0 | Dm | FMSCD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 1 | Dn | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FNMSCD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 1 0 | Dn | Dd | 1 0 1 1 | 0 | 0 | 0 | 0 | Dm | FMULD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 1 0 | Dn | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FNMULD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 1 1 | Dn | Dd | 1 0 1 1 | 0 | 0 | 0 | 0 | Dm | FADDD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 1 1 | Dn | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FSUBD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 0 0 | Dn | Dd | 1 0 1 1 | 0 | 0 | 0 | 0 | Dm | FDIVD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 0 0 0 | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FCPYD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 0 0 0 | Dd | 1 0 1 1 | 1 | 1 | 0 | 0 | Dm | FABSD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 0 0 1 | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FNEGD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 0 0 1 | Dd | 1 0 1 1 | 1 | 1 | 0 | 0 | Dm | FSQRTD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 1 0 0 | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | Dm | FCMPD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 1 0 0 | Dd | 1 0 1 1 | 1 | 1 | 0 | 0 | Dm | FCMPED Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 1 0 1 | Dd | 1 0 1 1 | 0 | 1 | 0 | 0 | 0 | FCMPZD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 1 0 1 | Dd | 1 0 1 1 | 1 | 1 | 0 | 0 | 0 | FCMPEZD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 1 1 1 | Fd | 1 0 1 1 | 1 | 1 | 0 | 0 | Dm | FCVTSD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 1 0 0 0 | Dd | 1 0 1 1 | 0 | 1 | M | 0 | Fm | FUITOD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 1 0 0 0 | Dd | 1 0 1 1 | 1 | 1 | M | 0 | Fm | FSITOD Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 1 0 0 | Fd | 1 0 1 1 | Z | 1 | 0 | 0 | Dm | FTOUID Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 1 0 1 | Fd | 1 0 1 1 | Z | 1 | 0 | 0 | Dm | FTOSID Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // // ################################################################################ // ################################################################################ // // 31 28 27 26 25 24 23 22 21 20 19 18 17 16 15 12 11 10 9 8 7 6 5 4 3 0 // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 1 U | D | 0 L | Rn | Fd | 1 0 1 0 | offset | FSTS/FLDS Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 P U | D | W L | Rn | Fd | 1 0 1 0 | offset | FSTMS/FLDMS Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 0 0 0 | 1 | 0 Dr| Rn | Rd | 1 0 1 0 | 0 | 0 | M | 1 | Fm | FMSRR/FMRRS Coprocessor Data Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | 0 | 0 Dr| Fn | Rd | 1 0 1 0 | N | 0 | 0 | 1 | 0 | FMSR/FMRS Coprocessor Register Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 1 | 1 Dr| reg | Rd | 1 0 1 0 | 0 | 0 | 0 | 1 | 0 | FMXR/FMRX Coprocessor Register Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 1 | 1 1 | 0 0 0 1 | 1111 | 1 0 1 0 | 0 | 0 | 0 | 1 | 0 | FMSTAT Coprocessor Register Transfer // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 0 0 | Fn | Fd | 1 0 1 0 | N | 0 | M | 0 | Fm | FMACS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 0 0 | Fn | Fd | 1 0 1 0 | N | 1 | M | 0 | Fm | FNMACS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 0 1 | Fn | Fd | 1 0 1 0 | N | 0 | M | 0 | Fm | FMSCS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 0 1 | Fn | Fd | 1 0 1 0 | N | 1 | M | 0 | Fm | FNMSCS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 1 0 | Fn | Fd | 1 0 1 0 | N | 0 | M | 0 | Fm | FMULS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 1 0 | Fn | Fd | 1 0 1 0 | N | 1 | M | 0 | Fm | FNMULS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 1 1 | Fn | Fd | 1 0 1 0 | N | 0 | M | 0 | Fm | FADDS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 0 | D | 1 1 | Fn | Fd | 1 0 1 0 | N | 1 | M | 0 | Fm | FSUBS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 0 0 | Fn | Fd | 1 0 1 0 | N | 0 | M | 0 | Fm | FDIVS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 0 0 0 | Fd | 1 0 1 0 | 0 | 1 | M | 0 | Fm | FCPYS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 0 0 0 | Fd | 1 0 1 0 | 1 | 1 | M | 0 | Fm | FABSS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 0 0 1 | Fd | 1 0 1 0 | 0 | 1 | M | 0 | Fm | FNEGS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 0 0 1 | Fd | 1 0 1 0 | 1 | 1 | M | 0 | Fm | FSQRTS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 1 0 0 | Fd | 1 0 1 0 | 0 | 1 | M | 0 | Fm | FCMPS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 1 0 0 | Fd | 1 0 1 0 | 1 | 1 | M | 0 | Fm | FCMPES Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 1 0 1 | Fd | 1 0 1 0 | 0 | 1 | 0 | 0 | 0 | FCMPZS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 0 1 0 1 | Fd | 1 0 1 0 | 1 | 1 | 0 | 0 | 0 | FCMPEZS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | 0 | 1 1 | 0 1 1 1 | Dd | 1 0 1 0 | 1 | 1 | M | 0 | Fm | FCVTDS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 0 0 0 | Dd | 1 0 1 0 | 0 | 1 | M | 0 | Fm | FUITOS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 0 0 0 | Fd | 1 0 1 0 | 1 | 1 | M | 0 | Fm | FSITOS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 1 0 0 | Fd | 1 0 1 0 | Z | 1 | M | 0 | Fm | FTOUIS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // | cond | 1 1 1 0 1 | D | 1 1 | 1 1 0 1 | Fd | 1 0 1 0 | Z | 1 | M | 0 | Fm | FTOSIS Coprocessor Data Operation // +------+---------------+---+------+------------+------+-----------+---+---+---+---+----+ // // public const uint op_ConditionCodeTransfer = 0x0EF1FA10; public const uint opmask_ConditionCodeTransfer = 0x0FFFFFFF; public const uint op_SystemRegisterTransfer = 0x0EE00A10; public const uint opmask_SystemRegisterTransfer = 0x0FE00FFF; public const uint op_32bitLoRegisterTransfer = 0x0E000B10; public const uint opmask_32bitLoRegisterTransfer = 0x0FE00FFF; public const uint op_32bitHiRegisterTransfer = 0x0E200B10; public const uint opmask_32bitHiRegisterTransfer = 0x0FE00FFF; public const uint op_32bitRegisterTransfer = 0x0E000A10; public const uint opmask_32bitRegisterTransfer = 0x0FE00F7F; public const uint op_64bitRegisterTransfer = 0x0C400A10; public const uint opmask_64bitRegisterTransfer = 0x0FE00ED0; public const uint op_DataTransfer = 0x0D000A00; public const uint opmask_DataTransfer = 0x0F200E00; public const uint op_CompareToZero = 0x0EB50A40; public const uint opmask_CompareToZero = 0x0FBF0E7F; public const uint op_ConvertFloatToFloat = 0x0EB70AC0; public const uint opmask_ConvertFloatToFloat = 0x0FBF0ED0; public const uint op_UnaryDataOperation = 0x0EB00A40; public const uint opmask_UnaryDataOperation = 0x0FB00E50; public const uint op_BinaryDataOperation = 0x0E000A00; public const uint opmask_BinaryDataOperation = 0x0F000E10; public const uint op_BlockDataTransfer = 0x0C000A00; public const uint opmask_BlockDataTransfer = 0x0E000E00; //--// ////////////////////////////////////////////////////////////////////////// public const uint c_register_s0 = 0 + 32 ; // public const uint c_register_s1 = 1 + 32 ; // public const uint c_register_s2 = 2 + 32 ; // public const uint c_register_s3 = 3 + 32 ; // public const uint c_register_s4 = 4 + 32 ; // public const uint c_register_s5 = 5 + 32 ; // public const uint c_register_s6 = 6 + 32 ; // public const uint c_register_s7 = 7 + 32 ; // public const uint c_register_s8 = 8 + 32 ; // public const uint c_register_s9 = 9 + 32 ; // public const uint c_register_s10 = 10 + 32 ; // public const uint c_register_s11 = 11 + 32 ; // public const uint c_register_s12 = 12 + 32 ; // public const uint c_register_s13 = 13 + 32 ; // public const uint c_register_s14 = 14 + 32 ; // public const uint c_register_s15 = 15 + 32 ; // public const uint c_register_s16 = 16 + 32 ; // public const uint c_register_s17 = 17 + 32 ; // public const uint c_register_s18 = 18 + 32 ; // public const uint c_register_s19 = 19 + 32 ; // public const uint c_register_s20 = 20 + 32 ; // public const uint c_register_s21 = 21 + 32 ; // public const uint c_register_s22 = 22 + 32 ; // public const uint c_register_s23 = 23 + 32 ; // public const uint c_register_s24 = 24 + 32 ; // public const uint c_register_s25 = 25 + 32 ; // public const uint c_register_s26 = 26 + 32 ; // public const uint c_register_s27 = 27 + 32 ; // public const uint c_register_s28 = 28 + 32 ; // public const uint c_register_s29 = 29 + 32 ; // public const uint c_register_s30 = 30 + 32 ; // public const uint c_register_s31 = 31 + 32 ; // // public const uint c_register_d0 = 0 + 32+32 ; // public const uint c_register_d1 = 1 + 32+32 ; // public const uint c_register_d2 = 2 + 32+32 ; // public const uint c_register_d3 = 3 + 32+32 ; // public const uint c_register_d4 = 4 + 32+32 ; // public const uint c_register_d5 = 5 + 32+32 ; // public const uint c_register_d6 = 6 + 32+32 ; // public const uint c_register_d7 = 7 + 32+32 ; // public const uint c_register_d8 = 8 + 32+32 ; // public const uint c_register_d9 = 9 + 32+32 ; // public const uint c_register_d10 = 10 + 32+32 ; // public const uint c_register_d11 = 11 + 32+32 ; // public const uint c_register_d12 = 12 + 32+32 ; // public const uint c_register_d13 = 13 + 32+32 ; // public const uint c_register_d14 = 14 + 32+32 ; // public const uint c_register_d15 = 15 + 32+32 ; // // public const uint c_register_FPSID = c_systemRegister_FPSID + 32+32+16; // public const uint c_register_FPSCR = c_systemRegister_FPSCR + 32+32+16; // public const uint c_register_FPEXC = c_systemRegister_FPEXC + 32+32+16; // ////////////////////////////////////////////////////////////////////////// /////////////////////////////////////////// public const uint c_systemRegister_FPSID = 0; public const uint c_systemRegister_FPSCR = 1; public const uint c_systemRegister_FPEXC = 8; /////////////////////////////////////////// /////////////////////////////////////////// public const uint c_binaryOperation_MAC = 0x0; // Floating-point Multiply and Accumulate public const uint c_binaryOperation_NMAC = 0x1; // Floating-point Negated Multiply and Accumulate public const uint c_binaryOperation_MSC = 0x2; // Floating-point Multiply and Subtract public const uint c_binaryOperation_NMSC = 0x3; // Floating-point Negated Multiply and Subtract public const uint c_binaryOperation_MUL = 0x4; // Floating-point Multiply public const uint c_binaryOperation_NMUL = 0x5; // Floating-point Negated Multiply public const uint c_binaryOperation_ADD = 0x6; // Floating-point Addition public const uint c_binaryOperation_SUB = 0x7; // Floating-point Subtract public const uint c_binaryOperation_DIV = 0x8; // Floating-point Divide /////////////////////////////////////////// //--// /////////////////////////////////////////// public const uint c_unaryOperation_CPY = 0x00; // Floating-point Copy public const uint c_unaryOperation_ABS = 0x01; // Floating-point Absolute Value public const uint c_unaryOperation_NEG = 0x02; // Floating-point Negate public const uint c_unaryOperation_SQRT = 0x03; // Floating-point Square Root public const uint c_unaryOperation_CMP = 0x08; // Floating-point Compare public const uint c_unaryOperation_CMPE = 0x09; // Floating-point Compare (NaN Exceptions) public const uint c_unaryOperation_UITO = 0x10; // Convert Unsigned Integer to Floating-point public const uint c_unaryOperation_SITO = 0x11; // Convert Signed Integer to Floating-point public const uint c_unaryOperation_TOUI = 0x18; // Convert from Floating-point to Unsigned Integer public const uint c_unaryOperation_TOUIZ = 0x19; // Convert from Floating-point to Unsigned Integer, Round Towards Zero public const uint c_unaryOperation_TOSI = 0x1A; // Convert from Floating-point to Signed Integer public const uint c_unaryOperation_TOSIZ = 0x1B; // Convert from Floating-point to Signed Integer, Round Towards Zero /////////////////////////////////////////// //--// /////////////////////////////////////////// public const int c_fpexc_bit_EN = 30; public const int c_fpexc_bit_EX = 31; public const uint c_fpexc_EN = 1U << c_fpexc_bit_EN; public const uint c_fpexc_EX = 1U << c_fpexc_bit_EX; /////////////////////////////////////////// /////////////////////////////////////////// public const int c_fpscr_bit_IOC = 0; // Invalid Operation (Cumulative exception bit) public const int c_fpscr_bit_IOE = 8; // Invalid Operation (Trap enable bit) public const int c_fpscr_bit_DZC = 1; // Division by Zero (Cumulative exception bit) public const int c_fpscr_bit_DZE = 9; // Division by Zero (Trap enable bit) public const int c_fpscr_bit_OFC = 2; // Overflow (Cumulative exception bit) public const int c_fpscr_bit_OFE = 10; // Overflow (Trap enable bit) public const int c_fpscr_bit_UFC = 3; // Underflow (Cumulative exception bit) public const int c_fpscr_bit_UFE = 11; // Underflow (Trap enable bit) public const int c_fpscr_bit_IXC = 4; // Inexact (Cumulative exception bit) public const int c_fpscr_bit_IXE = 12; // Inexact (Trap enable bit) public const int c_fpscr_bit_IDC = 7; // Input Denormal (Cumulative exception bit) public const int c_fpscr_bit_IDE = 15; // Input Denormal (Trap enable bit) public const int c_fpscr_shift_LEN = 16; // Vector length for VFP instructions public const int c_fpscr_mask_LEN = 0x7; // public const int c_fpscr_shift_STRIDE = 20; // Vector stride for VFP instructions public const int c_fpscr_mask_STRIDE = 0x3; // public const int c_fpscr_shift_RMODE = 22; // Rounding mode control public const int c_fpscr_mask_RMODE = 0x3; // public const int c_fpscr_bit_FZ = 24; // Flush-to-zero mode control public const int c_fpscr_bit_DN = 25; // Default NaN mode control public const int c_fpscr_bit_V = 28; // Is 1 if the comparison produced an unordered result. public const int c_fpscr_bit_C = 29; // Is 1 if the comparison produced an equal, greater than or unordered result public const int c_fpscr_bit_Z = 30; // Is 1 if the comparison produced an equal result public const int c_fpscr_bit_N = 31; // Is 1 if the comparison produced a less than result public const uint c_fpscr_IOC = 1U << c_fpscr_bit_IOC; public const uint c_fpscr_IOE = 1U << c_fpscr_bit_IOE; public const uint c_fpscr_DZC = 1U << c_fpscr_bit_DZC; public const uint c_fpscr_DZE = 1U << c_fpscr_bit_DZE; public const uint c_fpscr_OFC = 1U << c_fpscr_bit_OFC; public const uint c_fpscr_OFE = 1U << c_fpscr_bit_OFE; public const uint c_fpscr_UFC = 1U << c_fpscr_bit_UFC; public const uint c_fpscr_UFE = 1U << c_fpscr_bit_UFE; public const uint c_fpscr_IXC = 1U << c_fpscr_bit_IXC; public const uint c_fpscr_IXE = 1U << c_fpscr_bit_IXE; public const uint c_fpscr_IDC = 1U << c_fpscr_bit_IDC; public const uint c_fpscr_IDE = 1U << c_fpscr_bit_IDE; public const uint c_fpscr_FZ = 1U << c_fpscr_bit_FZ; public const uint c_fpscr_DN = 1U << c_fpscr_bit_DN; public const uint c_fpscr_V = 1U << c_fpscr_bit_V; public const uint c_fpscr_C = 1U << c_fpscr_bit_C; public const uint c_fpscr_Z = 1U << c_fpscr_bit_Z; public const uint c_fpscr_N = 1U << c_fpscr_bit_N; /////////////////////////////////////////// //--// abstract public uint get_Rn( uint op ); abstract public uint set_Rn( uint val ); abstract public uint get_SysReg( uint op ); abstract public uint set_SysReg( uint val ); abstract public uint get_Fn( uint op ); abstract public uint set_Fn( uint val ); abstract public uint get_Rd( uint op ); abstract public uint set_Rd( uint val ); abstract public uint get_Fd( uint op ); abstract public uint set_Fd( uint val ); abstract public uint get_Fm( uint op ); abstract public uint set_Fm( uint val ); abstract public bool get_IsDouble( uint op ); abstract public uint set_IsDouble( bool val ); abstract public bool get_CheckNaN( uint op ); abstract public uint set_CheckNaN( bool val ); //--// abstract public uint get_BinaryOperation( uint op ); abstract public uint set_BinaryOperation( uint val ); //--// abstract public uint get_UnaryOperation( uint op ); abstract public uint set_UnaryOperation( uint val ); //-// abstract public bool get_RegisterTransfer_IsFromCoproc( uint op ); abstract public uint set_RegisterTransfer_IsFromCoproc( bool val ); //--// abstract public bool get_DataTransfer_IsLoad ( uint op ); abstract public uint set_DataTransfer_IsLoad ( bool val ); abstract public bool get_DataTransfer_ShouldWriteBack( uint op ); abstract public uint set_DataTransfer_ShouldWriteBack( bool val ); abstract public bool get_DataTransfer_IsUp ( uint op ); abstract public uint set_DataTransfer_IsUp ( bool val ); abstract public bool get_DataTransfer_IsPreIndexing ( uint op ); abstract public uint set_DataTransfer_IsPreIndexing ( bool val ); abstract public uint get_DataTransfer_Offset ( uint op ); abstract public uint set_DataTransfer_Offset ( uint val ); } }
#region S# License /****************************************************************************************** NOTICE!!! This program and source code is owned and licensed by StockSharp, LLC, www.stocksharp.com Viewing or use of this code requires your acceptance of the license agreement found at https://github.com/StockSharp/StockSharp/blob/master/LICENSE Removal of this comment is a violation of the license agreement. Project: StockSharp.Algo.Storages.Binary.Algo File: CandleBinarySerializer.cs Created: 2015, 12, 14, 1:43 PM Copyright 2010 by StockSharp, LLC *******************************************************************************************/ #endregion S# License namespace StockSharp.Algo.Storages.Binary { using System; using System.Collections.Generic; using System.IO; using System.Linq; using Ecng.Collections; using Ecng.Common; using Ecng.Serialization; using StockSharp.Messages; using StockSharp.Localization; class CandleMetaInfo : BinaryMetaInfo<CandleMetaInfo> { public CandleMetaInfo(DateTime date) : base(date) { } public override void Write(Stream stream) { base.Write(stream); stream.Write(FirstPrice); stream.Write(LastPrice); WriteFractionalVolume(stream); if (Version < MarketDataVersions.Version50) return; stream.Write(ServerOffset); if (Version < MarketDataVersions.Version53) return; WriteOffsets(stream); } public override void Read(Stream stream) { base.Read(stream); FirstPrice = stream.Read<decimal>(); LastPrice = stream.Read<decimal>(); ReadFractionalVolume(stream); if (Version < MarketDataVersions.Version50) return; ServerOffset = stream.Read<TimeSpan>(); if (Version < MarketDataVersions.Version53) return; ReadOffsets(stream); } public override void CopyFrom(CandleMetaInfo src) { base.CopyFrom(src); FirstPrice = src.FirstPrice; LastPrice = src.LastPrice; } } class CandleBinarySerializer<TCandleMessage> : BinaryMarketDataSerializer<TCandleMessage, CandleMetaInfo> where TCandleMessage : CandleMessage, new() { private readonly object _arg; public CandleBinarySerializer(SecurityId securityId, object arg) : base(securityId, 74, MarketDataVersions.Version54) { if (arg == null) throw new ArgumentNullException(nameof(arg)); _arg = arg; } protected override void OnSave(BitArrayWriter writer, IEnumerable<TCandleMessage> candles, CandleMetaInfo metaInfo) { if (metaInfo.IsEmpty()) { var firstCandle = candles.First(); metaInfo.FirstPrice = firstCandle.LowPrice; metaInfo.LastPrice = firstCandle.LowPrice; metaInfo.ServerOffset = firstCandle.OpenTime.Offset; } writer.WriteInt(candles.Count()); var allowNonOrdered = metaInfo.Version >= MarketDataVersions.Version49; var isUtc = metaInfo.Version >= MarketDataVersions.Version50; var allowDiffOffsets = metaInfo.Version >= MarketDataVersions.Version53; foreach (var candle in candles) { writer.WriteVolume(candle.TotalVolume, metaInfo, SecurityId); if (metaInfo.Version < MarketDataVersions.Version52) writer.WriteVolume(candle.RelativeVolume ?? 0, metaInfo, SecurityId); else { writer.Write(candle.RelativeVolume != null); if (candle.RelativeVolume != null) writer.WriteVolume(candle.RelativeVolume.Value, metaInfo, SecurityId); } writer.WritePrice(candle.LowPrice, metaInfo.LastPrice, metaInfo, SecurityId); metaInfo.LastPrice = candle.LowPrice; writer.WritePrice(candle.OpenPrice, metaInfo.LastPrice, metaInfo, SecurityId); writer.WritePrice(candle.ClosePrice, metaInfo.LastPrice, metaInfo, SecurityId); writer.WritePrice(candle.HighPrice, metaInfo.LastPrice, metaInfo, SecurityId); var lastOffset = metaInfo.LastServerOffset; metaInfo.LastTime = writer.WriteTime(candle.OpenTime, metaInfo.LastTime, LocalizedStrings.Str998, allowNonOrdered, isUtc, metaInfo.ServerOffset, allowDiffOffsets, ref lastOffset); metaInfo.LastServerOffset = lastOffset; if (metaInfo.Version >= MarketDataVersions.Version46) { var isAll = !candle.HighTime.IsDefault() && !candle.LowTime.IsDefault(); DateTimeOffset first; DateTimeOffset second; writer.Write(isAll); if (isAll) { var isOrdered = candle.HighTime <= candle.LowTime; writer.Write(isOrdered); first = isOrdered ? candle.HighTime : candle.LowTime; second = isOrdered ? candle.LowTime : candle.HighTime; } else { writer.Write(!candle.HighTime.IsDefault()); writer.Write(!candle.LowTime.IsDefault()); if (candle.HighTime.IsDefault()) { first = candle.LowTime; second = default(DateTimeOffset); } else { first = candle.HighTime; second = default(DateTimeOffset); } } if (!first.IsDefault()) { if (first.Offset != lastOffset) throw new ArgumentException(LocalizedStrings.WrongTimeOffset.Put(first, lastOffset)); metaInfo.LastTime = writer.WriteTime(first, metaInfo.LastTime, LocalizedStrings.Str999, allowNonOrdered, isUtc, metaInfo.ServerOffset, allowDiffOffsets, ref lastOffset); } if (!second.IsDefault()) { if (second.Offset != lastOffset) throw new ArgumentException(LocalizedStrings.WrongTimeOffset.Put(second, lastOffset)); metaInfo.LastTime = writer.WriteTime(second, metaInfo.LastTime, LocalizedStrings.Str1000, allowNonOrdered, isUtc, metaInfo.ServerOffset, allowDiffOffsets, ref lastOffset); } } if (metaInfo.Version >= MarketDataVersions.Version47) { writer.Write(!candle.CloseTime.IsDefault()); if (!candle.CloseTime.IsDefault()) { if (candle.CloseTime.Offset != lastOffset) throw new ArgumentException(LocalizedStrings.WrongTimeOffset.Put(candle.CloseTime, lastOffset)); metaInfo.LastTime = writer.WriteTime(candle.CloseTime, metaInfo.LastTime, LocalizedStrings.Str1001, allowNonOrdered, isUtc, metaInfo.ServerOffset, allowDiffOffsets, ref lastOffset); } } else { var time = writer.WriteTime(candle.CloseTime, metaInfo.LastTime, LocalizedStrings.Str1001, allowNonOrdered, isUtc, metaInfo.ServerOffset, allowDiffOffsets, ref lastOffset); if (metaInfo.Version >= MarketDataVersions.Version41) metaInfo.LastTime = time; } if (metaInfo.Version >= MarketDataVersions.Version46) { if (metaInfo.Version < MarketDataVersions.Version51) { writer.WriteVolume(candle.OpenVolume ?? 0m, metaInfo, SecurityId); writer.WriteVolume(candle.HighVolume ?? 0m, metaInfo, SecurityId); writer.WriteVolume(candle.LowVolume ?? 0m, metaInfo, SecurityId); writer.WriteVolume(candle.CloseVolume ?? 0m, metaInfo, SecurityId); } else { if (candle.OpenVolume == null) writer.Write(false); else { writer.Write(true); writer.WriteVolume(candle.OpenVolume.Value, metaInfo, SecurityId); } if (candle.HighVolume == null) writer.Write(false); else { writer.Write(true); writer.WriteVolume(candle.HighVolume.Value, metaInfo, SecurityId); } if (candle.LowVolume == null) writer.Write(false); else { writer.Write(true); writer.WriteVolume(candle.LowVolume.Value, metaInfo, SecurityId); } if (candle.CloseVolume == null) writer.Write(false); else { writer.Write(true); writer.WriteVolume(candle.CloseVolume.Value, metaInfo, SecurityId); } } } writer.WriteInt((int)candle.State); if (metaInfo.Version < MarketDataVersions.Version45) continue; var oi = candle.OpenInterest; if (metaInfo.Version < MarketDataVersions.Version48) writer.WriteVolume(oi ?? 0m, metaInfo, SecurityId); else { writer.Write(oi != null); if (oi != null) writer.WriteVolume(oi.Value, metaInfo, SecurityId); } if (metaInfo.Version < MarketDataVersions.Version52) continue; writer.Write(candle.DownTicks != null); if (candle.DownTicks != null) writer.WriteInt(candle.DownTicks.Value); writer.Write(candle.UpTicks != null); if (candle.UpTicks != null) writer.WriteInt(candle.UpTicks.Value); writer.Write(candle.TotalTicks != null); if (candle.TotalTicks != null) writer.WriteInt(candle.TotalTicks.Value); if (metaInfo.Version < MarketDataVersions.Version54) continue; var priceLevels = candle.PriceLevels; writer.Write(priceLevels != null); if (priceLevels == null) continue; priceLevels = priceLevels.ToArray(); writer.WriteInt(priceLevels.Count()); foreach (var level in priceLevels) { writer.WritePrice(level.Price, metaInfo.LastPrice, metaInfo, SecurityId); writer.WriteInt(level.BuyCount); writer.WriteInt(level.SellCount); writer.WriteVolume(level.BuyVolume, metaInfo, SecurityId); writer.WriteVolume(level.SellVolume, metaInfo, SecurityId); var volumes = level.BuyVolumes; if (volumes == null) writer.Write(false); else { writer.Write(true); volumes = volumes.ToArray(); writer.WriteInt(volumes.Count()); foreach (var volume in volumes) { writer.WriteVolume(volume, metaInfo, SecurityId); } } volumes = level.SellVolumes; if (volumes == null) writer.Write(false); else { writer.Write(true); volumes = volumes.ToArray(); writer.WriteInt(volumes.Count()); foreach (var volume in volumes) { writer.WriteVolume(volume, metaInfo, SecurityId); } } } } } public override TCandleMessage MoveNext(MarketDataEnumerator enumerator) { var reader = enumerator.Reader; var metaInfo = enumerator.MetaInfo; var candle = new TCandleMessage { SecurityId = SecurityId, TotalVolume = reader.ReadVolume(metaInfo), RelativeVolume = metaInfo.Version < MarketDataVersions.Version52 || !reader.Read() ? (decimal?)null : reader.ReadVolume(metaInfo), LowPrice = reader.ReadPrice(metaInfo.FirstPrice, metaInfo), Arg = _arg }; candle.OpenPrice = reader.ReadPrice(candle.LowPrice, metaInfo); candle.ClosePrice = reader.ReadPrice(candle.LowPrice, metaInfo); candle.HighPrice = reader.ReadPrice(candle.LowPrice, metaInfo); var prevTime = metaInfo.FirstTime; var allowNonOrdered = metaInfo.Version >= MarketDataVersions.Version49; var isUtc = metaInfo.Version >= MarketDataVersions.Version50; var timeZone = metaInfo.GetTimeZone(isUtc, SecurityId); var allowDiffOffsets = metaInfo.Version >= MarketDataVersions.Version53; var lastOffset = metaInfo.FirstServerOffset; candle.OpenTime = reader.ReadTime(ref prevTime, allowNonOrdered, isUtc, timeZone, allowDiffOffsets, ref lastOffset); metaInfo.FirstServerOffset = lastOffset; if (metaInfo.Version >= MarketDataVersions.Version46) { if (reader.Read()) { var isOrdered = reader.Read(); var first = reader.ReadTime(ref prevTime, allowNonOrdered, isUtc, timeZone, allowDiffOffsets, ref lastOffset); var second = reader.ReadTime(ref prevTime, allowNonOrdered, isUtc, timeZone, allowDiffOffsets, ref lastOffset); candle.HighTime = isOrdered ? first : second; candle.LowTime = isOrdered ? second : first; } else { if (reader.Read()) candle.HighTime = reader.ReadTime(ref prevTime, allowNonOrdered, isUtc, timeZone, allowDiffOffsets, ref lastOffset); if (reader.Read()) candle.LowTime = reader.ReadTime(ref prevTime, allowNonOrdered, isUtc, timeZone, allowDiffOffsets, ref lastOffset); } } if (metaInfo.Version >= MarketDataVersions.Version47) { if (reader.Read()) candle.CloseTime = reader.ReadTime(ref prevTime, allowNonOrdered, isUtc, timeZone, allowDiffOffsets, ref lastOffset); } else candle.CloseTime = reader.ReadTime(ref prevTime, allowNonOrdered, isUtc, metaInfo.LocalOffset, allowDiffOffsets, ref lastOffset); if (metaInfo.Version >= MarketDataVersions.Version46) { if (metaInfo.Version < MarketDataVersions.Version51) { candle.OpenVolume = reader.ReadVolume(metaInfo); candle.HighVolume = reader.ReadVolume(metaInfo); candle.LowVolume = reader.ReadVolume(metaInfo); candle.CloseVolume = reader.ReadVolume(metaInfo); } else { candle.OpenVolume = reader.Read() ? reader.ReadVolume(metaInfo) : (decimal?)null; candle.HighVolume = reader.Read() ? reader.ReadVolume(metaInfo) : (decimal?)null; candle.LowVolume = reader.Read() ? reader.ReadVolume(metaInfo) : (decimal?)null; candle.CloseVolume = reader.Read() ? reader.ReadVolume(metaInfo) : (decimal?)null; } } candle.State = (CandleStates)reader.ReadInt(); metaInfo.FirstPrice = candle.LowPrice; metaInfo.FirstTime = metaInfo.Version <= MarketDataVersions.Version40 ? candle.OpenTime.LocalDateTime : prevTime; if (metaInfo.Version >= MarketDataVersions.Version45) { if (metaInfo.Version < MarketDataVersions.Version48 || reader.Read()) candle.OpenInterest = reader.ReadVolume(metaInfo); } if (metaInfo.Version >= MarketDataVersions.Version52) { candle.DownTicks = reader.Read() ? reader.ReadInt() : (int?)null; candle.UpTicks = reader.Read() ? reader.ReadInt() : (int?)null; candle.TotalTicks = reader.Read() ? reader.ReadInt() : (int?)null; } if (metaInfo.Version >= MarketDataVersions.Version54 && reader.Read()) { var priceLevels = new CandlePriceLevel[reader.ReadInt()]; for (var i = 0; i < priceLevels.Length; i++) { var priceLevel = new CandlePriceLevel { Price = reader.ReadPrice(candle.LowPrice, metaInfo), BuyCount = reader.ReadInt(), SellCount = reader.ReadInt(), BuyVolume = reader.ReadVolume(metaInfo), SellVolume = reader.ReadVolume(metaInfo) }; if (reader.Read()) { var volumes = new decimal[reader.ReadInt()]; for (var j = 0; j < volumes.Length; j++) volumes[j] = reader.ReadVolume(metaInfo); priceLevel.BuyVolumes = volumes; } if (reader.Read()) { var volumes = new decimal[reader.ReadInt()]; for (var j = 0; j < volumes.Length; j++) volumes[j] = reader.ReadVolume(metaInfo); priceLevel.SellVolumes = volumes; } priceLevels[i] = priceLevel; } candle.PriceLevels = priceLevels; } return candle; } } }
using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; using SuperSocket; using SuperSocket.Channel; using SuperSocket.ProtoBase; namespace SuperSocket.Server { public class SuperSocketService<TReceivePackageInfo> : IHostedService, IServer, IChannelRegister where TReceivePackageInfo : class { private readonly IServiceProvider _serviceProvider; public IServiceProvider ServiceProvider { get { return _serviceProvider; } } private readonly IOptions<ServerOptions> _serverOptions; private readonly ILoggerFactory _loggerFactory; private readonly ILogger _logger; private IPipelineFilterFactory<TReceivePackageInfo> _pipelineFilterFactory; private IChannelCreatorFactory _channelCreatorFactory; private List<IChannelCreator> _channelCreators; private IPackageHandler<TReceivePackageInfo> _packageHandler; public string Name { get; } private int _sessionCount; public int SessionCount => _sessionCount; private ISessionFactory _sessionFactory; private IMiddleware[] _middlewares; private ServerState _state = ServerState.None; public ServerState State { get { return _state; } } public SuperSocketService(IServiceProvider serviceProvider, IOptions<ServerOptions> serverOptions, ILoggerFactory loggerFactory, IChannelCreatorFactory channelCreatorFactory) { _serverOptions = serverOptions; Name = serverOptions.Value.Name; _serviceProvider = serviceProvider; _pipelineFilterFactory = GetPipelineFilterFactory(); _serverOptions = serverOptions; _loggerFactory = loggerFactory; _logger = _loggerFactory.CreateLogger("SuperSocketService"); _channelCreatorFactory = channelCreatorFactory; _packageHandler = serviceProvider.GetService<IPackageHandler<TReceivePackageInfo>>(); // initialize session factory _sessionFactory = serviceProvider.GetService<ISessionFactory>(); if (_sessionFactory == null) _sessionFactory = new DefaultSessionFactory(); InitializeMiddlewares(); } private void InitializeMiddlewares() { _middlewares = _serviceProvider.GetServices<IMiddleware>().ToArray(); } protected virtual IPipelineFilterFactory<TReceivePackageInfo> GetPipelineFilterFactory() { return _serviceProvider.GetRequiredService<IPipelineFilterFactory<TReceivePackageInfo>>(); } private bool AddChannelCreator(ListenOptions listenOptions, ServerOptions serverOptions) { var listener = _channelCreatorFactory.CreateChannelCreator<TReceivePackageInfo>(listenOptions, serverOptions, _loggerFactory, _pipelineFilterFactory); listener.NewClientAccepted += OnNewClientAccept; if (!listener.Start()) { _logger.LogError($"Failed to listen {listener}."); return false; } _channelCreators.Add(listener); return true; } private Task<bool> StartListenAsync(CancellationToken cancellationToken) { _channelCreators = new List<IChannelCreator>(); var serverOptions = _serverOptions.Value; if (serverOptions.Listeners != null && serverOptions.Listeners.Any()) { foreach (var l in serverOptions.Listeners) { if (cancellationToken.IsCancellationRequested) break; if (!AddChannelCreator(l, serverOptions)) { _logger.LogError($"Failed to listen {l}."); continue; } } } else { _logger.LogWarning("No listner was defined, so this server only can accept connections from the ActiveConnect."); if (!AddChannelCreator(null, serverOptions)) { _logger.LogError($"Failed to add the channel creator."); return Task.FromResult(false); } } return Task.FromResult(true); } protected virtual void OnNewClientAccept(IChannelCreator listener, IChannel channel) { AcceptNewChannel(channel); } private void AcceptNewChannel(IChannel channel) { var session = _sessionFactory.Create() as AppSession; InitializeSession(session, channel); HandleSession(session).DoNotAwait(); } void IChannelRegister.RegisterChannel(object connection) { var channel = _channelCreators.FirstOrDefault().CreateChannel(connection); AcceptNewChannel(channel); } private void InitializeSession(IAppSession session, IChannel channel) { session.Initialize(this, channel); var middlewares = _middlewares; if (middlewares != null && middlewares.Length > 0) { for (var i = 0; i < middlewares.Length; i++) { middlewares[i].Register(this, session); } } var packageHandler = _packageHandler; if (packageHandler != null) { if (session.Channel is IChannel<TReceivePackageInfo> packegedChannel) { packegedChannel.PackageReceived += async (ch, p) => { try { await packageHandler.Handle(session, p); } catch (Exception e) { OnSessionError(session, e); } }; } } } private async Task HandleSession(AppSession session) { Interlocked.Increment(ref _sessionCount); try { _logger.LogInformation($"A new session connected: {session.SessionID}"); session.OnSessionConnected(); await ((IAppSession)session).Channel.StartAsync(); _logger.LogInformation($"The session disconnected: {session.SessionID}"); } catch (Exception e) { _logger.LogError($"Failed to handle the session {session.SessionID}.", e); } Interlocked.Decrement(ref _sessionCount); } protected virtual void OnSessionError(IAppSession session, Exception exception) { _logger.LogError($"Session[{session.SessionID}]: session exception.", exception); } public async Task StartAsync(CancellationToken cancellationToken) { var state = _state; if (state != ServerState.None && state != ServerState.Stopped) { throw new InvalidOperationException($"The server cannot be started right now, because its state is {state}."); } _state = ServerState.Starting; await StartListenAsync(cancellationToken); _state = ServerState.Started; } public async Task StopAsync(CancellationToken cancellationToken) { var state = _state; if (state != ServerState.Started) { throw new InvalidOperationException($"The server cannot be stopped right now, because its state is {state}."); } _state = ServerState.Stopping; var tasks = _channelCreators.Where(l => l.IsRunning).Select(l => l.StopAsync()).ToArray(); await Task.WhenAll(tasks); _state = ServerState.Stopped; } async Task<bool> IServer.StartAsync() { await StartAsync(CancellationToken.None); return true; } async Task IServer.StopAsync() { await StopAsync(CancellationToken.None); } #region IDisposable Support private bool disposedValue = false; // To detect redundant calls ValueTask IAsyncDisposable.DisposeAsync() => DisposeAsync(true); protected virtual async ValueTask DisposeAsync(bool disposing) { if (!disposedValue) { if (disposing) { try { if (_state != ServerState.Started) { await StopAsync(CancellationToken.None); } } catch { } } disposedValue = true; } } void IDisposable.Dispose() { DisposeAsync(true).GetAwaiter().GetResult(); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.IO.Pipes.Tests { /// <summary> /// The Simple NamedPipe tests cover potentially every-day scenarios that are shared /// by all NamedPipes whether they be Server/Client or In/Out/Inout. /// </summary> public abstract class NamedPipeTest_Simple : NamedPipeTestBase { /// <summary> /// Yields every combination of testing options for the OneWayReadWrites test /// </summary> /// <returns></returns> public static IEnumerable<object[]> OneWayReadWritesMemberData() { var options = new[] { PipeOptions.None, PipeOptions.Asynchronous }; var bools = new[] { false, true }; foreach (PipeOptions serverOption in options) foreach (PipeOptions clientOption in options) foreach (bool asyncServerOps in bools) foreach (bool asyncClientOps in bools) yield return new object[] { serverOption, clientOption, asyncServerOps, asyncClientOps }; } [Theory] [MemberData(nameof(OneWayReadWritesMemberData))] public async Task OneWayReadWrites(PipeOptions serverOptions, PipeOptions clientOptions, bool asyncServerOps, bool asyncClientOps) { using (NamedPipePair pair = CreateNamedPipePair(serverOptions, clientOptions)) { NamedPipeClientStream client = pair.clientStream; NamedPipeServerStream server = pair.serverStream; byte[] received = new byte[] { 0 }; Task clientTask = Task.Run(async () => { if (asyncClientOps) { await client.ConnectAsync(); if (pair.writeToServer) { received = await ReadBytesAsync(client, sendBytes.Length); } else { await WriteBytesAsync(client, sendBytes); } } else { client.Connect(); if (pair.writeToServer) { received = ReadBytes(client, sendBytes.Length); } else { WriteBytes(client, sendBytes); } } }); if (asyncServerOps) { await server.WaitForConnectionAsync(); if (pair.writeToServer) { await WriteBytesAsync(server, sendBytes); } else { received = await ReadBytesAsync(server, sendBytes.Length); } } else { server.WaitForConnection(); if (pair.writeToServer) { WriteBytes(server, sendBytes); } else { received = ReadBytes(server, sendBytes.Length); } } await clientTask; Assert.Equal(sendBytes, received); server.Disconnect(); Assert.False(server.IsConnected); } } [Fact] public async Task ClonedServer_ActsAsOriginalServer() { byte[] msg1 = new byte[] { 5, 7, 9, 10 }; byte[] received1 = new byte[] { 0, 0, 0, 0 }; using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream serverBase = pair.serverStream; NamedPipeClientStream client = pair.clientStream; pair.Connect(); if (pair.writeToServer) { Task<int> clientTask = client.ReadAsync(received1, 0, received1.Length); using (NamedPipeServerStream server = new NamedPipeServerStream(PipeDirection.Out, false, true, serverBase.SafePipeHandle)) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(1, client.NumberOfServerInstances); } server.Write(msg1, 0, msg1.Length); int receivedLength = await clientTask; Assert.Equal(msg1.Length, receivedLength); Assert.Equal(msg1, received1); } } else { Task clientTask = client.WriteAsync(msg1, 0, msg1.Length); using (NamedPipeServerStream server = new NamedPipeServerStream(PipeDirection.In, false, true, serverBase.SafePipeHandle)) { int receivedLength = server.Read(received1, 0, msg1.Length); Assert.Equal(msg1.Length, receivedLength); Assert.Equal(msg1, received1); await clientTask; } } } } [Fact] public async Task ClonedClient_ActsAsOriginalClient() { byte[] msg1 = new byte[] { 5, 7, 9, 10 }; byte[] received1 = new byte[] { 0, 0, 0, 0 }; using (NamedPipePair pair = CreateNamedPipePair()) { pair.Connect(); NamedPipeServerStream server = pair.serverStream; if (pair.writeToServer) { using (NamedPipeClientStream client = new NamedPipeClientStream(PipeDirection.In, false, true, pair.clientStream.SafePipeHandle)) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) { Assert.Equal(1, client.NumberOfServerInstances); } Task<int> clientTask = client.ReadAsync(received1, 0, received1.Length); server.Write(msg1, 0, msg1.Length); int receivedLength = await clientTask; Assert.Equal(msg1.Length, receivedLength); Assert.Equal(msg1, received1); } } else { using (NamedPipeClientStream client = new NamedPipeClientStream(PipeDirection.Out, false, true, pair.clientStream.SafePipeHandle)) { Task clientTask = client.WriteAsync(msg1, 0, msg1.Length); int receivedLength = server.Read(received1, 0, msg1.Length); Assert.Equal(msg1.Length, receivedLength); Assert.Equal(msg1, received1); await clientTask; } } } } [Fact] public void ConnectOnAlreadyConnectedClient_Throws_InvalidOperationException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); Assert.True(client.IsConnected); Assert.True(server.IsConnected); Assert.Throws<InvalidOperationException>(() => client.Connect()); } } [Fact] public void WaitForConnectionOnAlreadyConnectedServer_Throws_InvalidOperationException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); Assert.True(client.IsConnected); Assert.True(server.IsConnected); Assert.Throws<InvalidOperationException>(() => server.WaitForConnection()); } } [Fact] public async Task CancelTokenOn_ServerWaitForConnectionAsync_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; var ctx = new CancellationTokenSource(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // cancellation token after the operation has been initiated { Task serverWaitTimeout = server.WaitForConnectionAsync(ctx.Token); ctx.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverWaitTimeout); } ctx.Cancel(); Assert.True(server.WaitForConnectionAsync(ctx.Token).IsCanceled); } } [Fact] [PlatformSpecific(PlatformID.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOff_ServerWaitForConnectionAsyncWithOuterCancellation_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; Task waitForConnectionTask = server.WaitForConnectionAsync(CancellationToken.None); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => waitForConnectionTask); Assert.True(waitForConnectionTask.IsCanceled); } } [Fact] [PlatformSpecific(PlatformID.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOn_ServerWaitForConnectionAsyncWithOuterCancellation_Throws_IOException() { using (NamedPipePair pair = CreateNamedPipePair()) { var cts = new CancellationTokenSource(); NamedPipeServerStream server = pair.serverStream; Task waitForConnectionTask = server.WaitForConnectionAsync(cts.Token); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAsync<IOException>(() => waitForConnectionTask); } } [Fact] public async Task OperationsOnDisconnectedServer() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; pair.Connect(); Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete); Assert.Throws<InvalidOperationException>(() => server.WaitForConnection()); await Assert.ThrowsAsync<InvalidOperationException>(() => server.WaitForConnectionAsync()); // fails because allowed connections is set to 1 server.Disconnect(); Assert.Throws<InvalidOperationException>(() => server.Disconnect()); // double disconnect byte[] buffer = new byte[] { 0, 0, 0, 0 }; if (pair.writeToServer) { Assert.Throws<InvalidOperationException>(() => server.Write(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => server.WriteByte(5)); Assert.Throws<InvalidOperationException>(() => { server.WriteAsync(buffer, 0, buffer.Length); }); } else { Assert.Throws<InvalidOperationException>(() => server.Read(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => server.ReadByte()); Assert.Throws<InvalidOperationException>(() => { server.ReadAsync(buffer, 0, buffer.Length); }); } Assert.Throws<InvalidOperationException>(() => server.Flush()); Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete); Assert.Throws<InvalidOperationException>(() => server.GetImpersonationUserName()); } } [Fact] public virtual async Task OperationsOnDisconnectedClient() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; NamedPipeClientStream client = pair.clientStream; pair.Connect(); Assert.Throws<InvalidOperationException>(() => client.IsMessageComplete); Assert.Throws<InvalidOperationException>(() => client.Connect()); await Assert.ThrowsAsync<InvalidOperationException>(() => client.ConnectAsync()); server.Disconnect(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; if (!pair.writeToServer) { if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // writes on Unix may still succeed after other end disconnects, due to socket being used { // Pipe is broken Assert.Throws<IOException>(() => client.Write(buffer, 0, buffer.Length)); Assert.Throws<IOException>(() => client.WriteByte(5)); Assert.Throws<IOException>(() => { client.WriteAsync(buffer, 0, buffer.Length); }); Assert.Throws<IOException>(() => client.Flush()); Assert.Throws<IOException>(() => client.NumberOfServerInstances); } } else { // Nothing for the client to read, but no exception throwing Assert.Equal(0, client.Read(buffer, 0, buffer.Length)); Assert.Equal(-1, client.ReadByte()); if (!RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // NumberOfServerInstances not supported on Unix { Assert.Throws<PlatformNotSupportedException>(() => client.NumberOfServerInstances); } } Assert.Throws<InvalidOperationException>(() => client.IsMessageComplete); } } [Fact] [PlatformSpecific(PlatformID.Windows)] // Unix implemented on sockets, where disposal information doesn't propagate public async Task Windows_OperationsOnNamedServerWithDisposedClient() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; pair.Connect(); pair.clientStream.Dispose(); Assert.Throws<IOException>(() => server.WaitForConnection()); await Assert.ThrowsAsync<IOException>(() => server.WaitForConnectionAsync()); Assert.Throws<IOException>(() => server.GetImpersonationUserName()); } } [Fact] [PlatformSpecific(PlatformID.AnyUnix)] public async Task Unix_OperationsOnNamedServerWithDisposedClient() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; pair.Connect(); pair.clientStream.Dispose(); // On Unix, the server still thinks that it is connected after client Disposal. Assert.Throws<InvalidOperationException>(() => server.WaitForConnection()); await Assert.ThrowsAsync<InvalidOperationException>(() => server.WaitForConnectionAsync()); Assert.NotNull(server.GetImpersonationUserName()); } } [Fact] public void OperationsOnUnconnectedServer() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; // doesn't throw exceptions PipeTransmissionMode transmitMode = server.TransmissionMode; Assert.Throws<ArgumentOutOfRangeException>(() => server.ReadMode = (PipeTransmissionMode)999); byte[] buffer = new byte[] { 0, 0, 0, 0 }; if (pair.writeToServer) { Assert.Equal(0, server.OutBufferSize); Assert.Throws<InvalidOperationException>(() => server.Write(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => server.WriteByte(5)); Assert.Throws<InvalidOperationException>(() => { server.WriteAsync(buffer, 0, buffer.Length); }); } else { Assert.Equal(0, server.InBufferSize); PipeTransmissionMode readMode = server.ReadMode; Assert.Throws<InvalidOperationException>(() => server.Read(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => server.ReadByte()); Assert.Throws<InvalidOperationException>(() => { server.ReadAsync(buffer, 0, buffer.Length); }); } Assert.Throws<InvalidOperationException>(() => server.Disconnect()); // disconnect when not connected Assert.Throws<InvalidOperationException>(() => server.IsMessageComplete); } } [Fact] public void OperationsOnUnconnectedClient() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; if (client.CanRead) { Assert.Throws<InvalidOperationException>(() => client.Read(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => client.ReadByte()); Assert.Throws<InvalidOperationException>(() => { client.ReadAsync(buffer, 0, buffer.Length); }); Assert.Throws<InvalidOperationException>(() => client.ReadMode); Assert.Throws<InvalidOperationException>(() => client.ReadMode = PipeTransmissionMode.Byte); } if (client.CanWrite) { Assert.Throws<InvalidOperationException>(() => client.Write(buffer, 0, buffer.Length)); Assert.Throws<InvalidOperationException>(() => client.WriteByte(5)); Assert.Throws<InvalidOperationException>(() => { client.WriteAsync(buffer, 0, buffer.Length); }); } Assert.Throws<InvalidOperationException>(() => client.NumberOfServerInstances); Assert.Throws<InvalidOperationException>(() => client.TransmissionMode); Assert.Throws<InvalidOperationException>(() => client.InBufferSize); Assert.Throws<InvalidOperationException>(() => client.OutBufferSize); Assert.Throws<InvalidOperationException>(() => client.SafePipeHandle); } } [Fact] public async Task DisposedServerPipe_Throws_ObjectDisposedException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream pipe = pair.serverStream; pipe.Dispose(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws<ObjectDisposedException>(() => pipe.Disconnect()); Assert.Throws<ObjectDisposedException>(() => pipe.GetImpersonationUserName()); Assert.Throws<ObjectDisposedException>(() => pipe.WaitForConnection()); await Assert.ThrowsAsync<ObjectDisposedException>(() => pipe.WaitForConnectionAsync()); } } [Fact] public async Task DisposedClientPipe_Throws_ObjectDisposedException() { using (NamedPipePair pair = CreateNamedPipePair()) { pair.Connect(); NamedPipeClientStream pipe = pair.clientStream; pipe.Dispose(); byte[] buffer = new byte[] { 0, 0, 0, 0 }; Assert.Throws<ObjectDisposedException>(() => pipe.Connect()); await Assert.ThrowsAsync<ObjectDisposedException>(() => pipe.ConnectAsync()); Assert.Throws<ObjectDisposedException>(() => pipe.NumberOfServerInstances); } } [Fact] public async Task ReadAsync_DisconnectDuringRead_Returns0() { using (NamedPipePair pair = CreateNamedPipePair()) { pair.Connect(); Task<int> readTask; if (pair.clientStream.CanRead) { readTask = pair.clientStream.ReadAsync(new byte[1], 0, 1); pair.serverStream.Dispose(); } else { readTask = pair.serverStream.ReadAsync(new byte[1], 0, 1); pair.clientStream.Dispose(); } Assert.Equal(0, await readTask); } } [PlatformSpecific(PlatformID.Windows)] // Unix named pipes are on sockets, where small writes with an empty buffer will succeed immediately [Fact] public async Task WriteAsync_DisconnectDuringWrite_Throws() { using (NamedPipePair pair = CreateNamedPipePair()) { pair.Connect(); Task writeTask; if (pair.clientStream.CanWrite) { writeTask = pair.clientStream.WriteAsync(new byte[1], 0, 1); pair.serverStream.Dispose(); } else { writeTask = pair.serverStream.WriteAsync(new byte[1], 0, 1); pair.clientStream.Dispose(); } await Assert.ThrowsAsync<IOException>(() => writeTask); } } [Fact] public async Task Server_ReadWriteCancelledToken_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (server.CanRead && client.CanWrite) { var ctx1 = new CancellationTokenSource(); Task<int> serverReadToken = server.ReadAsync(buffer, 0, buffer.Length, ctx1.Token); ctx1.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverReadToken); ctx1.Cancel(); Assert.True(server.ReadAsync(buffer, 0, buffer.Length, ctx1.Token).IsCanceled); } if (server.CanWrite) { var ctx1 = new CancellationTokenSource(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // On Unix WriteAsync's aren't cancelable once initiated { Task serverWriteToken = server.WriteAsync(buffer, 0, buffer.Length, ctx1.Token); ctx1.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverWriteToken); } ctx1.Cancel(); Assert.True(server.WriteAsync(buffer, 0, buffer.Length, ctx1.Token).IsCanceled); } } } [Fact] [PlatformSpecific(PlatformID.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOff_Server_ReadWriteCancelledToken_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (server.CanRead) { Task serverReadToken = server.ReadAsync(buffer, 0, buffer.Length, CancellationToken.None); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverReadToken); Assert.True(serverReadToken.IsCanceled); } if (server.CanWrite) { Task serverWriteToken = server.WriteAsync(buffer, 0, buffer.Length, CancellationToken.None); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverWriteToken); Assert.True(serverWriteToken.IsCanceled); } } } [Fact] [PlatformSpecific(PlatformID.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOn_Server_ReadWriteCancelledToken_Throws_IOException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeServerStream server = pair.serverStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (server.CanRead) { var cts = new CancellationTokenSource(); Task serverReadToken = server.ReadAsync(buffer, 0, buffer.Length, cts.Token); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAsync<IOException>(() => serverReadToken); } if (server.CanWrite) { var cts = new CancellationTokenSource(); Task serverWriteToken = server.WriteAsync(buffer, 0, buffer.Length, cts.Token); Assert.True(Interop.CancelIoEx(server.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAsync<IOException>(() => serverWriteToken); } } } [Fact] public async Task Client_ReadWriteCancelledToken_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (client.CanRead) { var ctx1 = new CancellationTokenSource(); Task serverReadToken = client.ReadAsync(buffer, 0, buffer.Length, ctx1.Token); ctx1.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverReadToken); Assert.True(client.ReadAsync(buffer, 0, buffer.Length, ctx1.Token).IsCanceled); } if (client.CanWrite) { var ctx1 = new CancellationTokenSource(); if (RuntimeInformation.IsOSPlatform(OSPlatform.Windows)) // On Unix WriteAsync's aren't cancelable once initiated { Task serverWriteToken = client.WriteAsync(buffer, 0, buffer.Length, ctx1.Token); ctx1.Cancel(); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => serverWriteToken); } ctx1.Cancel(); Assert.True(client.WriteAsync(buffer, 0, buffer.Length, ctx1.Token).IsCanceled); } } } [Fact] [PlatformSpecific(PlatformID.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOff_Client_ReadWriteCancelledToken_Throws_OperationCanceledException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (client.CanRead) { Task clientReadToken = client.ReadAsync(buffer, 0, buffer.Length, CancellationToken.None); Assert.True(Interop.CancelIoEx(client.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientReadToken); Assert.True(clientReadToken.IsCanceled); } if (client.CanWrite) { Task clientWriteToken = client.WriteAsync(buffer, 0, buffer.Length, CancellationToken.None); Assert.True(Interop.CancelIoEx(client.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAnyAsync<OperationCanceledException>(() => clientWriteToken); Assert.True(clientWriteToken.IsCanceled); } } } [Fact] [PlatformSpecific(PlatformID.Windows)] // P/Invoking to Win32 functions public async Task CancelTokenOn_Client_ReadWriteCancelledToken_Throws_IOException() { using (NamedPipePair pair = CreateNamedPipePair()) { NamedPipeClientStream client = pair.clientStream; byte[] buffer = new byte[] { 0, 0, 0, 0 }; pair.Connect(); if (client.CanRead) { var cts = new CancellationTokenSource(); Task clientReadToken = client.ReadAsync(buffer, 0, buffer.Length, cts.Token); Assert.True(Interop.CancelIoEx(client.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAsync<IOException>(() => clientReadToken); } if (client.CanWrite) { var cts = new CancellationTokenSource(); Task clientWriteToken = client.WriteAsync(buffer, 0, buffer.Length, cts.Token); Assert.True(Interop.CancelIoEx(client.SafePipeHandle), "Outer cancellation failed"); await Assert.ThrowsAsync<IOException>(() => clientWriteToken); } } } [Theory] [InlineData(true)] [InlineData(false)] public async Task ManyConcurrentOperations(bool cancelable) { using (NamedPipePair pair = CreateNamedPipePair(PipeOptions.Asynchronous, PipeOptions.Asynchronous)) { await Task.WhenAll(pair.serverStream.WaitForConnectionAsync(), pair.clientStream.ConnectAsync()); const int NumOps = 100; const int DataPerOp = 512; byte[] sendingData = new byte[NumOps * DataPerOp]; byte[] readingData = new byte[sendingData.Length]; new Random().NextBytes(sendingData); var cancellationToken = cancelable ? new CancellationTokenSource().Token : CancellationToken.None; Stream reader = pair.writeToServer ? (Stream)pair.clientStream : pair.serverStream; Stream writer = pair.writeToServer ? (Stream)pair.serverStream : pair.clientStream; var reads = new Task<int>[NumOps]; var writes = new Task[NumOps]; for (int i = 0; i < reads.Length; i++) reads[i] = reader.ReadAsync(readingData, i * DataPerOp, DataPerOp, cancellationToken); for (int i = 0; i < reads.Length; i++) writes[i] = writer.WriteAsync(sendingData, i * DataPerOp, DataPerOp, cancellationToken); const int WaitTimeout = 30000; Assert.True(Task.WaitAll(writes, WaitTimeout)); Assert.True(Task.WaitAll(reads, WaitTimeout)); // The data of each write may not be written atomically, and as such some of the data may be // interleaved rather than entirely in the order written. Assert.Equal(sendingData.OrderBy(b => b), readingData.OrderBy(b => b)); } } } public class NamedPipeTest_Simple_ServerInOutRead_ClientInOutWrite : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, clientOptions); ret.writeToServer = false; return ret; } } public class NamedPipeTest_Simple_ServerInOutWrite_ClientInOutRead : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.InOut, clientOptions); ret.writeToServer = true; return ret; } } public class NamedPipeTest_Simple_ServerInOut_ClientIn : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.In, clientOptions); ret.writeToServer = true; return ret; } } public class NamedPipeTest_Simple_ServerInOut_ClientOut : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.InOut, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, clientOptions); ret.writeToServer = false; return ret; } } public class NamedPipeTest_Simple_ServerOut_ClientIn : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.Out, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.In, clientOptions); ret.writeToServer = true; return ret; } } public class NamedPipeTest_Simple_ServerIn_ClientOut : NamedPipeTest_Simple { protected override NamedPipePair CreateNamedPipePair(PipeOptions serverOptions, PipeOptions clientOptions) { NamedPipePair ret = new NamedPipePair(); string pipeName = GetUniquePipeName(); ret.serverStream = new NamedPipeServerStream(pipeName, PipeDirection.In, 1, PipeTransmissionMode.Byte, serverOptions); ret.clientStream = new NamedPipeClientStream(".", pipeName, PipeDirection.Out, clientOptions); ret.writeToServer = false; return ret; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. // =+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+=+ // // ConcatQueryOperator.cs // // =-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=- using System.Collections.Generic; using System.Diagnostics.Contracts; using System.Threading; namespace System.Linq.Parallel { /// <summary> /// Concatenates one data source with another. Order preservation is used to ensure /// the output is actually a concatenation -- i.e. one after the other. The only /// special synchronization required is to find the largest index N in the first data /// source so that the indices of elements in the second data source can be offset /// by adding N+1. This makes it appear to the order preservation infrastructure as /// though all elements in the second came after all elements in the first, which is /// precisely what we want. /// </summary> /// <typeparam name="TSource"></typeparam> internal sealed class ConcatQueryOperator<TSource> : BinaryQueryOperator<TSource, TSource, TSource> { private readonly bool _prematureMergeLeft = false; // Whether to prematurely merge the left data source private readonly bool _prematureMergeRight = false; // Whether to prematurely merge the right data source //--------------------------------------------------------------------------------------- // Initializes a new concatenation operator. // // Arguments: // child - the child whose data we will reverse // internal ConcatQueryOperator(ParallelQuery<TSource> firstChild, ParallelQuery<TSource> secondChild) : base(firstChild, secondChild) { Contract.Assert(firstChild != null, "first child data source cannot be null"); Contract.Assert(secondChild != null, "second child data source cannot be null"); _outputOrdered = LeftChild.OutputOrdered || RightChild.OutputOrdered; _prematureMergeLeft = LeftChild.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); _prematureMergeRight = RightChild.OrdinalIndexState.IsWorseThan(OrdinalIndexState.Increasing); if ((LeftChild.OrdinalIndexState == OrdinalIndexState.Indexible) && (RightChild.OrdinalIndexState == OrdinalIndexState.Indexible)) { SetOrdinalIndex(OrdinalIndexState.Indexible); } else { SetOrdinalIndex( ExchangeUtilities.Worse(OrdinalIndexState.Increasing, ExchangeUtilities.Worse(LeftChild.OrdinalIndexState, RightChild.OrdinalIndexState))); } } //--------------------------------------------------------------------------------------- // Just opens the current operator, including opening the child and wrapping it with // partitions as needed. // internal override QueryResults<TSource> Open(QuerySettings settings, bool preferStriping) { // We just open the children operators. QueryResults<TSource> leftChildResults = LeftChild.Open(settings, preferStriping); QueryResults<TSource> rightChildResults = RightChild.Open(settings, preferStriping); return ConcatQueryOperatorResults.NewResults(leftChildResults, rightChildResults, this, settings, preferStriping); } public override void WrapPartitionedStream<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStream, PartitionedStream<TSource, TRightKey> rightStream, IPartitionedStreamRecipient<TSource> outputRecipient, bool preferStriping, QuerySettings settings) { // Prematurely merge the left results, if necessary if (_prematureMergeLeft) { ListQueryResults<TSource> leftStreamResults = ExecuteAndCollectResults(leftStream, leftStream.PartitionCount, LeftChild.OutputOrdered, preferStriping, settings); PartitionedStream<TSource, int> leftStreamInc = leftStreamResults.GetPartitionedStream(); WrapHelper<int, TRightKey>(leftStreamInc, rightStream, outputRecipient, settings, preferStriping); } else { Contract.Assert(!ExchangeUtilities.IsWorseThan(leftStream.OrdinalIndexState, OrdinalIndexState.Increasing)); WrapHelper<TLeftKey, TRightKey>(leftStream, rightStream, outputRecipient, settings, preferStriping); } } private void WrapHelper<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStreamInc, PartitionedStream<TSource, TRightKey> rightStream, IPartitionedStreamRecipient<TSource> outputRecipient, QuerySettings settings, bool preferStriping) { // Prematurely merge the right results, if necessary if (_prematureMergeRight) { ListQueryResults<TSource> rightStreamResults = ExecuteAndCollectResults(rightStream, leftStreamInc.PartitionCount, LeftChild.OutputOrdered, preferStriping, settings); PartitionedStream<TSource, int> rightStreamInc = rightStreamResults.GetPartitionedStream(); WrapHelper2<TLeftKey, int>(leftStreamInc, rightStreamInc, outputRecipient); } else { Contract.Assert(!ExchangeUtilities.IsWorseThan(rightStream.OrdinalIndexState, OrdinalIndexState.Increasing)); WrapHelper2<TLeftKey, TRightKey>(leftStreamInc, rightStream, outputRecipient); } } private void WrapHelper2<TLeftKey, TRightKey>( PartitionedStream<TSource, TLeftKey> leftStreamInc, PartitionedStream<TSource, TRightKey> rightStreamInc, IPartitionedStreamRecipient<TSource> outputRecipient) { int partitionCount = leftStreamInc.PartitionCount; // Generate the shared data. IComparer<ConcatKey> comparer = ConcatKey.MakeComparer( leftStreamInc.KeyComparer, rightStreamInc.KeyComparer); var outputStream = new PartitionedStream<TSource, ConcatKey>(partitionCount, comparer, OrdinalIndexState); for (int i = 0; i < partitionCount; i++) { outputStream[i] = new ConcatQueryOperatorEnumerator<TLeftKey, TRightKey>(leftStreamInc[i], rightStreamInc[i]); } outputRecipient.Receive(outputStream); } //--------------------------------------------------------------------------------------- // Returns an enumerable that represents the query executing sequentially. // internal override IEnumerable<TSource> AsSequentialQuery(CancellationToken token) { return LeftChild.AsSequentialQuery(token).Concat(RightChild.AsSequentialQuery(token)); } //--------------------------------------------------------------------------------------- // Whether this operator performs a premature merge that would not be performed in // a similar sequential operation (i.e., in LINQ to Objects). // internal override bool LimitsParallelism { get { return false; } } //--------------------------------------------------------------------------------------- // The enumerator type responsible for concatenating two data sources. // class ConcatQueryOperatorEnumerator<TLeftKey, TRightKey> : QueryOperatorEnumerator<TSource, ConcatKey> { private QueryOperatorEnumerator<TSource, TLeftKey> _firstSource; // The first data source to enumerate. private QueryOperatorEnumerator<TSource, TRightKey> _secondSource; // The second data source to enumerate. private bool _begunSecond; // Whether this partition has begun enumerating the second source yet. //--------------------------------------------------------------------------------------- // Instantiates a new select enumerator. // internal ConcatQueryOperatorEnumerator( QueryOperatorEnumerator<TSource, TLeftKey> firstSource, QueryOperatorEnumerator<TSource, TRightKey> secondSource) { Contract.Assert(firstSource != null); Contract.Assert(secondSource != null); _firstSource = firstSource; _secondSource = secondSource; } //--------------------------------------------------------------------------------------- // MoveNext advances to the next element in the output. While the first data source has // elements, this consists of just advancing through it. After this, all partitions must // synchronize at a barrier and publish the maximum index N. Finally, all partitions can // move on to the second data source, adding N+1 to indices in order to get the correct // index offset. // internal override bool MoveNext(ref TSource currentElement, ref ConcatKey currentKey) { Contract.Assert(_firstSource != null); Contract.Assert(_secondSource != null); // If we are still enumerating the first source, fetch the next item. if (!_begunSecond) { // If elements remain, just return true and continue enumerating the left. TLeftKey leftKey = default(TLeftKey); if (_firstSource.MoveNext(ref currentElement, ref leftKey)) { currentKey = ConcatKey.MakeLeft<TLeftKey, TRightKey>(leftKey); return true; } _begunSecond = true; } // Now either move on to, or continue, enumerating the right data source. TRightKey rightKey = default(TRightKey); if (_secondSource.MoveNext(ref currentElement, ref rightKey)) { currentKey = ConcatKey.MakeLeft<TLeftKey, TRightKey>(rightKey); return true; } return false; } protected override void Dispose(bool disposing) { _firstSource.Dispose(); _secondSource.Dispose(); } } //----------------------------------------------------------------------------------- // Query results for a Concat operator. The results are indexible if the child // results were indexible. // class ConcatQueryOperatorResults : BinaryQueryOperatorResults { private ConcatQueryOperator<TSource> _concatOp; // Operator that generated the results private int _leftChildCount; // The number of elements in the left child result set private int _rightChildCount; // The number of elements in the right child result set public static QueryResults<TSource> NewResults( QueryResults<TSource> leftChildQueryResults, QueryResults<TSource> rightChildQueryResults, ConcatQueryOperator<TSource> op, QuerySettings settings, bool preferStriping) { if (leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible) { return new ConcatQueryOperatorResults( leftChildQueryResults, rightChildQueryResults, op, settings, preferStriping); } else { return new BinaryQueryOperatorResults( leftChildQueryResults, rightChildQueryResults, op, settings, preferStriping); } } private ConcatQueryOperatorResults( QueryResults<TSource> leftChildQueryResults, QueryResults<TSource> rightChildQueryResults, ConcatQueryOperator<TSource> concatOp, QuerySettings settings, bool preferStriping) : base(leftChildQueryResults, rightChildQueryResults, concatOp, settings, preferStriping) { _concatOp = concatOp; Contract.Assert(leftChildQueryResults.IsIndexible && rightChildQueryResults.IsIndexible); _leftChildCount = leftChildQueryResults.ElementsCount; _rightChildCount = rightChildQueryResults.ElementsCount; } internal override bool IsIndexible { get { return true; } } internal override int ElementsCount { get { Contract.Assert(_leftChildCount >= 0 && _rightChildCount >= 0); return _leftChildCount + _rightChildCount; } } internal override TSource GetElement(int index) { if (index < _leftChildCount) { return _leftChildQueryResults.GetElement(index); } else { return _rightChildQueryResults.GetElement(index - _leftChildCount); } } } } //--------------------------------------------------------------------------------------- // ConcatKey represents an ordering key for the Concat operator. It knows whether the // element it is associated with is from the left source or the right source, and also // the elements ordering key. // internal struct ConcatKey { private readonly object _leftKey; private readonly object _rightKey; private readonly bool _isLeft; private ConcatKey(object leftKey, object rightKey, bool isLeft) { _leftKey = leftKey; _rightKey = rightKey; _isLeft = isLeft; } internal static ConcatKey MakeLeft<TLeftKey, TRightKey>(object leftKey) { return new ConcatKey(leftKey, default(TRightKey), true); } internal static ConcatKey MakeRight<TLeftKey, TRightKey>(object rightKey) { return new ConcatKey(default(TLeftKey), rightKey, false); } internal static IComparer<ConcatKey> MakeComparer<T, U>( IComparer<T> leftComparer, IComparer<U> rightComparer) { return new ConcatKeyComparer<T, U>(leftComparer, rightComparer); } //--------------------------------------------------------------------------------------- // ConcatKeyComparer compares ConcatKeys, so that elements from the left source come // before elements from the right source, and elements within each source are ordered // according to the corresponding order key. // private class ConcatKeyComparer<T, U> : IComparer<ConcatKey> { private IComparer<T> _leftComparer; private IComparer<U> _rightComparer; internal ConcatKeyComparer(IComparer<T> leftComparer, IComparer<U> rightComparer) { _leftComparer = leftComparer; _rightComparer = rightComparer; } public int Compare(ConcatKey x, ConcatKey y) { // If one element is from the left source and the other not, the element from the left source // comes earlier. if (x._isLeft != y._isLeft) { return x._isLeft ? -1 : 1; } // Elements are from the same source (left or right). Compare the corresponding keys. if (x._isLeft) { return _leftComparer.Compare((T)x._leftKey, (T)y._leftKey); } return _rightComparer.Compare((U)x._rightKey, (U)y._rightKey); } } } }
// Copyright (c) 2007-2014 SIL International // Licensed under the MIT license: opensource.org/licenses/MIT namespace SolidGui { partial class StructurePropertiesView { /// <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 Component Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this._nestedTableLayoutPanel = new System.Windows.Forms.TableLayoutPanel(); this._parentListView = new System.Windows.Forms.ListView(); this.columnHeaderMarker = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.columnHeaderOccurs = ((System.Windows.Forms.ColumnHeader)(new System.Windows.Forms.ColumnHeader())); this.summaryLabel = new System.Windows.Forms.TextBox(); this._commentsLabel = new System.Windows.Forms.TextBox(); this._commentTextBox = new System.Windows.Forms.TextBox(); this._summaryTextBox = new System.Windows.Forms.TextBox(); this._parentLabel = new System.Windows.Forms.TextBox(); this._explanationLabel = new System.Windows.Forms.TextBox(); this.flowLayoutPanelOccurs = new System.Windows.Forms.FlowLayoutPanel(); this._onceRadioButton = new System.Windows.Forms.RadioButton(); this._multipleTogetherRadioButton = new System.Windows.Forms.RadioButton(); this._multipleApartRadioButton = new System.Windows.Forms.RadioButton(); this._requiredCheckBox = new System.Windows.Forms.CheckBox(); this._InferComboBox = new System.Windows.Forms.ComboBox(); this._inferComboLabel = new System.Windows.Forms.TextBox(); this.flowLayoutPanel1 = new System.Windows.Forms.FlowLayoutPanel(); this._deleteButton = new System.Windows.Forms.Button(); this._nestedTableLayoutPanel.SuspendLayout(); this.flowLayoutPanelOccurs.SuspendLayout(); this.flowLayoutPanel1.SuspendLayout(); this.SuspendLayout(); // // _nestedTableLayoutPanel // this._nestedTableLayoutPanel.ColumnCount = 2; this._nestedTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 26.19718F)); this._nestedTableLayoutPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle(System.Windows.Forms.SizeType.Percent, 73.80282F)); this._nestedTableLayoutPanel.Controls.Add(this._parentListView, 0, 1); this._nestedTableLayoutPanel.Controls.Add(this.summaryLabel, 0, 3); this._nestedTableLayoutPanel.Controls.Add(this._commentsLabel, 0, 4); this._nestedTableLayoutPanel.Controls.Add(this._commentTextBox, 1, 4); this._nestedTableLayoutPanel.Controls.Add(this._summaryTextBox, 1, 3); this._nestedTableLayoutPanel.Controls.Add(this._parentLabel, 0, 0); this._nestedTableLayoutPanel.Controls.Add(this.flowLayoutPanelOccurs, 1, 1); this._nestedTableLayoutPanel.Controls.Add(this._InferComboBox, 1, 2); this._nestedTableLayoutPanel.Controls.Add(this._inferComboLabel, 0, 2); this._nestedTableLayoutPanel.Controls.Add(this.flowLayoutPanel1, 1, 0); this._nestedTableLayoutPanel.Dock = System.Windows.Forms.DockStyle.Fill; this._nestedTableLayoutPanel.Location = new System.Drawing.Point(0, 0); this._nestedTableLayoutPanel.Name = "_nestedTableLayoutPanel"; this._nestedTableLayoutPanel.RowCount = 5; this._nestedTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 35F)); this._nestedTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 110F)); this._nestedTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this._nestedTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 30F)); this._nestedTableLayoutPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Percent, 100F)); this._nestedTableLayoutPanel.Size = new System.Drawing.Size(355, 266); this._nestedTableLayoutPanel.TabIndex = 1; // // _parentListView // this._parentListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeaderMarker, this.columnHeaderOccurs}); this._parentListView.Dock = System.Windows.Forms.DockStyle.Fill; this._parentListView.FullRowSelect = true; this._parentListView.HideSelection = false; this._parentListView.LabelEdit = true; this._parentListView.Location = new System.Drawing.Point(3, 38); this._parentListView.MultiSelect = false; this._parentListView.Name = "_parentListView"; this._parentListView.Size = new System.Drawing.Size(86, 104); this._parentListView.TabIndex = 9; this._parentListView.UseCompatibleStateImageBehavior = false; this._parentListView.View = System.Windows.Forms.View.Details; this._parentListView.AfterLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this._parentListView_AfterLabelEdit); this._parentListView.BeforeLabelEdit += new System.Windows.Forms.LabelEditEventHandler(this._parentListView_BeforeLabelEdit); this._parentListView.SelectedIndexChanged += new System.EventHandler(this._parentListView_SelectedIndexChanged); this._parentListView.KeyUp += new System.Windows.Forms.KeyEventHandler(this._parentListView_KeyUp); this._parentListView.MouseUp += new System.Windows.Forms.MouseEventHandler(this._parentListView_MouseUp); // // columnHeaderMarker // this.columnHeaderMarker.Text = "Marker"; this.columnHeaderMarker.Width = 44; // // columnHeaderOccurs // this.columnHeaderOccurs.Text = "Occurs"; this.columnHeaderOccurs.Width = 39; // // summaryLabel // this.summaryLabel.BackColor = System.Drawing.SystemColors.ControlLightLight; this.summaryLabel.BorderStyle = System.Windows.Forms.BorderStyle.None; this.summaryLabel.Dock = System.Windows.Forms.DockStyle.Fill; this.summaryLabel.Location = new System.Drawing.Point(3, 178); this.summaryLabel.Name = "summaryLabel"; this.summaryLabel.Size = new System.Drawing.Size(86, 13); this.summaryLabel.TabIndex = 0; this.summaryLabel.TabStop = false; this.summaryLabel.Text = "Summary:"; // // _commentsLabel // this._commentsLabel.BackColor = System.Drawing.SystemColors.ControlLightLight; this._commentsLabel.BorderStyle = System.Windows.Forms.BorderStyle.None; this._commentsLabel.Location = new System.Drawing.Point(3, 208); this._commentsLabel.Name = "_commentsLabel"; this._commentsLabel.Size = new System.Drawing.Size(86, 13); this._commentsLabel.TabIndex = 0; this._commentsLabel.TabStop = false; this._commentsLabel.Text = "Comments:"; // // _commentTextBox // this._commentTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this._commentTextBox.Location = new System.Drawing.Point(95, 208); this._commentTextBox.Multiline = true; this._commentTextBox.Name = "_commentTextBox"; this._commentTextBox.Size = new System.Drawing.Size(257, 55); this._commentTextBox.TabIndex = 3; this._commentTextBox.Leave += new System.EventHandler(this.CommentTextBoxMaybeChanged); this._commentTextBox.Validated += new System.EventHandler(this.CommentTextBoxMaybeChanged); // // _summaryTextBox // this._summaryTextBox.BackColor = System.Drawing.SystemColors.ControlLightLight; this._summaryTextBox.BorderStyle = System.Windows.Forms.BorderStyle.None; this._summaryTextBox.Dock = System.Windows.Forms.DockStyle.Fill; this._summaryTextBox.Location = new System.Drawing.Point(95, 178); this._summaryTextBox.Name = "_summaryTextBox"; this._summaryTextBox.Size = new System.Drawing.Size(257, 13); this._summaryTextBox.TabIndex = 0; this._summaryTextBox.TabStop = false; this._summaryTextBox.Text = "i"; // // _parentLabel // this._parentLabel.BackColor = System.Drawing.SystemColors.ControlLightLight; this._parentLabel.BorderStyle = System.Windows.Forms.BorderStyle.None; this._parentLabel.Dock = System.Windows.Forms.DockStyle.Fill; this._parentLabel.Location = new System.Drawing.Point(3, 3); this._parentLabel.Name = "_parentLabel"; this._parentLabel.Size = new System.Drawing.Size(86, 13); this._parentLabel.TabIndex = 0; this._parentLabel.TabStop = false; this._parentLabel.Text = "Parent Marker(s):"; // // _explanationLabel // this._explanationLabel.Anchor = System.Windows.Forms.AnchorStyles.None; this._explanationLabel.BackColor = System.Drawing.SystemColors.ControlLightLight; this._explanationLabel.BorderStyle = System.Windows.Forms.BorderStyle.None; this._explanationLabel.Location = new System.Drawing.Point(38, 8); this._explanationLabel.Name = "_explanationLabel"; this._explanationLabel.Size = new System.Drawing.Size(211, 13); this._explanationLabel.TabIndex = 0; this._explanationLabel.TabStop = false; this._explanationLabel.Text = "Under {0}, {1} can occur..."; // // flowLayoutPanelOccurs // this.flowLayoutPanelOccurs.Controls.Add(this._onceRadioButton); this.flowLayoutPanelOccurs.Controls.Add(this._multipleTogetherRadioButton); this.flowLayoutPanelOccurs.Controls.Add(this._multipleApartRadioButton); this.flowLayoutPanelOccurs.Controls.Add(this._requiredCheckBox); this.flowLayoutPanelOccurs.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanelOccurs.FlowDirection = System.Windows.Forms.FlowDirection.TopDown; this.flowLayoutPanelOccurs.Location = new System.Drawing.Point(95, 38); this.flowLayoutPanelOccurs.Name = "flowLayoutPanelOccurs"; this.flowLayoutPanelOccurs.Size = new System.Drawing.Size(257, 104); this.flowLayoutPanelOccurs.TabIndex = 2; // // _onceRadioButton // this._onceRadioButton.AutoSize = true; this._onceRadioButton.Checked = true; this._onceRadioButton.Location = new System.Drawing.Point(3, 3); this._onceRadioButton.Name = "_onceRadioButton"; this._onceRadioButton.Size = new System.Drawing.Size(51, 17); this._onceRadioButton.TabIndex = 0; this._onceRadioButton.TabStop = true; this._onceRadioButton.Text = "Once"; this._onceRadioButton.UseVisualStyleBackColor = true; this._onceRadioButton.CheckedChanged += new System.EventHandler(this._radioButton_Click); // // _multipleTogetherRadioButton // this._multipleTogetherRadioButton.AutoSize = true; this._multipleTogetherRadioButton.Location = new System.Drawing.Point(3, 26); this._multipleTogetherRadioButton.Name = "_multipleTogetherRadioButton"; this._multipleTogetherRadioButton.Size = new System.Drawing.Size(250, 17); this._multipleTogetherRadioButton.TabIndex = 0; this._multipleTogetherRadioButton.Text = "One or more times \'together\' (excluding children)"; this._multipleTogetherRadioButton.UseVisualStyleBackColor = true; this._multipleTogetherRadioButton.CheckedChanged += new System.EventHandler(this._radioButton_Click); // // _multipleApartRadioButton // this._multipleApartRadioButton.AutoSize = true; this._multipleApartRadioButton.Location = new System.Drawing.Point(3, 49); this._multipleApartRadioButton.Name = "_multipleApartRadioButton"; this._multipleApartRadioButton.Size = new System.Drawing.Size(250, 17); this._multipleApartRadioButton.TabIndex = 0; this._multipleApartRadioButton.Text = "One or more times (siblings may be interspersed)"; this._multipleApartRadioButton.UseVisualStyleBackColor = true; this._multipleApartRadioButton.CheckedChanged += new System.EventHandler(this._radioButton_Click); // // _requiredCheckBox // this._requiredCheckBox.AutoSize = true; this._requiredCheckBox.Location = new System.Drawing.Point(3, 72); this._requiredCheckBox.Name = "_requiredCheckBox"; this._requiredCheckBox.Size = new System.Drawing.Size(143, 17); this._requiredCheckBox.TabIndex = 1; this._requiredCheckBox.Text = "Must occur (i.e. required)"; this._requiredCheckBox.UseVisualStyleBackColor = true; this._requiredCheckBox.CheckedChanged += new System.EventHandler(this._radioButton_Click); // // _InferComboBox // this._InferComboBox.Dock = System.Windows.Forms.DockStyle.Fill; this._InferComboBox.FormattingEnabled = true; this._InferComboBox.Items.AddRange(new object[] { "Report Error"}); this._InferComboBox.Location = new System.Drawing.Point(95, 148); this._InferComboBox.Name = "_InferComboBox"; this._InferComboBox.Size = new System.Drawing.Size(257, 21); this._InferComboBox.TabIndex = 2; this._InferComboBox.SelectedIndexChanged += new System.EventHandler(this._InferComboBox_SelectedIndexChanged); // // _inferComboLabel // this._inferComboLabel.BackColor = System.Drawing.SystemColors.ControlLightLight; this._inferComboLabel.BorderStyle = System.Windows.Forms.BorderStyle.None; this._inferComboLabel.Location = new System.Drawing.Point(3, 148); this._inferComboLabel.Name = "_inferComboLabel"; this._inferComboLabel.Size = new System.Drawing.Size(86, 13); this._inferComboLabel.TabIndex = 0; this._inferComboLabel.TabStop = false; this._inferComboLabel.Text = "If no parent, then"; // // flowLayoutPanel1 // this.flowLayoutPanel1.Controls.Add(this._deleteButton); this.flowLayoutPanel1.Controls.Add(this._explanationLabel); this.flowLayoutPanel1.Dock = System.Windows.Forms.DockStyle.Fill; this.flowLayoutPanel1.Location = new System.Drawing.Point(95, 3); this.flowLayoutPanel1.Name = "flowLayoutPanel1"; this.flowLayoutPanel1.Size = new System.Drawing.Size(257, 29); this.flowLayoutPanel1.TabIndex = 10; // // _deleteButton // this._deleteButton.FlatStyle = System.Windows.Forms.FlatStyle.Flat; this._deleteButton.Location = new System.Drawing.Point(3, 4); this._deleteButton.Margin = new System.Windows.Forms.Padding(3, 4, 1, 3); this._deleteButton.Name = "_deleteButton"; this._deleteButton.Size = new System.Drawing.Size(31, 22); this._deleteButton.TabIndex = 1; this._deleteButton.Text = "&del"; this._deleteButton.UseVisualStyleBackColor = true; this._deleteButton.Click += new System.EventHandler(this._deleteButton_Click); // // StructurePropertiesView // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.SystemColors.ControlLightLight; this.Controls.Add(this._nestedTableLayoutPanel); this.MinimumSize = new System.Drawing.Size(355, 266); this.Name = "StructurePropertiesView"; this.Size = new System.Drawing.Size(355, 266); this.Leave += new System.EventHandler(this.CommentTextBoxMaybeChanged); this._nestedTableLayoutPanel.ResumeLayout(false); this._nestedTableLayoutPanel.PerformLayout(); this.flowLayoutPanelOccurs.ResumeLayout(false); this.flowLayoutPanelOccurs.PerformLayout(); this.flowLayoutPanel1.ResumeLayout(false); this.flowLayoutPanel1.PerformLayout(); this.ResumeLayout(false); } #endregion private System.Windows.Forms.TableLayoutPanel _nestedTableLayoutPanel; private System.Windows.Forms.ComboBox _InferComboBox; private System.Windows.Forms.ListView _parentListView; private System.Windows.Forms.ColumnHeader columnHeaderMarker; private System.Windows.Forms.ColumnHeader columnHeaderOccurs; private System.Windows.Forms.TextBox summaryLabel; private System.Windows.Forms.TextBox _commentsLabel; private System.Windows.Forms.TextBox _commentTextBox; private System.Windows.Forms.TextBox _summaryTextBox; private System.Windows.Forms.TextBox _parentLabel; private System.Windows.Forms.TextBox _explanationLabel; private System.Windows.Forms.TextBox _inferComboLabel; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanelOccurs; private System.Windows.Forms.RadioButton _onceRadioButton; private System.Windows.Forms.RadioButton _multipleTogetherRadioButton; private System.Windows.Forms.RadioButton _multipleApartRadioButton; private System.Windows.Forms.CheckBox _requiredCheckBox; private System.Windows.Forms.FlowLayoutPanel flowLayoutPanel1; private System.Windows.Forms.Button _deleteButton; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Pixator.Api.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.MirrorSequences { using Microsoft.Rest; using Models; /// <summary> /// A sample API that uses a petstore as an example to demonstrate /// features in the swagger-2.0 specification /// </summary> public partial class SequenceRequestResponseTest : Microsoft.Rest.ServiceClient<SequenceRequestResponseTest>, ISequenceRequestResponseTest { /// <summary> /// The base URI of the service. /// </summary> public System.Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public Newtonsoft.Json.JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Initializes a new instance of the SequenceRequestResponseTest class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SequenceRequestResponseTest(params System.Net.Http.DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SequenceRequestResponseTest class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public SequenceRequestResponseTest(System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the SequenceRequestResponseTest class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SequenceRequestResponseTest(System.Uri baseUri, params System.Net.Http.DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the SequenceRequestResponseTest class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public SequenceRequestResponseTest(System.Uri baseUri, System.Net.Http.HttpClientHandler rootHandler, params System.Net.Http.DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new System.ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// An optional partial-method to perform custom initialization. ///</summary> partial void CustomInitialize(); /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.BaseUri = new System.Uri("http://petstore.swagger.wordnik.com/api"); SerializationSettings = new Newtonsoft.Json.JsonSerializerSettings { Formatting = Newtonsoft.Json.Formatting.Indented, DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; DeserializationSettings = new Newtonsoft.Json.JsonSerializerSettings { DateFormatHandling = Newtonsoft.Json.DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = Newtonsoft.Json.DateTimeZoneHandling.Utc, NullValueHandling = Newtonsoft.Json.NullValueHandling.Ignore, ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Serialize, ContractResolver = new Microsoft.Rest.Serialization.ReadOnlyJsonContractResolver(), Converters = new System.Collections.Generic.List<Newtonsoft.Json.JsonConverter> { new Microsoft.Rest.Serialization.Iso8601TimeSpanConverter() } }; CustomInitialize(); } /// <summary> /// Creates a new pet in the store. Duplicates are allowed /// </summary> /// <param name='pets'> /// Pets to add to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorModelException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>>> AddPetWithHttpMessagesAsync(System.Collections.Generic.IList<Pet> pets, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (pets == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "pets"); } if (pets != null) { foreach (var element in pets) { if (element != null) { element.Validate(); } } } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("pets", pets); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "AddPet", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "pets").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(pets != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(pets, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorModelException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); ErrorModel _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<ErrorModel>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<Pet>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<Pet>>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Adds new pet stylesin the store. Duplicates are allowed /// </summary> /// <param name='petStyle'> /// Pet style to add to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<int?>>> AddPetStylesWithHttpMessagesAsync(System.Collections.Generic.IList<int?> petStyle, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (petStyle == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "petStyle"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("petStyle", petStyle); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "AddPetStyles", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("POST"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(petStyle != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); System.Collections.Generic.IList<ErrorModel> _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<ErrorModel>>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<int?>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<int?>>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Updates new pet stylesin the store. Duplicates are allowed /// </summary> /// <param name='petStyle'> /// Pet style to add to the store /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.HttpOperationException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<int?>>> UpdatePetStylesWithHttpMessagesAsync(System.Collections.Generic.IList<int?> petStyle, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { if (petStyle == null) { throw new Microsoft.Rest.ValidationException(Microsoft.Rest.ValidationRules.CannotBeNull, "petStyle"); } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("petStyle", petStyle); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "UpdatePetStyles", tracingParameters); } // Construct URL var _baseUrl = this.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "primitives").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(petStyle != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(petStyle, this.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new Microsoft.Rest.HttpOperationException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); System.Collections.Generic.IList<ErrorModel> _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<ErrorModel>>(_responseContent, this.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<System.Collections.Generic.IList<int?>>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<System.Collections.Generic.IList<int?>>(_responseContent, this.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; /// <summary> /// System.String.Equals(Object) /// Determines whether this instance of String and a specified object, /// which must also be a String object, have the same value. /// This method performs an ordinal (case-sensitive and culture-insensitive) comparison. /// </summary> class StringEquals1 { private const int c_MIN_STRING_LEN = 8; private const int c_MAX_STRING_LEN = 256; private const int c_MAX_SHORT_STR_LEN = 31;//short string (<32 chars) private const int c_MIN_LONG_STR_LEN = 257;//long string ( >256 chars) private const int c_MAX_LONG_STR_LEN = 65535; private const string c_POS_TEST_PREFIX = "PosTest"; private const string c_NEG_TEST_PREFIX = "NegTest"; private const string c_GREEK_SIGMA_STR_A = "\x03C2\x03C3\x03A3\x03C2\x03C3"; private const string c_GREEK_SIGMA_STR_B = "\x03A3\x03A3\x03A3\x03C3\x03C2"; private int totalTestCount; private int posTestCount; private int negTestCount; private int passedTestCount; private int failedTestCount; private enum TestType { PositiveTest = 1, NegativeTest = 2 }; private enum TestResult { NotRun = 0, PassedTest = 1, FailedTest = 2 }; internal struct Parameters { public string strSrc; public object obj; public string DataString { get { string str, strA, strB; int lenA, lenB; if (null == strSrc) { strA = "null"; lenA = 0; } else { strA = strSrc; lenA = strSrc.Length; } if (null == obj) { strB = "null"; lenB = 0; } else { strB = obj.ToString(); lenB = strB.Length; } str = string.Format("\n[String value]\nSource: \"{0}\"\nObj: \"{1}\"", strA, strB); str += string.Format("\n[String length]\nSource: {0}\nObj: {1}", lenA, lenB); return str; } } } //Default constructor to ininitial all kind of test counts public StringEquals1() { totalTestCount = posTestCount = negTestCount = 0; passedTestCount = failedTestCount = 0; } #region Methods for all test scenarioes //Update (postive or negative) and total test count at the beginning of test scenario private void UpdateCounts(TestType testType) { if (TestType.PositiveTest == testType) { posTestCount++; totalTestCount++; return; } if (TestType.NegativeTest == testType) { negTestCount++; totalTestCount++; return; } } //Update failed or passed test counts at the end of test scenario private void UpdateCounts(TestResult testResult) { if (TestResult.PassedTest == testResult) { passedTestCount++; return; } if (TestResult.FailedTest == testResult) { failedTestCount++; return; } } //Generate standard error number string //i.e "9", "12" is not proper. Instead they should be "009", "012" private string GenerateErrorNum(int errorNum) { string temp = errorNum.ToString(); string errorNumStr = new string('0', 3 - temp.Length) + temp; return errorNumStr; } //Generate testId string //i.e "P9", "N12" is not proper. Instead they should be "P009", "N012" private string GenerateTestId(TestType testType) { string temp, testId; if (testType == TestType.PositiveTest) { temp = this.posTestCount.ToString(); testId = "P" + new string('0', 3 - temp.Length) + temp; } else { temp = this.negTestCount.ToString(); testId = "N" + new string('0', 3 - temp.Length) + temp; } return testId; } #endregion public static int Main() { StringEquals1 sc = new StringEquals1(); TestLibrary.TestFramework.BeginTestCase("for method: System.String.Equals(Object obj)"); if (sc.RunTests()) { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("PASS"); return 100; } else { TestLibrary.TestFramework.EndTestCase(); TestLibrary.TestFramework.LogInformation("FAIL"); return 0; } } public bool RunTests() { bool retVal = true; //Postive test scenarios TestLibrary.TestFramework.LogInformation("[Positive]"); retVal = PosTest1() && retVal; retVal = PosTest2() && retVal; retVal = PosTest3() && retVal; retVal = PosTest4() && retVal; retVal = PosTest5() && retVal; retVal = PosTest6() && retVal; retVal = PosTest7() && retVal; retVal = PosTest8() && retVal; retVal = PosTest9() && retVal; retVal = PosTest10() && retVal; retVal = PosTest11() && retVal; retVal = PosTest12() && retVal; retVal = PosTest13() && retVal; retVal = PosTest14() && retVal; retVal = PosTest15() && retVal; retVal = PosTest16() && retVal; retVal = PosTest17() && retVal; retVal = PosTest18() && retVal; retVal = PosTest19() && retVal; retVal = PosTest20() && retVal; retVal = PosTest21() && retVal; //Negative test scenarios TestLibrary.TestFramework.LogInformation("[Negative]"); retVal = NegTest1() && retVal; return retVal; } #region Positive test scenarioes #region null, String.Empty and "\0" testing public bool PosTest1() { Parameters paras; const string c_TEST_DESC = "The obj to compare with is null"; bool expectedValue = false; paras.strSrc = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); paras.obj = null; return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } // PosTest2 to PosTest6 are new tests added in 8-4-2006 by v-yaduoj public bool PosTest2() { Parameters paras; const string c_TEST_DESC = "String.Empty vs null"; bool expectedValue = false; paras.strSrc = String.Empty; paras.obj = null; return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest3() { Parameters paras; const string c_TEST_DESC = "String.Empty vs \"\""; bool expectedValue = true; paras.strSrc = String.Empty; paras.obj = ""; return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest4() { Parameters paras; const string c_TEST_DESC = "String.Empty vs \"\\0\""; bool expectedValue = false; paras.strSrc = String.Empty; paras.obj = "\0"; return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest5() { Parameters paras; const string c_TEST_DESC = "String.Empty vs unempty string"; bool expectedValue = false; paras.strSrc = String.Empty; paras.obj = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest6() { Parameters paras; const string c_TEST_DESC = "Embedded '\\0' string "; bool expectedValue = true; StringBuilder sb = new StringBuilder("This\0String\0Is\0Valid"); paras.strSrc = sb.ToString(); paras.obj = sb.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } // PosTest2 to PosTest6 are new tests added in 8-4-2006 by Noter(v-yaduoj) #endregion //The following region is new updates in 8-4-2006 by Noter(v-yaduoj) #region Tab and space testing public bool PosTest7() { Parameters paras; const string c_TEST_DESC = "Tab vs 4 spaces"; bool expectedValue = false; paras.strSrc = "\t"; paras.obj = new string('\x0020', 4); // new update 8-8-2006 Noter(v-yaduoj) return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest8() { Parameters paras; const string c_TEST_DESC = "Tab vs 8 spaces"; bool expectedValue = false; paras.strSrc = "\t"; paras.obj = new string('\x0020', 8); // new update 8-8-2006 Noter(v-yaduoj) return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } #endregion #region Non-string type obj public bool PosTest9() { Parameters paras; const string c_TEST_DESC = "The type of obj to compare with is Int32"; bool expectedValue = false; paras.obj = TestLibrary.Generator.GetInt32(-55); paras.strSrc = paras.obj.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest10() { Parameters paras; const string c_TEST_DESC = "The type of obj to compare with is Int16"; bool expectedValue = false; paras.obj = TestLibrary.Generator.GetInt16(-55); paras.strSrc = paras.obj.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest11() { Parameters paras; const string c_TEST_DESC = "The type of obj to compare with is Int64"; bool expectedValue = false; paras.obj = TestLibrary.Generator.GetInt64(-55); paras.strSrc = paras.obj.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest12() { Parameters paras; const string c_TEST_DESC = "The type of obj to compare with is Double"; bool expectedValue = false; paras.obj = TestLibrary.Generator.GetDouble(-55); paras.strSrc = paras.obj.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest13() { Parameters paras; const string c_TEST_DESC = "The type of obj to compare with is single"; bool expectedValue = false; paras.obj = TestLibrary.Generator.GetSingle(-55); paras.strSrc = paras.obj.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest14() { Parameters paras; const string c_TEST_DESC = "The type of obj to compare with is string[]"; bool expectedValue = false; paras.obj = TestLibrary.Generator.GetStrings(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); paras.strSrc = paras.obj.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest15() { Parameters paras; const string c_TEST_DESC = "The type of obj to compare with is byte"; bool expectedValue = false; paras.obj = TestLibrary.Generator.GetByte(-55); paras.strSrc = paras.obj.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest16() { Parameters paras; const string c_TEST_DESC = "The type of obj to compare with is Byte[]"; bool expectedValue = false; paras.obj = new byte[] {1,2,3}; paras.strSrc = paras.obj.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest17() { Parameters paras; const string c_TEST_DESC = "The type of obj to compare with is char"; bool expectedValue = false; paras.obj = TestLibrary.Generator.GetChar(-55); paras.strSrc = paras.obj.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest18() { Parameters paras; const string c_TEST_DESC = "The type of obj to compare with is char[]"; bool expectedValue = false; paras.obj = new char[] {'1', 'a', '\x098A'}; paras.strSrc = paras.obj.ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } #endregion #region Case sensitive testing public bool PosTest19() { Parameters paras; const string c_TEST_DESC = "Case sensitive testing"; bool expectedValue = false; char ch = this.GetUpperChar(); paras.obj = ch.ToString(); paras.strSrc = char.ToLower(ch).ToString(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } //Greek Sigma: //Two lower case Sigma: (0x03C2), (0x03C3) //One upper case Sigma: (0x03A3) //where 2 lower case characters have the same upper case character. public bool PosTest20() { Parameters paras; const string c_TEST_DESC = "Asymmetric casing: Greek Sigma character, different case"; bool expectedValue = false; paras.obj = c_GREEK_SIGMA_STR_A; paras.strSrc = c_GREEK_SIGMA_STR_B; return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } public bool PosTest21() { Parameters paras; const string c_TEST_DESC = "Asymmetric casing: Greek Sigma character, both upper case"; bool expectedValue = true; string str1 = c_GREEK_SIGMA_STR_A; string str2 = c_GREEK_SIGMA_STR_B; paras.obj = str1.ToUpper(); paras.strSrc = str2.ToUpper(); return ExecutePosTest(paras, expectedValue, c_TEST_DESC); } #endregion #endregion //end for positive test scenarioes #region Helper methods for positive test scenarioes private bool ExecutePosTest(Parameters paras, bool expectedValue, string testDesc) { bool retVal = true; UpdateCounts(TestType.PositiveTest); string testId = GenerateTestId(TestType.PositiveTest); TestResult testResult = TestResult.NotRun; string testInfo = c_POS_TEST_PREFIX + this.posTestCount.ToString() + ": " + testDesc; bool actualValue; TestLibrary.TestFramework.BeginScenario(testInfo); try { actualValue = this.CallTestMethod(paras); if (expectedValue != actualValue) { string errorDesc = "Value is not " + expectedValue + " as expected: Actual(" + actualValue + ")"; errorDesc += paras.DataString + "\nTest scenario Id: " + testId; // new updates 8-6-2006 Noter(v-yaduoj) TestLibrary.TestFramework.LogError(GenerateErrorNum((totalTestCount << 1) - 1) + " TestId -" + testId, errorDesc); testResult = TestResult.FailedTest; retVal = false; } testResult = TestResult.PassedTest; } catch (Exception e) { TestLibrary.TestFramework.LogError(GenerateErrorNum(totalTestCount << 1) + " TestId -" + testId, "Unexpected exception: " + e + paras.DataString); testResult = TestResult.FailedTest; retVal = false; } UpdateCounts(testResult); return retVal; } #endregion #region Negative test scenarioes public bool NegTest1() { Parameters paras; const string c_TEST_DESC = "The instance of source string is null"; const string c_ERROR_DESC = "NullReferenceException is not thrown as expected"; paras.strSrc = null; paras.obj = TestLibrary.Generator.GetString(-55, false, c_MIN_STRING_LEN, c_MAX_STRING_LEN); return ExeNegTest_NRE(paras, c_TEST_DESC, c_ERROR_DESC); } #endregion //end for negative test scenarioes #region Helper methods for negative test scenarioes //Test NullReferenceException private bool ExeNegTest_NRE(Parameters paras, string testDesc, string errorDesc) { bool retVal = true; UpdateCounts(TestType.NegativeTest); string testId = GenerateTestId(TestType.NegativeTest); string testInfo = c_NEG_TEST_PREFIX + this.negTestCount.ToString() + ": " + testDesc; TestResult testResult = TestResult.NotRun; TestLibrary.TestFramework.BeginScenario(testInfo); try { this.CallTestMethod(paras); TestLibrary.TestFramework.LogError(GenerateErrorNum((this.totalTestCount << 1) - 1) + " TestId -" + testId, errorDesc + paras.DataString); testResult = TestResult.FailedTest; retVal = false; } catch (NullReferenceException) { testResult = TestResult.PassedTest; } catch (Exception e) { TestLibrary.TestFramework.LogError(GenerateErrorNum(this.totalTestCount << 1) + " TestId -" + testId, "Unexpected exception: " + e + paras.DataString); testResult = TestResult.FailedTest; retVal = false; } UpdateCounts(testResult); return retVal; } #endregion //Involke the test method private bool CallTestMethod(Parameters paras) { return paras.strSrc.Equals(paras.obj); } #region helper methods for generating test data private bool GetBoolean() { Int32 i = this.GetInt32(1, 2); return (i == 1) ? true : false; } //Get a non-negative integer between minValue and maxValue private Int32 GetInt32(Int32 minValue, Int32 maxValue) { try { if (minValue == maxValue) { return minValue; } if (minValue < maxValue) { return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue); } } catch { throw; } return minValue; } private Int32 Min(Int32 i1, Int32 i2) { return (i1 <= i2) ? i1 : i2; } private Int32 Max(Int32 i1, Int32 i2) { return (i1 >= i2) ? i1 : i2; } private char GetUpperChar() { Char c; // Grab an ASCII letter c = Convert.ToChar(TestLibrary.Generator.GetInt16(-55) % 26 + 'A'); return c; } #endregion }
// // XmlDsigExcC14NTransformTest.cs - Test Cases for XmlDsigExcC14NTransform // // Author: // original: // Sebastien Pouliot <sebastien@ximian.com> // Aleksey Sanin (aleksey@aleksey.com) // this file: // Atsushi Enomoto <atsushi@ximian.com> // // (C) 2002, 2003 Motus Technologies Inc. (http://www.motus.com) // (C) 2003 Aleksey Sanin (aleksey@aleksey.com) // (C) 2004 Novell (http://www.novell.com) // // Licensed to the .NET Foundation under one or more agreements. // See the LICENSE file in the project root for more information. using System.IO; using System.Text; using System.Xml; using System.Xml.Resolvers; using Xunit; namespace System.Security.Cryptography.Xml.Tests { // Note: GetInnerXml is protected in XmlDsigExcC14NTransform making it // difficult to test properly. This class "open it up" :-) public class UnprotectedXmlDsigExcC14NTransform : XmlDsigExcC14NTransform { public UnprotectedXmlDsigExcC14NTransform() { } public UnprotectedXmlDsigExcC14NTransform(bool includeComments) : base(includeComments) { } public UnprotectedXmlDsigExcC14NTransform(string inclusiveNamespacesPrefixList) : base(inclusiveNamespacesPrefixList) { } public UnprotectedXmlDsigExcC14NTransform(bool includeComments, string inclusiveNamespacesPrefixList) : base(includeComments, inclusiveNamespacesPrefixList) { } public XmlNodeList UnprotectedGetInnerXml() { return base.GetInnerXml(); } } public class XmlDsigExcC14NTransformTest { protected UnprotectedXmlDsigExcC14NTransform transform; public XmlDsigExcC14NTransformTest() { transform = new UnprotectedXmlDsigExcC14NTransform(); } [Fact] // ctor () public void Constructor1() { Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#", transform.Algorithm); Assert.Null(transform.InclusiveNamespacesPrefixList); CheckProperties(transform); } [Fact] // ctor (Boolean) public void Constructor2() { transform = new UnprotectedXmlDsigExcC14NTransform(true); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#WithComments", transform.Algorithm); Assert.Null(transform.InclusiveNamespacesPrefixList); CheckProperties(transform); transform = new UnprotectedXmlDsigExcC14NTransform(false); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#", transform.Algorithm); Assert.Null(transform.InclusiveNamespacesPrefixList); CheckProperties(transform); } [Fact] // ctor (String) public void Constructor3() { transform = new UnprotectedXmlDsigExcC14NTransform(null); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#", transform.Algorithm); Assert.Null(transform.InclusiveNamespacesPrefixList); CheckProperties(transform); transform = new UnprotectedXmlDsigExcC14NTransform(string.Empty); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#", transform.Algorithm); Assert.Equal(string.Empty, transform.InclusiveNamespacesPrefixList); CheckProperties(transform); transform = new UnprotectedXmlDsigExcC14NTransform("#default xsd"); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#", transform.Algorithm); Assert.Equal("#default xsd", transform.InclusiveNamespacesPrefixList); CheckProperties(transform); } [Fact] // ctor (Boolean, String) public void Constructor4() { transform = new UnprotectedXmlDsigExcC14NTransform(true, null); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#WithComments", transform.Algorithm); Assert.Null(transform.InclusiveNamespacesPrefixList); CheckProperties(transform); transform = new UnprotectedXmlDsigExcC14NTransform(true, string.Empty); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#WithComments", transform.Algorithm); Assert.Equal(string.Empty, transform.InclusiveNamespacesPrefixList); CheckProperties(transform); transform = new UnprotectedXmlDsigExcC14NTransform(true, "#default xsd"); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#WithComments", transform.Algorithm); Assert.Equal("#default xsd", transform.InclusiveNamespacesPrefixList); CheckProperties(transform); transform = new UnprotectedXmlDsigExcC14NTransform(false, null); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#", transform.Algorithm); Assert.Null(transform.InclusiveNamespacesPrefixList); CheckProperties(transform); transform = new UnprotectedXmlDsigExcC14NTransform(false, string.Empty); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#", transform.Algorithm); Assert.Equal(string.Empty, transform.InclusiveNamespacesPrefixList); CheckProperties(transform); transform = new UnprotectedXmlDsigExcC14NTransform(false, "#default xsd"); Assert.Equal("http://www.w3.org/2001/10/xml-exc-c14n#", transform.Algorithm); Assert.Equal("#default xsd", transform.InclusiveNamespacesPrefixList); CheckProperties(transform); } void CheckProperties(XmlDsigExcC14NTransform transform) { Type[] input = transform.InputTypes; Assert.True((input.Length == 3), "Input #"); // check presence of every supported input types bool istream = false; bool ixmldoc = false; bool ixmlnl = false; foreach (Type t in input) { if (t.ToString() == "System.IO.Stream") istream = true; if (t.ToString() == "System.Xml.XmlDocument") ixmldoc = true; if (t.ToString() == "System.Xml.XmlNodeList") ixmlnl = true; } Assert.True(istream, "Input Stream"); Assert.True(ixmldoc, "Input XmlDocument"); Assert.True(ixmlnl, "Input XmlNodeList"); Type[] output = transform.OutputTypes; Assert.True((output.Length == 1), "Output #"); // check presence of every supported output types bool ostream = false; foreach (Type t in output) { if (t.ToString() == "System.IO.Stream") ostream = true; } Assert.True(ostream, "Output Stream"); } [Fact] public void Types() { Type[] input = transform.InputTypes; input[0] = null; input[1] = null; input[2] = null; // property does not return a clone foreach (Type t in transform.InputTypes) { Assert.Null(t); } // it's not a static array XmlDsigExcC14NTransform t2 = new XmlDsigExcC14NTransform(); foreach (Type t in t2.InputTypes) { Assert.NotNull(t); } } [Fact] public void GetInnerXml() { XmlNodeList xnl = transform.UnprotectedGetInnerXml(); Assert.Null(xnl); } private string Stream2String(Stream s) { StringBuilder sb = new StringBuilder(); int b = s.ReadByte(); while (b != -1) { sb.Append(Convert.ToChar(b)); b = s.ReadByte(); } return sb.ToString(); } static string xml = "<Test attrib='at ' xmlns=\"http://www.go-mono.com/\" > \r\n &#xD; <Toto/> text &amp; </Test >"; // GOOD for Stream input static string c14xml2 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> \n &#xD; <Toto></Toto> text &amp; </Test>"; // GOOD for XmlDocument input. The difference is because once // xml string is loaded to XmlDocument, there is no difference // between \r and &#xD;, so every \r must be handled as &#xD;. static string c14xml3 = "<Test xmlns=\"http://www.go-mono.com/\" attrib=\"at \"> &#xD;\n &#xD; <Toto></Toto> text &amp; </Test>"; private XmlDocument GetDoc() { XmlDocument doc = new XmlDocument(); doc.PreserveWhitespace = true; doc.LoadXml(xml); return doc; } [Fact] public void LoadInputAsXmlDocument() { XmlDocument doc = GetDoc(); transform.LoadInput(doc); Stream s = (Stream)transform.GetOutput(); string output = Stream2String(s); Assert.Equal(c14xml3, output); } [Fact(Skip = "https://github.com/dotnet/corefx/issues/16685")] // see LoadInputAsXmlNodeList2 description public void LoadInputAsXmlNodeList() { XmlDocument doc = GetDoc(); // Argument list just contains element Test. transform.LoadInput(doc.ChildNodes); Stream s = (Stream)transform.GetOutput(); string output = Stream2String(s); Assert.Equal("<Test></Test>", output); } [Fact(Skip = "https://github.com/dotnet/corefx/issues/16685")] // MS has a bug that those namespace declaration nodes in // the node-set are written to output. Related spec section is: // http://www.w3.org/TR/2001/REC-xml-c14n-20010315#ProcessingModel public void LoadInputAsXmlNodeList2() { XmlDocument doc = GetDoc(); transform.LoadInput(doc.SelectNodes("//*")); Stream s = (Stream)transform.GetOutput(); string output = Stream2String(s); string expected = @"<Test><Toto></Toto></Test>"; Assert.Equal(expected, output); } [Fact] public void LoadInputAsStream() { MemoryStream ms = new MemoryStream(); byte[] x = Encoding.ASCII.GetBytes(xml); ms.Write(x, 0, x.Length); ms.Position = 0; transform.LoadInput(ms); Stream s = (Stream)transform.GetOutput(); string output = Stream2String(s); Assert.Equal(c14xml2, output); } [Fact] public void LoadInputWithUnsupportedType() { byte[] bad = { 0xBA, 0xD }; AssertExtensions.Throws<ArgumentException>("obj", () => transform.LoadInput(bad)); } [Fact] public void UnsupportedOutput() { XmlDocument doc = new XmlDocument(); AssertExtensions.Throws<ArgumentException>("type", () => transform.GetOutput(doc.GetType())); } [Fact] public void ExcC14NSpecExample1() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("doc.dtd"), ""); string res = ExecuteXmlDSigExcC14NTransform(ExcC14NSpecExample1Input); Assert.Equal(ExcC14NSpecExample1Output, res); } [Fact] public void ExcC14NSpecExample2() { string res = ExecuteXmlDSigExcC14NTransform(ExcC14NSpecExample2Input); Assert.Equal(ExcC14NSpecExample2Output, res); } [Fact] public void ExcC14NSpecExample3() { string res = ExecuteXmlDSigExcC14NTransform(ExcC14NSpecExample3Input); Assert.Equal(ExcC14NSpecExample3Output, res); } [Fact] // [Ignore ("This test should be fine, but it does not pass under MS.NET")] public void ExcC14NSpecExample4() { string res = ExecuteXmlDSigExcC14NTransform(ExcC14NSpecExample4Input); Assert.Equal(ExcC14NSpecExample4Output, res); } [Fact] public void ExcC14NSpecExample5() { XmlPreloadedResolver resolver = new XmlPreloadedResolver(); resolver.Add(TestHelpers.ToUri("doc.txt"), "world"); string input = ExcC14NSpecExample5Input; string res = ExecuteXmlDSigExcC14NTransform(input, resolver); Assert.Equal(ExcC14NSpecExample5Output, res); } [Fact] public void ExcC14NSpecExample6() { string res = ExecuteXmlDSigExcC14NTransform(ExcC14NSpecExample6Input); Assert.Equal(ExcC14NSpecExample6Output, res); } private string ExecuteXmlDSigExcC14NTransform(string InputXml, XmlResolver resolver = null) { XmlDocument doc = new XmlDocument(); doc.XmlResolver = resolver; doc.PreserveWhitespace = true; doc.LoadXml(InputXml); // Testing default attribute support with // vreader.ValidationType = ValidationType.None. // UTF8Encoding utf8 = new UTF8Encoding(); byte[] data = utf8.GetBytes(InputXml.ToString()); Stream stream = new MemoryStream(data); var settings = new XmlReaderSettings { ValidationType = ValidationType.None, DtdProcessing = DtdProcessing.Parse, XmlResolver = resolver }; using (XmlReader reader = XmlReader.Create(stream, settings)) { doc.Load(reader); transform.LoadInput(doc); return Stream2String((Stream) transform.GetOutput()); } } // // Example 1 from ExcC14N spec - PIs, Comments, and Outside of Document Element: // http://www.w3.org/TR/xml-c14n#Example-OutsideDoc // // Aleksey: // removed reference to an empty external DTD // static string ExcC14NSpecExample1Input = "<?xml version=\"1.0\"?>\n" + "\n" + "<?xml-stylesheet href=\"doc.xsl\"\n" + " type=\"text/xsl\" ?>\n" + "\n" + "<!DOCTYPE doc SYSTEM \"doc.dtd\">\n" + "\n" + "<doc>Hello, world!<!-- Comment 1 --></doc>\n" + "\n" + "<?pi-without-data ?>\n\n" + "<!-- Comment 2 -->\n\n" + "<!-- Comment 3 -->\n"; static string ExcC14NSpecExample1Output = "<?xml-stylesheet href=\"doc.xsl\"\n" + " type=\"text/xsl\" ?>\n" + "<doc>Hello, world!</doc>\n" + "<?pi-without-data?>"; // // Example 2 from ExcC14N spec - Whitespace in Document Content: // http://www.w3.org/TR/xml-c14n#Example-WhitespaceInContent // static string ExcC14NSpecExample2Input = "<doc>\n" + " <clean> </clean>\n" + " <dirty> A B </dirty>\n" + " <mixed>\n" + " A\n" + " <clean> </clean>\n" + " B\n" + " <dirty> A B </dirty>\n" + " C\n" + " </mixed>\n" + "</doc>\n"; static string ExcC14NSpecExample2Output = "<doc>\n" + " <clean> </clean>\n" + " <dirty> A B </dirty>\n" + " <mixed>\n" + " A\n" + " <clean> </clean>\n" + " B\n" + " <dirty> A B </dirty>\n" + " C\n" + " </mixed>\n" + "</doc>"; // // Example 3 from ExcC14N spec - Start and End Tags: // http://www.w3.org/TR/xml-c14n#Example-SETags // static string ExcC14NSpecExample3Input = "<!DOCTYPE doc [<!ATTLIST e9 attr CDATA \"default\">]>\n" + "<doc>\n" + " <e1 />\n" + " <e2 ></e2>\n" + " <e3 name = \"elem3\" id=\"elem3\" />\n" + " <e4 name=\"elem4\" id=\"elem4\" ></e4>\n" + " <e5 a:attr=\"out\" b:attr=\"sorted\" attr2=\"all\" attr=\"I\'m\"\n" + " xmlns:b=\"http://www.ietf.org\" \n" + " xmlns:a=\"http://www.w3.org\"\n" + " xmlns=\"http://www.uvic.ca\"/>\n" + " <e6 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + " <e7 xmlns=\"http://www.ietf.org\">\n" + " <e8 xmlns=\"\" xmlns:a=\"http://www.w3.org\">\n" + " <e9 xmlns=\"\" xmlns:a=\"http://www.ietf.org\"/>\n" + " </e8>\n" + " </e7>\n" + " </e6>\n" + "</doc>\n"; static string ExcC14NSpecExample3Output = "<doc>\n" + " <e1></e1>\n" + " <e2></e2>\n" + " <e3 id=\"elem3\" name=\"elem3\"></e3>\n" + " <e4 id=\"elem4\" name=\"elem4\"></e4>\n" + " <e5 xmlns=\"http://www.uvic.ca\" xmlns:a=\"http://www.w3.org\" xmlns:b=\"http://www.ietf.org\" attr=\"I\'m\" attr2=\"all\" b:attr=\"sorted\" a:attr=\"out\"></e5>\n" + " <e6>\n" + " <e7 xmlns=\"http://www.ietf.org\">\n" + " <e8 xmlns=\"\">\n" + " <e9 attr=\"default\"></e9>\n" + // " <e9 xmlns:a=\"http://www.ietf.org\"></e9>\n" + " </e8>\n" + " </e7>\n" + " </e6>\n" + "</doc>"; // // Example 4 from ExcC14N spec - Character Modifications and Character References: // http://www.w3.org/TR/xml-c14n#Example-Chars // // Aleksey: // This test does not include "normId" element // because it has an invalid ID attribute "id" which // should be normalized by XML parser. Currently Mono // does not support this (see comment after this example // in the spec). static string ExcC14NSpecExample4Input = "<!DOCTYPE doc [<!ATTLIST normId id ID #IMPLIED>]>\n" + "<doc>\n" + " <text>First line&#x0d;&#10;Second line</text>\n" + " <value>&#x32;</value>\n" + " <compute><![CDATA[value>\"0\" && value<\"10\" ?\"valid\":\"error\"]]></compute>\n" + " <compute expr=\'value>\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"\'>valid</compute>\n" + " <norm attr=\' &apos; &#x20;&#13;&#xa;&#9; &apos; \'/>\n" + // " <normId id=\' &apos; &#x20;&#13;&#xa;&#9; &apos; \'/>\n" + "</doc>\n"; static string ExcC14NSpecExample4Output = "<doc>\n" + " <text>First line&#xD;\n" + "Second line</text>\n" + " <value>2</value>\n" + " <compute>value&gt;\"0\" &amp;&amp; value&lt;\"10\" ?\"valid\":\"error\"</compute>\n" + " <compute expr=\"value>&quot;0&quot; &amp;&amp; value&lt;&quot;10&quot; ?&quot;valid&quot;:&quot;error&quot;\">valid</compute>\n" + " <norm attr=\" \' &#xD;&#xA;&#x9; \' \"></norm>\n" + // " <normId id=\"\' &#xD;&#xA;&#x9; \'\"></normId>\n" + "</doc>"; // // Example 5 from ExcC14N spec - Entity References: // http://www.w3.org/TR/xml-c14n#Example-Entities // static string ExcC14NSpecExample5Input => "<!DOCTYPE doc [\n" + "<!ATTLIST doc attrExtEnt ENTITY #IMPLIED>\n" + "<!ENTITY ent1 \"Hello\">\n" + $"<!ENTITY ent2 SYSTEM \"doc.txt\">\n" + "<!ENTITY entExt SYSTEM \"earth.gif\" NDATA gif>\n" + "<!NOTATION gif SYSTEM \"viewgif.exe\">\n" + "]>\n" + "<doc attrExtEnt=\"entExt\">\n" + " &ent1;, &ent2;!\n" + "</doc>\n" + "\n" + $"<!-- Let doc.txt contain \"world\" (excluding the quotes) -->\n"; static string ExcC14NSpecExample5Output = "<doc attrExtEnt=\"entExt\">\n" + " Hello, world!\n" + "</doc>"; // // Example 6 from ExcC14N spec - UTF-8 Encoding: // http://www.w3.org/TR/xml-c14n#Example-UTF8 // static string ExcC14NSpecExample6Input = "<?xml version=\"1.0\" encoding=\"ISO-8859-1\"?>\n" + "<doc>&#169;</doc>\n"; static string ExcC14NSpecExample6Output = "<doc>\xC2\xA9</doc>"; [Fact] public void SimpleNamespacePrefixes() { string input = "<a:Action xmlns:a='urn:foo'>http://tempuri.org/IFoo/Echo</a:Action>"; string expected = @"<a:Action xmlns:a=""urn:foo"">http://tempuri.org/IFoo/Echo</a:Action>"; XmlDocument doc = new XmlDocument(); doc.LoadXml(input); XmlDsigExcC14NTransform t = new XmlDsigExcC14NTransform(); t.LoadInput(doc); Stream s = t.GetOutput() as Stream; Assert.Equal(new StreamReader(s, Encoding.UTF8).ReadToEnd(), expected); } [Fact] public void GetDigestedOutput_Null() { Assert.Throws<NullReferenceException>(() => new XmlDsigExcC14NTransform().GetDigestedOutput(null)); } } }
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gaxgrpc = Google.Api.Gax.Grpc; using lro = Google.LongRunning; using grpccore = Grpc.Core; using moq = Moq; using st = System.Threading; using stt = System.Threading.Tasks; using xunit = Xunit; namespace Google.Cloud.Compute.V1.Tests { /// <summary>Generated unit tests.</summary> public sealed class GeneratedNetworkEndpointGroupsClientTest { [xunit::FactAttribute] public void GetRequestObject() { moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNetworkEndpointGroupRequest request = new GetNetworkEndpointGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NetworkEndpointGroup = "network_endpoint_groupdf1fb34e", }; NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", CloudRun = new NetworkEndpointGroupCloudRun(), Annotations = { { "key8a0b6e3c", "value60c16320" }, }, NetworkEndpointType = "network_endpoint_typecc2da78a", Region = "regionedb20d96", Network = "networkd22ce091", PscTargetService = "psc_target_service718e45ab", Subnetwork = "subnetworkf55bf572", AppEngine = new NetworkEndpointGroupAppEngine(), Description = "description2cf9da67", DefaultPort = 4850952, SelfLink = "self_link7e87f12d", CloudFunction = new NetworkEndpointGroupCloudFunction(), }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); NetworkEndpointGroup response = client.Get(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetRequestObjectAsync() { moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNetworkEndpointGroupRequest request = new GetNetworkEndpointGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NetworkEndpointGroup = "network_endpoint_groupdf1fb34e", }; NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", CloudRun = new NetworkEndpointGroupCloudRun(), Annotations = { { "key8a0b6e3c", "value60c16320" }, }, NetworkEndpointType = "network_endpoint_typecc2da78a", Region = "regionedb20d96", Network = "networkd22ce091", PscTargetService = "psc_target_service718e45ab", Subnetwork = "subnetworkf55bf572", AppEngine = new NetworkEndpointGroupAppEngine(), Description = "description2cf9da67", DefaultPort = 4850952, SelfLink = "self_link7e87f12d", CloudFunction = new NetworkEndpointGroupCloudFunction(), }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NetworkEndpointGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); NetworkEndpointGroup responseCallSettings = await client.GetAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); NetworkEndpointGroup responseCancellationToken = await client.GetAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void Get() { moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNetworkEndpointGroupRequest request = new GetNetworkEndpointGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NetworkEndpointGroup = "network_endpoint_groupdf1fb34e", }; NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", CloudRun = new NetworkEndpointGroupCloudRun(), Annotations = { { "key8a0b6e3c", "value60c16320" }, }, NetworkEndpointType = "network_endpoint_typecc2da78a", Region = "regionedb20d96", Network = "networkd22ce091", PscTargetService = "psc_target_service718e45ab", Subnetwork = "subnetworkf55bf572", AppEngine = new NetworkEndpointGroupAppEngine(), Description = "description2cf9da67", DefaultPort = 4850952, SelfLink = "self_link7e87f12d", CloudFunction = new NetworkEndpointGroupCloudFunction(), }; mockGrpcClient.Setup(x => x.Get(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); NetworkEndpointGroup response = client.Get(request.Project, request.Zone, request.NetworkEndpointGroup); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task GetAsync() { moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); GetNetworkEndpointGroupRequest request = new GetNetworkEndpointGroupRequest { Zone = "zone255f4ea8", Project = "projectaa6ff846", NetworkEndpointGroup = "network_endpoint_groupdf1fb34e", }; NetworkEndpointGroup expectedResponse = new NetworkEndpointGroup { Id = 11672635353343658936UL, Kind = "kindf7aa39d9", Name = "name1c9368b0", Size = -1218396681, Zone = "zone255f4ea8", CreationTimestamp = "creation_timestamp235e59a1", CloudRun = new NetworkEndpointGroupCloudRun(), Annotations = { { "key8a0b6e3c", "value60c16320" }, }, NetworkEndpointType = "network_endpoint_typecc2da78a", Region = "regionedb20d96", Network = "networkd22ce091", PscTargetService = "psc_target_service718e45ab", Subnetwork = "subnetworkf55bf572", AppEngine = new NetworkEndpointGroupAppEngine(), Description = "description2cf9da67", DefaultPort = 4850952, SelfLink = "self_link7e87f12d", CloudFunction = new NetworkEndpointGroupCloudFunction(), }; mockGrpcClient.Setup(x => x.GetAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<NetworkEndpointGroup>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); NetworkEndpointGroup responseCallSettings = await client.GetAsync(request.Project, request.Zone, request.NetworkEndpointGroup, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); NetworkEndpointGroup responseCancellationToken = await client.GetAsync(request.Project, request.Zone, request.NetworkEndpointGroup, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissionsRequestObject() { moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNetworkEndpointGroupRequest request = new TestIamPermissionsNetworkEndpointGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsRequestObjectAsync() { moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNetworkEndpointGroupRequest request = new TestIamPermissionsNetworkEndpointGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public void TestIamPermissions() { moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNetworkEndpointGroupRequest request = new TestIamPermissionsNetworkEndpointGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissions(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(expectedResponse); NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse response = client.TestIamPermissions(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource); xunit::Assert.Same(expectedResponse, response); mockGrpcClient.VerifyAll(); } [xunit::FactAttribute] public async stt::Task TestIamPermissionsAsync() { moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient> mockGrpcClient = new moq::Mock<NetworkEndpointGroups.NetworkEndpointGroupsClient>(moq::MockBehavior.Strict); mockGrpcClient.Setup(x => x.CreateOperationsClientForZoneOperations()).Returns(new moq::Mock<lro::Operations.OperationsClient>().Object); TestIamPermissionsNetworkEndpointGroupRequest request = new TestIamPermissionsNetworkEndpointGroupRequest { Zone = "zone255f4ea8", Resource = "resource164eab96", Project = "projectaa6ff846", TestPermissionsRequestResource = new TestPermissionsRequest(), }; TestPermissionsResponse expectedResponse = new TestPermissionsResponse { Permissions = { "permissions535a2741", }, }; mockGrpcClient.Setup(x => x.TestIamPermissionsAsync(request, moq::It.IsAny<grpccore::CallOptions>())).Returns(new grpccore::AsyncUnaryCall<TestPermissionsResponse>(stt::Task.FromResult(expectedResponse), null, null, null, null)); NetworkEndpointGroupsClient client = new NetworkEndpointGroupsClientImpl(mockGrpcClient.Object, null); TestPermissionsResponse responseCallSettings = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, gaxgrpc::CallSettings.FromCancellationToken(st::CancellationToken.None)); xunit::Assert.Same(expectedResponse, responseCallSettings); TestPermissionsResponse responseCancellationToken = await client.TestIamPermissionsAsync(request.Project, request.Zone, request.Resource, request.TestPermissionsRequestResource, st::CancellationToken.None); xunit::Assert.Same(expectedResponse, responseCancellationToken); mockGrpcClient.VerifyAll(); } } }
#region Foreign-License // .Net40 Kludge #endregion #if !CLR4 using System.Runtime.InteropServices; using System.Security; using System.Collections; namespace System.Runtime.CompilerServices { /* * Description: Compiler support for runtime-generated "object fields." * * Lets DLR and other language compilers expose the ability to attach arbitrary "properties" to instanced managed objects at runtime. * * We expose this support as a dictionary whose keys are the instanced objects and the values are the "properties." * * Unlike a regular dictionary, ConditionalWeakTables will not keep keys alive. * * * Lifetimes of keys and values: * * Inserting a key and value into the dictonary will not prevent the key from dying, even if the key is strongly reachable * from the value. * * Prior to ConditionalWeakTable, the CLR did not expose the functionality needed to implement this guarantee. * * Once the key dies, the dictionary automatically removes the key/value entry. * * * Relationship between ConditionalWeakTable and Dictionary: * * ConditionalWeakTable mirrors the form and functionality of the IDictionary interface for the sake of api consistency. * * Unlike Dictionary, ConditionalWeakTable is fully thread-safe and requires no additional locking to be done by callers. * * ConditionalWeakTable defines equality as Object.ReferenceEquals(). ConditionalWeakTable does not invoke GetHashCode() overrides. * * It is not intended to be a general purpose collection and it does not formally implement IDictionary or * expose the full public surface area. * * * Thread safety guarantees: * * ConditionalWeakTable is fully thread-safe and requires no additional locking to be done by callers. * * * OOM guarantees: * * Will not corrupt unmanaged handle table on OOM. No guarantees about managed weak table consistency. Native handles reclamation * may be delayed until appdomain shutdown. */ [ComVisible(false)] #if !COREINTERNAL public #endif sealed class ConditionalWeakTable<TKey, TValue> where TKey : class where TValue : class { private int[] _buckets; // _buckets[hashcode & _buckets.Length] contains index of first entry in bucket (-1 if empty) private Entry[] _entries; private int _freeList; // -1 = empty, else index of first unused Entry private const int _initialCapacity = 5; private bool _invalid; // flag detects if OOM or other background exception threw us out of the lock. private object _lock; // this could be a ReaderWriterLock but CoreCLR does not support RWLocks. public delegate TValue CreateValueCallback(TKey key); [StructLayout(LayoutKind.Sequential)] private struct Entry { // Holds key and value using a weak reference for the key and a strong reference // for the value that is traversed only if the key is reachable without going through the value. public DependentHandle depHnd; public int hashCode; // Cached copy of key's hashcode public int next; // Index of next entry, -1 if last } [SecuritySafeCritical] public ConditionalWeakTable() { _buckets = new int[0]; _entries = new Entry[0]; _freeList = -1; _lock = new object(); // Resize at once (so won't need "if initialized" checks all over) Resize(); } [SecuritySafeCritical] ~ConditionalWeakTable() { // We're just freeing per-appdomain unmanaged handles here. If we're already shutting down the AD, don't bother. // (Despite its name, Environment.HasShutdownStart also returns true if the current AD is finalizing.) if (!Environment.HasShutdownStarted && (_lock != null)) lock (_lock) if (!_invalid) { Entry[] entries = _entries; // Make sure anyone sneaking into the table post-resurrection gets booted before they can damage the native handle table. _invalid = true; _entries = null; _buckets = null; for (int entriesIndex = 0; entriesIndex < entries.Length; entriesIndex++) entries[entriesIndex].depHnd.Free(); } } [SecuritySafeCritical] public void Add(TKey key, TValue value) { if (key == null) throw new ArgumentNullException("key"); lock (_lock) { VerifyIntegrity(); _invalid = true; if (FindEntry(key) != -1) { _invalid = false; throw new ArgumentException("Argument_AddingDuplicate", "key"); } CreateEntry(key, value); _invalid = false; } } [SecurityCritical] private void CreateEntry(TKey key, TValue value) { if (_freeList == -1) Resize(); int hashCode = RuntimeHelpers.GetHashCode(key) & 0x7fffffff; int bucket = hashCode % _buckets.Length; int newEntry = _freeList; _freeList = _entries[newEntry].next; _entries[newEntry].hashCode = hashCode; _entries[newEntry].depHnd = new DependentHandle(key, value); _entries[newEntry].next = _buckets[bucket]; _buckets[bucket] = newEntry; } [SecurityCritical] private int FindEntry(TKey key) { int hashCode = RuntimeHelpers.GetHashCode(key) & 0x7fffffff; for (int entriesIndex = _buckets[hashCode % _buckets.Length]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) if ((_entries[entriesIndex].hashCode == hashCode) && (_entries[entriesIndex].depHnd.GetPrimary() == key)) return entriesIndex; return -1; } // Kludge: CompilerServicesExtensions dependency internal int FindEntryForLazyValueHelper<TLazyKey>(TLazyKey key, bool isValueCreated) { Lazy<TLazyKey> lazy; for (int entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) { var depHnd = _entries[entriesIndex].depHnd; if (depHnd.IsAllocated && ((lazy = (Lazy<TLazyKey>)depHnd.GetPrimary()) != null) && (lazy.IsValueCreated || isValueCreated) && lazy.Value.Equals(key)) return entriesIndex; } return -1; } public TValue GetOrCreateValue(TKey key) { return GetValue(key, (TKey k) => Activator.CreateInstance<TValue>()); } [SecuritySafeCritical] public TValue GetValue(TKey key, CreateValueCallback createValueCallback) { TValue local; if (createValueCallback == null) throw new ArgumentNullException("createValueCallback"); if (TryGetValue(key, out local)) return local; // If we got here, the key is not currently in table. Invoke the callback (outside the lock) to generate the new value for the key. var newValue = createValueCallback(key); lock (_lock) { VerifyIntegrity(); _invalid = true; // Now that we've retaken the lock, must recheck in case we lost a ---- to add the key. if (TryGetValueWorker(key, out local)) { _invalid = false; return local; } // Verified in-lock that we won the ---- to add the key. Add it now. CreateEntry(key, newValue); _invalid = false; return newValue; } } [SecuritySafeCritical] public bool Remove(TKey key) { if (key == null) throw new ArgumentException("key"); lock (_lock) { VerifyIntegrity(); _invalid = true; int hashCode = RuntimeHelpers.GetHashCode(key) & 0x7fffffff; int bucket = hashCode % _buckets.Length; int last = -1; for (int entriesIndex = _buckets[bucket]; entriesIndex != -1; entriesIndex = _entries[entriesIndex].next) { if ((_entries[entriesIndex].hashCode == hashCode) && (_entries[entriesIndex].depHnd.GetPrimary() == key)) { if (last == -1) _buckets[bucket] = _entries[entriesIndex].next; else _entries[last].next = _entries[entriesIndex].next; _entries[entriesIndex].depHnd.Free(); _entries[entriesIndex].next = _freeList; _freeList = entriesIndex; _invalid = false; return true; } last = entriesIndex; } _invalid = false; return false; } } [SecurityCritical] private void Resize() { // Start by assuming we won't resize. int newSize = _buckets.Length; // If any expired keys exist, we won't resize. bool hasExpiredEntries = false; int entriesIndex; for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) if (_entries[entriesIndex].depHnd.IsAllocated && (_entries[entriesIndex].depHnd.GetPrimary() == null)) { hasExpiredEntries = true; break; } if (!hasExpiredEntries) newSize = HashHelpers.GetPrime((_buckets.Length == 0) ? 6 : (_buckets.Length * 2)); // Reallocate both buckets and entries and rebuild the bucket and freelists from scratch. // This serves both to scrub entries with expired keys and to put the new entries in the proper bucket. int newFreeList = -1; int[] newBuckets = new int[newSize]; for (int bucketIndex = 0; bucketIndex < newSize; bucketIndex++) newBuckets[bucketIndex] = -1; var newEntries = new Entry[newSize]; // Migrate existing entries to the new table. for (entriesIndex = 0; entriesIndex < _entries.Length; entriesIndex++) { var depHnd = _entries[entriesIndex].depHnd; if (depHnd.IsAllocated && (depHnd.GetPrimary() != null)) { // Entry is used and has not expired. Link it into the appropriate bucket list. int index = _entries[entriesIndex].hashCode % newSize; newEntries[entriesIndex].depHnd = depHnd; newEntries[entriesIndex].hashCode = _entries[entriesIndex].hashCode; newEntries[entriesIndex].next = newBuckets[index]; newBuckets[index] = entriesIndex; } else { // Entry has either expired or was on the freelist to begin with. Either way insert it on the new freelist. _entries[entriesIndex].depHnd.Free(); newEntries[entriesIndex].depHnd = new DependentHandle(); newEntries[entriesIndex].next = newFreeList; newFreeList = entriesIndex; } } // Add remaining entries to freelist. while (entriesIndex != newEntries.Length) { newEntries[entriesIndex].depHnd = new DependentHandle(); newEntries[entriesIndex].next = newFreeList; newFreeList = entriesIndex; entriesIndex++; } _buckets = newBuckets; _entries = newEntries; _freeList = newFreeList; } [SecuritySafeCritical] public bool TryGetValue(TKey key, out TValue value) { if (key == null) throw new ArgumentException("key"); lock (_lock) { VerifyIntegrity(); return TryGetValueWorker(key, out value); } } [SecurityCritical] private bool TryGetValueWorker(TKey key, out TValue value) { int index = FindEntry(key); if (index != -1) { object primary = null; object secondary = null; _entries[index].depHnd.GetPrimaryAndSecondary(out primary, out secondary); // Now that we've secured a strong reference to the secondary, must check the primary again to ensure it didn't expire // (otherwise, we open a ---- where TryGetValue misreports an expired key as a live key with a null value.) if (primary != null) { value = (TValue)secondary; return true; } } value = default(TValue); return false; } // Kludge: CompilerServicesExtensions dependency [SecurityCritical] public bool TryGetValueWorkerForLazyValueHelper<TLazyKey>(TLazyKey key, out TValue value, bool isValueCreated) { int index = FindEntryForLazyValueHelper(key, isValueCreated); if (index != -1) { object primary = null; object secondary = null; _entries[index].depHnd.GetPrimaryAndSecondary(out primary, out secondary); // Now that we've secured a strong reference to the secondary, must check the primary again to ensure it didn't expire // (otherwise, we open a ---- where TryGetValue misreports an expired key as a live key with a null value.) if (primary != null) { value = (TValue)secondary; return true; } } value = default(TValue); return false; } private void VerifyIntegrity() { if (_invalid) throw new InvalidOperationException(EnvironmentEx2.GetResourceString("CollectionCorrupted")); } } } #endif
// // Copyright (c) 2012-2021 Antmicro // // This file is licensed under the MIT License. // Full license text is available in the LICENSE file. using System; using Antmicro.Migrant.Customization; using System.IO; using System.Reflection; using Antmicro.Migrant.VersionTolerance; using System.Linq; namespace Antmicro.Migrant.Tests { public class TwoDomainsDriver { public TwoDomainsDriver(bool useGeneratedSerializer, bool useGeneratedDeserializer) { settings = new DriverSettings(useGeneratedSerializer, useGeneratedDeserializer, true); // this is just a little hack that allows us to debug TwoDomainTests on one domain // when `PrepareDomains` method is not called; when `PrepareDomains` is called // then these fields are overwritten with proper values testsOnDomain1 = new InnerDriver { Settings = settings }; testsOnDomain2 = testsOnDomain1; } public void PrepareDomains() { var pathBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); foreach (var domain in new[] { "domain1", "domain2" }.Select(x => Path.Combine(pathBase, x))) { Directory.CreateDirectory(domain); foreach(var file in new[] { "Tests.dll", "Migrant.dll" }) { File.Copy(Path.Combine(pathBase, file), Path.Combine(domain, file), true); } } domain1 = AppDomain.CreateDomain("domain1", null, Path.Combine(pathBase, "domain1"), string.Empty, false); domain2 = AppDomain.CreateDomain("domain2", null, Path.Combine(pathBase, "domain2"), string.Empty, false); testsOnDomain1 = (InnerDriver)domain1.CreateInstanceAndUnwrap(typeof(InnerDriver).Assembly.FullName, typeof(InnerDriver).FullName); testsOnDomain2 = (InnerDriver)domain2.CreateInstanceAndUnwrap(typeof(InnerDriver).Assembly.FullName, typeof(InnerDriver).FullName); testsOnDomain1.Settings = settings; testsOnDomain2.Settings = settings; } public void DisposeDomains() { testsOnDomain1 = null; testsOnDomain2 = null; AppDomain.Unload(domain1); AppDomain.Unload(domain2); domain1 = null; domain2 = null; var pathBase = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); Directory.Delete(Path.Combine(pathBase, "domain1"), true); Directory.Delete(Path.Combine(pathBase, "domain2"), true); } public bool SerializeAndDeserializeOnTwoAppDomains(DynamicType domainOneType, DynamicType domainTwoType, VersionToleranceLevel vtl, bool allowGuidChange = true) { testsOnDomain1.CreateInstanceOnAppDomain(domainOneType); testsOnDomain2.CreateInstanceOnAppDomain(domainTwoType); var bytes = testsOnDomain1.SerializeOnAppDomain(); try { testsOnDomain2.DeserializeOnAppDomain(bytes, settings.GetSettings(allowGuidChange ? vtl | VersionToleranceLevel.AllowGuidChange : vtl)); return true; } catch (VersionToleranceException) { return false; } } protected DriverSettings settings; protected InnerDriver testsOnDomain1; protected InnerDriver testsOnDomain2; private AppDomain domain1; private AppDomain domain2; } public class DriverSettings : MarshalByRefObject { public DriverSettings(bool useGeneratedSerializer, bool useGeneratedDeserializer, bool useStamping) { this.useGeneratedDeserializer = useGeneratedDeserializer; this.useGeneratedSerializer = useGeneratedSerializer; this.useStamping = useStamping; } public Settings GetSettings(VersionToleranceLevel level = 0) { return new Settings(useGeneratedSerializer ? Method.Generated : Method.Reflection, useGeneratedDeserializer ? Method.Generated : Method.Reflection, level, disableTypeStamping: !useStamping); } public Settings GetSettingsAllowingGuidChange(VersionToleranceLevel level = 0) { return GetSettings(level | VersionToleranceLevel.AllowGuidChange); } private bool useGeneratedSerializer; private bool useGeneratedDeserializer; private bool useStamping; } public class InnerDriver : MarshalByRefObject { public InnerDriver() { DynamicType.prefix = AppDomain.CurrentDomain.FriendlyName; } public void CreateInstanceOnAppDomain(DynamicType type, Version version = null) { obj = type.Instantiate(version); } public void DeserializeOnAppDomain(byte[] data, Settings settings) { var stream = new MemoryStream(data); var deserializer = new Serializer(settings); obj = deserializer.Deserialize<object>(stream); } public void SetValueOnAppDomain(string className, string fieldName, object value) { var field = FindClass(className).GetField(fieldName); field.SetValue(obj, value); } public void SetValueOnAppDomain(string fieldName, object value) { SetValueOnAppDomainInner(obj, fieldName, value); } private object SetValueOnAppDomainInner(object o, string fieldName, object value) { var elements = fieldName.Split(new[] { '.' }, 2); if (elements.Length == 1) { var field = o.GetType().GetField(fieldName); field.SetValue(o, value); return o; } else { var field = o.GetType().GetField(elements[0]); var local = field.GetValue(o); local = SetValueOnAppDomainInner(local, elements[1], value); field.SetValue(o, local); return o; } } public object GetValueOnAppDomain(string className, string fieldName) { var field = FindClass(className).GetField(fieldName); return field.GetValue(obj); } public object GetValueOnAppDomain(string fieldName) { var elements = fieldName.Split('.'); FieldInfo field = null; object currentObject = null; foreach (var element in elements) { currentObject = (currentObject == null) ? obj : field.GetValue(currentObject); field = currentObject.GetType().GetField(element); } return field.GetValue(currentObject); } public byte[] SerializeOnAppDomain() { var stream = new MemoryStream(); var serializer = new Serializer(Settings.GetSettings()); serializer.Serialize(obj, stream); return stream.ToArray(); } private Type FindClass(string className) { var currentClass = obj.GetType(); while (currentClass != null && currentClass.Name != className) { currentClass = currentClass.BaseType; } if (currentClass == null) { throw new ArgumentException(className); } return currentClass; } public string Location { get; set; } public DriverSettings Settings { get; set; } protected object obj; } }
using System; using System.Collections; using System.Web.UI.WebControls; using System.IO; using Cuyahoga.Core.Util; using Cuyahoga.Core.Domain; using Cuyahoga.Web.UI; using Cuyahoga.Web.Util; using Cuyahoga.Modules.Forum; using Cuyahoga.Modules.Forum.Domain; using Cuyahoga.Modules.Forum.Utils; using Cuyahoga.Modules.Forum.Web.UI; namespace Cuyahoga.Modules.Forum { /// <summary> /// Summary description for Links. /// </summary> public class ForumViewPost : BaseForumControl { private const int BUFFER_SIZE = 8192; #region Private vars private ForumPost _forumPost; private ForumForum _forumForum; private ForumModule _module; #endregion protected System.Web.UI.WebControls.Repeater rptForumPostRepliesList; protected System.Web.UI.WebControls.Literal lblPostedDate; protected System.Web.UI.WebControls.Label lblUserInfo; protected System.Web.UI.WebControls.Literal lblMessages; protected System.Web.UI.WebControls.Label Label2; protected System.Web.UI.WebControls.HyperLink hplReply; protected System.Web.UI.WebControls.HyperLink hplNewTopic; protected System.Web.UI.WebControls.PlaceHolder phForumTop; protected System.Web.UI.WebControls.PlaceHolder phForumFooter; protected System.Web.UI.WebControls.Label lblTopic; protected System.Web.UI.WebControls.HyperLink hplAuthor; protected System.Web.UI.WebControls.HyperLink hplQuotePost; protected System.Web.UI.WebControls.Label Label1; protected System.Web.UI.WebControls.Literal ltlFileinfo; protected System.Web.UI.WebControls.Panel pnlAttachment; protected System.Web.UI.WebControls.Label lblAttachment; protected System.Web.UI.WebControls.HyperLink hplPostAttachment; protected System.Web.UI.WebControls.LinkButton lbtnRemove; private void Page_Load(object sender, System.EventArgs e) { this._module = base.Module as ForumModule; this._forumForum = this._module.GetForumById(this._module.CurrentForumId); this._module.CurrentForumCategoryId = this._forumForum.CategoryId; this.BindTopFooter(); if(this._forumForum.AllowGuestPost == 1 || this.Page.User.Identity.IsAuthenticated) { this.hplNewTopic.Visible = true; this.hplReply.Visible = true; this.hplQuotePost.Visible = true; } else { this.hplNewTopic.Visible = false; this.hplReply.Visible = false; this.hplQuotePost.Visible = false; } if(!this.IsPostBack) { if(this._module.DownloadId != 0) { this.DownloadCurrentFile(); } this.BindLinks(); this.BindForumPost(); this.BindForumPostReplies(); this.LocalizeControls(); } } private void BindTopFooter() { ForumTop tForumTop; ForumFooter tForumFooter; this._module = this.Module as ForumModule; tForumTop = (ForumTop)this.LoadControl("~/Modules/Forum/ForumTop.ascx"); tForumTop.Module = this._module; this.phForumTop.Controls.Add(tForumTop); tForumFooter = (ForumFooter)this.LoadControl("~/Modules/Forum/ForumFooter.ascx"); tForumFooter.Module = this._module; this.phForumFooter.Controls.Add(tForumFooter); } private void Translate() { string uname = ""; if(this.Page.User.Identity.IsAuthenticated) { Cuyahoga.Core.Domain.User currentUser = Context.User.Identity as Cuyahoga.Core.Domain.User; uname = currentUser.FullName; } else { uname = base.GetText("GUEST"); } } private void BindLinks() { this.hplReply.NavigateUrl = String.Format("{0}/ForumReplyPost/{1}/post/{2}",UrlHelper.GetUrlFromSection(this._module.Section), this._module.CurrentForumId,this._module.CurrentForumPostId); this.hplNewTopic.NavigateUrl = String.Format("{0}/ForumNewPost/{1}",UrlHelper.GetUrlFromSection(this._module.Section), this._module.CurrentForumId); this.hplQuotePost.NavigateUrl = String.Format("{0}/ForumReplyPostQuote/{1}/post/{2}/orig/{3}",UrlHelper.GetUrlFromSection(this._module.Section), this._module.CurrentForumId,this._module.CurrentForumPostId,this._module.CurrentForumPostId); this.hplQuotePost.CssClass = "forum"; } private void BindForumPost() { this._forumPost = this._module.GetForumPostById(this._module.CurrentForumPostId); this._forumPost.Views++; this._module.SaveForumPost(this._forumPost); this.lblTopic.Text = this._forumPost.Topic; if(this._forumPost.UserId == 0) { this.hplAuthor.Text = "Guest"; this.hplAuthor.CssClass = "forum"; this.lblUserInfo.Text = "&nbsp;"; } else { this.hplAuthor.Text = this._forumPost.UserName; this.hplAuthor.NavigateUrl = String.Format("{0}/ForumViewProfile/{1}",UrlHelper.GetUrlFromSection(this._module.Section), this._forumPost.UserId); this.hplAuthor.CssClass = "forum"; this.lblUserInfo.Text = "&nbsp;"; } string msg = this._forumPost.Message; this.lblMessages.Text = this._forumPost.Message; this.lblPostedDate.Text = TimeZoneUtil.AdjustDateToUserTimeZone(this._forumPost.DateCreated, this.Page.User.Identity).ToLongDateString() + " " +TimeZoneUtil.AdjustDateToUserTimeZone(this._forumPost.DateCreated, this.Page.User.Identity).ToLongTimeString(); if(this._forumPost.AttachmentId != 0) { ForumFile fFile = this._module.GetForumFileById(this._forumPost.AttachmentId); this.pnlAttachment.Visible = true; this.hplPostAttachment.NavigateUrl = String.Format("{0}/ForumViewPost/{1}/PostId/{2}/Download/{3}",UrlHelper.GetUrlFromSection(this._module.Section), this._forumPost.ForumId,this._forumPost.Id,this._forumPost.AttachmentId); this.hplPostAttachment.Text = fFile.OrigFileName; this.hplPostAttachment.ToolTip = String.Format("{0} - {1} bytes",fFile.OrigFileName,fFile.FileSize); this.ltlFileinfo.Text = String.Format(GetText("attachinfo"),fFile.FileSize,fFile.DlCount); } User cuyahogaUser = this.Page.User.Identity as User; if (cuyahogaUser != null) { if (cuyahogaUser.CanEdit(this._module.Section)) { this.lbtnRemove.Visible = true; } } } private void BindForumPostReplies() { // Bind the link HyperLink hpl = (HyperLink)this.FindControl("hplNewTopic"); if(hpl != null) { hpl.Text = "New topic"; hpl.NavigateUrl = String.Format("{0}/ForumNewPost/{1}",UrlHelper.GetUrlFromSection(this._module.Section), this._module.CurrentForumId); hpl.CssClass = "forum"; } this.rptForumPostRepliesList.ItemDataBound += new System.Web.UI.WebControls.RepeaterItemEventHandler(this.rptForumPostRepliesList_ItemDataBound); this.rptForumPostRepliesList.DataSource = this._module.GetAllForumPostReplies(this._module.CurrentForumPostId); this.rptForumPostRepliesList.DataBind(); } #region Web Form Designer generated code override protected void OnInit(EventArgs e) { // // CODEGEN: This call is required by the ASP.NET Web Form Designer. // InitializeComponent(); base.OnInit(e); } /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.Load += new System.EventHandler(this.Page_Load); } #endregion private void rptForumPostRepliesList_ItemDataBound(object sender, System.Web.UI.WebControls.RepeaterItemEventArgs e) { if (e.Item.ItemType == ListItemType.Item || e.Item.ItemType == ListItemType.AlternatingItem) { ForumPost fPost = e.Item.DataItem as ForumPost; // Attachement ?? if(fPost.AttachmentId != 0) { Panel replyPanel = (Panel)e.Item.FindControl("pnlReplyAttachment"); if(replyPanel != null) { replyPanel.Visible = true; ForumFile fFile = this._module.GetForumFileById(fPost.AttachmentId); HyperLink hplReplyAttachment = (HyperLink)e.Item.FindControl("hplReplyttachment"); hplReplyAttachment.NavigateUrl = String.Format("{0}/ForumViewPost/{1}/PostId/{2}/Download/{3}",UrlHelper.GetUrlFromSection(this._module.Section), fPost.ForumId,fPost.Id,fPost.AttachmentId); hplReplyAttachment.Text = fFile.OrigFileName; hplReplyAttachment.ToolTip = String.Format("{0} - {1} bytes",fFile.OrigFileName,fFile.FileSize); Literal ltlReplyFileinfo = (Literal)e.Item.FindControl("ltlReplyFileinfo"); ltlReplyFileinfo.Text = String.Format(GetText("attachinfo"),fFile.FileSize,fFile.DlCount); } } User cuyahogaUser = this.Page.User.Identity as User; if (cuyahogaUser != null) { if (cuyahogaUser.CanEdit(this._module.Section)) { e.Item.FindControl("lbtnRemove").Visible = true; } } } } private void rptForumPostRepliesList_ItemCommand(object source, System.Web.UI.WebControls.RepeaterCommandEventArgs e) { } public string GetPostedDate(object o) { ForumPost tPost = o as ForumPost; return TimeZoneUtil.AdjustDateToUserTimeZone(tPost.DateCreated, this.Page.User.Identity).ToLongDateString() + " " +TimeZoneUtil.AdjustDateToUserTimeZone(tPost.DateCreated, this.Page.User.Identity).ToLongTimeString(); } public string GetMessage(object o) { ForumPost tPost = o as ForumPost; return tPost.Message; } public string GetUserProfileLink(object o) { ForumPost tPost = o as ForumPost; if(tPost.UserId != 0) { return String.Format("<a href=\"{0}/ForumViewProfile/{1}\" class=\"forum\">{2}</a>",UrlHelper.GetUrlFromSection(this._module.Section),tPost.UserId,tPost.UserName); } else { return String.Format("<a href=\"#\" class=\"forum\">{0}</a>",tPost.UserName); } } public string GetQuoteLink(object o) { ForumPost tPost = o as ForumPost; if(this._forumForum.AllowGuestPost == 1 || this.Page.User.Identity.IsAuthenticated) { return String.Format("<a class=\"forum\" href=\"{0}/ForumReplyPostQuote/{1}/post/{2}/orig/{3}\">" + base.GetText("hplQuotePost") + "</a>",UrlHelper.GetUrlFromSection(this._module.Section), this._module.CurrentForumId,tPost.Id,this._module.CurrentForumPostId); } else { return "&nbsp;"; } } public string GetForumPostId(object o) { ForumPost tPost = o as ForumPost; return tPost.Id.ToString(); } private void DownloadCurrentFile() { //Response.End(); ForumFile file = this._module.GetForumFileById(this._module.DownloadId); //if (file.IsDownloadAllowed(this.Page.User.Identity)) { string physicalFilePath = file.ForumFileName; if (System.IO.File.Exists(physicalFilePath)) { Stream fileStream = null; try { byte[] buffer = new byte[BUFFER_SIZE]; // Open the file. fileStream = new System.IO.FileStream(physicalFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read, System.IO.FileShare.Read); // Total bytes to read: long dataToRead = fileStream.Length; // Support for resuming downloads long position = 0; if (Request.Headers["Range"] != null) { Response.StatusCode = 206; Response.StatusDescription = "Partial Content"; position = long.Parse(Request.Headers["Range"].Replace("bytes=", "").Replace("-", "")); } if (position != 0) { Response.AddHeader("Content-Range", "bytes " + position.ToString() + "-" + ((long)(dataToRead - 1)).ToString() + "/" + dataToRead.ToString()); } Response.ContentType = file.ContentType; Response.AppendHeader("Content-Disposition", "attachment; filename=" + file.OrigFileName); // The content length depends on the amount that is already transfered in an earlier request. Response.AppendHeader("Content-Length", (fileStream.Length - position).ToString()); // Stream the actual content bool isInterrupted = false; while (dataToRead > 0 && ! isInterrupted) { // Verify that the client is connected. if (Response.IsClientConnected) { // Read the data in buffer. int length = fileStream.Read(buffer, 0, BUFFER_SIZE); // Write the data to the current output stream. Response.OutputStream.Write(buffer, 0, length); // Flush the data to the HTML output. Response.Flush(); buffer = new byte[BUFFER_SIZE]; dataToRead = dataToRead - length; } else { //prevent infinite loop if user disconnects isInterrupted = true; } } // Only update download statistics if the download is succeeded. if (! isInterrupted) { file.DlCount++; this._module.SaveForumFile(file); } } finally { if (fileStream != null) { fileStream.Close(); } Response.End(); } } else { throw new Exception("The physical file was not found on the server."); } } //else //{ // throw new Exception("You are not allowed to download the file."); //} } protected void lbtnRemove_Click(object sender, EventArgs e) { LinkButton lbtnRemoveTemp = (LinkButton)sender; if (!lbtnRemoveTemp.Parent.GetType().Equals(typeof(RepeaterItem)) ) { foreach (RepeaterItem item in this.rptForumPostRepliesList.Items) { LinkButton lbtnRemoveTemp2 = (LinkButton)item.FindControl("lbtnRemove"); ForumPost postTemp = this._module.GetForumPostById(int.Parse(lbtnRemoveTemp2.CommandArgument)); if (postTemp.AttachmentId != 0) { ForumFile fFile = this._module.GetForumFileById(postTemp.AttachmentId); this._module.DeleteForumFile(fFile); } this._module.DeleteForumPost(postTemp); } this._forumPost = this._module.GetForumPostById(this._module.CurrentForumPostId); if (this._forumPost.AttachmentId != 0) { ForumFile fFile = this._module.GetForumFileById(this._forumPost.AttachmentId); this._module.DeleteForumFile(fFile); } this._module.DeleteForumPost(this._forumPost); Response.Redirect(String.Format("{0}/ForumView/{1}", UrlHelper.GetUrlFromSection(base.ForumModule.Section), base.ForumModule.CurrentForumId)); } else { ForumPost post = this._module.GetForumPostById(int.Parse(lbtnRemoveTemp.CommandArgument)); if (post.AttachmentId != 0) { ForumFile fFile = this._module.GetForumFileById(post.AttachmentId); this._module.DeleteForumFile(fFile); } this._module.DeleteForumPost(post); Response.Redirect(String.Format("{0}/ForumViewPost/{1}/PostId/{2}", UrlHelper.GetUrlFromSection(base.ForumModule.Section), base.ForumModule.CurrentForumId, base.ForumModule.CurrentForumPostId)); } } } }
using Android.Content; using Android.Graphics; using Android.OS; using Android.Runtime; using Android.Util; using Android.Views; using System; using System.Reactive.Linq; using System.Reactive.Subjects; using Toggl.Core.Analytics; using Toggl.Droid.Extensions; using Toggl.Droid.Helper; using Toggl.Droid.Views.EditDuration.Shapes; using Toggl.Shared; using Toggl.Shared.Extensions; using static Toggl.Shared.Math; using Color = Android.Graphics.Color; using Math = System.Math; using static Toggl.Core.UI.Helper.Colors.EditDuration.Wheel; using System.Linq; namespace Toggl.Droid.Views.EditDuration { [Register("toggl.droid.views.WheelForegroundView")] public class WheelForegroundView : View { private readonly Color capBackgroundColor = Color.White; private readonly Color capBorderColor = Color.ParseColor("#cecece"); private readonly Color capIconColor = Color.ParseColor("#328fff"); private float radius; private float wheelHandleDotIndicatorRadius; private float wheelHandleDotIndicatorDistanceToCenter; private float extendedRadiusMultiplier = 1.5f; private float arcWidth; private float capWidth; private float capBorderStrokeWidth; private float capShadowWidth; private int capIconSize; private int vibrationDurationInMilliseconds = 5; private int vibrationAmplitude = 5; private PointF startTimePosition = new PointF(); private PointF endTimePosition = new PointF(); private PointF center; private PointF touchInteractionPointF = new PointF(); private RectF bounds; private Vibrator hapticFeedbackProvider; private DateTimeOffset startTime; private DateTimeOffset endTime; private bool isRunning; private double startTimeAngle; private double endTimeAngle; private double endPointsRadius; private bool isDragging; private WheelUpdateType updateType; private double editBothAtOnceStartTimeAngleOffset; private int numberOfFullLoops => (int)((EndTime - StartTime).TotalMinutes / MinutesInAnHour); private bool isFullCircle => numberOfFullLoops >= 1; private readonly Lazy<Color[]> rainbowColors = new Lazy<Color[]>(() => Rainbow .Select(color => ActiveTheme.Is.DarkTheme ? color.WithAlpha(180) : color) .Select(color => color.ToNativeColor()) .ToArray()); private Color backgroundColor => rainbowColors.Value .GetPingPongIndexedItem(numberOfFullLoops); private Color foregroundColor => rainbowColors.Value .GetPingPongIndexedItem(numberOfFullLoops + 1); private readonly Subject<EditTimeSource> timeEditedSubject = new Subject<EditTimeSource>(); private readonly Subject<DateTimeOffset> startTimeSubject = new Subject<DateTimeOffset>(); private readonly Subject<DateTimeOffset> endTimeSubject = new Subject<DateTimeOffset>(); private Wheel fullWheel; private Arc arc; private Cap endCap; private Cap startCap; private Dot wheelHandleDotIndicator; public IObservable<EditTimeSource> TimeEdited => timeEditedSubject.AsObservable(); public IObservable<DateTimeOffset> StartTimeObservable => startTimeSubject.AsObservable(); public IObservable<DateTimeOffset> EndTimeObservable => endTimeSubject.AsObservable(); public DateTimeOffset MinimumStartTime { get; set; } public DateTimeOffset MaximumStartTime { get; set; } public DateTimeOffset MinimumEndTime { get; set; } public DateTimeOffset MaximumEndTime { get; set; } public DateTimeOffset StartTime { get => startTime; set { if (startTime == value) return; startTime = value.Clamp(MinimumStartTime, MaximumStartTime); if (center == null) return; startTimeAngle = startTime.LocalDateTime.TimeOfDay.ToAngleOnTheDial().ToPositiveAngle(); startTimePosition.UpdateWith(PointOnCircumference(center.ToPoint(), startTimeAngle, endPointsRadius)); arc?.Update(startTimeAngle, endTimeAngle); wheelHandleDotIndicator?.Update(startTimeAngle, endTimeAngle); startTimeSubject.OnNext(startTime); Invalidate(); } } public DateTimeOffset EndTime { get => endTime < startTime ? startTime : endTime; set { if (endTime == value) return; endTime = value.Clamp(MinimumEndTime, MaximumEndTime); if (center == null) return; endTimeAngle = endTime.LocalDateTime.TimeOfDay.ToAngleOnTheDial().ToPositiveAngle(); endTimePosition.UpdateWith(PointOnCircumference(center.ToPoint(), endTimeAngle, endPointsRadius)); arc?.Update(startTimeAngle, endTimeAngle); wheelHandleDotIndicator?.Update(startTimeAngle, endTimeAngle); endTimeSubject.OnNext(endTime); Invalidate(); } } public bool IsRunning { get => isRunning; set { if (isRunning == value) return; isRunning = value; Invalidate(); } } #region Constructors protected WheelForegroundView(IntPtr javaReference, JniHandleOwnership transfer) : base(javaReference, transfer) { } public WheelForegroundView(Context context) : base(context) { init(); } public WheelForegroundView(Context context, IAttributeSet attrs) : base(context, attrs) { init(); } public WheelForegroundView(Context context, IAttributeSet attrs, int defStyleAttr) : base(context, attrs, defStyleAttr) { init(); } public WheelForegroundView(Context context, IAttributeSet attrs, int defStyleAttr, int defStyleRes) : base(context, attrs, defStyleAttr, defStyleRes) { init(); } private void init() { MinimumStartTime = DateTimeOffset.MinValue; MaximumStartTime = DateTimeOffset.Now; MinimumEndTime = DateTimeOffset.Now; MaximumEndTime = DateTimeOffset.MaxValue; startTime = DateTimeOffset.Now; endTime = DateTimeOffset.Now; arcWidth = 8.DpToPixels(Context); capWidth = 28.DpToPixels(Context); capIconSize = 18.DpToPixels(Context); capShadowWidth = 2.DpToPixels(Context); capBorderStrokeWidth = 1.DpToPixels(Context); wheelHandleDotIndicatorRadius = 2.DpToPixels(Context); hapticFeedbackProvider = (Vibrator)Context.GetSystemService(Context.VibratorService); } #endregion protected override void OnLayout(bool changed, int left, int top, int right, int bottom) { base.OnLayout(changed, left, top, right, bottom); radius = Width * 0.5f; center = new PointF(radius, radius); bounds = new RectF(capWidth, capWidth, Width - capWidth, Width - capWidth); endPointsRadius = radius - capWidth; wheelHandleDotIndicatorDistanceToCenter = radius - capWidth / 2f; startTimeAngle = startTime.LocalDateTime.TimeOfDay.ToAngleOnTheDial().ToPositiveAngle(); startTimePosition.UpdateWith(PointOnCircumference(center.ToPoint(), startTimeAngle, endPointsRadius)); endTimeAngle = endTime.LocalDateTime.TimeOfDay.ToAngleOnTheDial().ToPositiveAngle(); endTimePosition.UpdateWith(PointOnCircumference(center.ToPoint(), endTimeAngle, endPointsRadius)); setupDrawingDelegates(); arc.Update(startTimeAngle, endTimeAngle); wheelHandleDotIndicator.Update(startTimeAngle, endTimeAngle); Invalidate(); } protected override void OnDraw(Canvas canvas) { base.OnDraw(canvas); updateUIElements(); fullWheel.OnDraw(canvas); arc.OnDraw(canvas); wheelHandleDotIndicator.OnDraw(canvas); endCap.OnDraw(canvas); startCap.OnDraw(canvas); } private void setupDrawingDelegates() { fullWheel = new Wheel(bounds, arcWidth, backgroundColor); arc = new Arc(bounds, arcWidth, foregroundColor); var endCapBitmap = Context.GetVectorDrawable(Resource.Drawable.ic_stop).ToBitmap(capIconSize, capIconSize); var startCapBitmap = Context.GetVectorDrawable(Resource.Drawable.ic_play).ToBitmap(capIconSize, capIconSize); endCap = createCapWithIcon(endCapBitmap); startCap = createCapWithIcon(startCapBitmap); wheelHandleDotIndicator = new Dot(center.ToPoint(), wheelHandleDotIndicatorDistanceToCenter, wheelHandleDotIndicatorRadius, capIconColor); } private Cap createCapWithIcon(Bitmap iconBitmap) { return new Cap(radius: capWidth / 2f, arcWidth: arcWidth, capColor: capBackgroundColor, capBorderColor: capBorderColor, foregroundColor: foregroundColor, capBorderStrokeWidth: capBorderStrokeWidth, icon: iconBitmap, iconColor: capIconColor, shadowWidth: capShadowWidth); } private void updateUIElements() { startCap.SetPosition(startTimePosition); startCap.SetForegroundColor(foregroundColor); endCap.SetPosition(endTimePosition); endCap.SetForegroundColor(foregroundColor); endCap.SetShowOnlyBackground(IsRunning); fullWheel.SetFillColor(backgroundColor); fullWheel.SetHidden(!isFullCircle); arc.SetFillColor(foregroundColor); } #region Touch interaction public override bool OnTouchEvent(MotionEvent motionEvent) { switch (motionEvent.Action) { case MotionEventActions.Down: touchInteractionPointF.UpdateWith(motionEvent); touchesBegan(touchInteractionPointF); return true; case MotionEventActions.Up: touchesEnded(); return true; case MotionEventActions.Move: touchInteractionPointF.UpdateWith(motionEvent); touchesMoved(touchInteractionPointF); return true; case MotionEventActions.Cancel: touchesCancelled(); return base.OnTouchEvent(motionEvent); } return base.OnTouchEvent(motionEvent); } private void touchesBegan(PointF position) { if (isValid(position)) { isDragging = true; } } private void touchesMoved(PointF position) { if (isDragging == false) return; double previousAngle; switch (updateType) { case WheelUpdateType.EditStartTime: previousAngle = startTimeAngle; break; case WheelUpdateType.EditEndTime: previousAngle = endTimeAngle; break; default: previousAngle = startTimeAngle + editBothAtOnceStartTimeAngleOffset; break; } var currentAngle = AngleBetween(position.ToPoint(), center.ToPoint()); var angleChange = currentAngle - previousAngle; while (angleChange < -Math.PI) angleChange += FullCircle; while (angleChange > Math.PI) angleChange -= FullCircle; var timeChange = angleChange.AngleToTime(); updateEditedTime(timeChange); } private void touchesCancelled() { finishTouchEditing(); } private void touchesEnded() { finishTouchEditing(); switch (updateType) { case WheelUpdateType.EditStartTime: timeEditedSubject.OnNext(EditTimeSource.WheelStartTime); break; case WheelUpdateType.EditEndTime: timeEditedSubject.OnNext(EditTimeSource.WheelEndTime); break; default: timeEditedSubject.OnNext(EditTimeSource.WheelBothTimes); break; } } private bool isValid(PointF position) { var intention = determineTapIntention(position); if (!intention.HasValue) return false; updateType = intention.Value; if (updateType == WheelUpdateType.EditBothAtOnce) { editBothAtOnceStartTimeAngleOffset = AngleBetween(position.ToPoint(), center.ToPoint()) - startTimeAngle; } return true; } private WheelUpdateType? determineTapIntention(PointF position) { if (touchesStartCap(position)) { return WheelUpdateType.EditStartTime; } if (!IsRunning && touchesEndCap(position)) { return WheelUpdateType.EditEndTime; } if (touchesStartCap(position, extendedRadius: true)) { return WheelUpdateType.EditStartTime; } if (!IsRunning && touchesEndCap(position, extendedRadius: true)) { return WheelUpdateType.EditEndTime; } if (!IsRunning && isOnTheWheelBetweenStartAndStop(position)) { return WheelUpdateType.EditBothAtOnce; } return null; } private bool touchesStartCap(PointF position, bool extendedRadius = false) => isCloseEnough(position, startTimePosition, calculateCapRadius(extendedRadius)); private bool touchesEndCap(PointF position, bool extendedRadius = false) => isCloseEnough(position, endTimePosition, calculateCapRadius(extendedRadius)); private float calculateCapRadius(bool extendedRadius) => (extendedRadius ? extendedRadiusMultiplier : 1) * (capWidth / 2); private static bool isCloseEnough(PointF tapPosition, PointF endPoint, float radius) => DistanceSq(tapPosition.ToPoint(), endPoint.ToPoint()) <= radius * radius; private bool isOnTheWheelBetweenStartAndStop(PointF point) { var distanceFromCenterSq = DistanceSq(center.ToPoint(), point.ToPoint()); if (distanceFromCenterSq < capWidth * capWidth || distanceFromCenterSq > radius * radius) { return false; } var angle = AngleBetween(point.ToPoint(), center.ToPoint()); return isFullCircle || angle.IsBetween(startTimeAngle, endTimeAngle); } private void updateEditedTime(TimeSpan diff) { var giveFeedback = false; var duration = EndTime - StartTime; if (updateType == WheelUpdateType.EditStartTime || updateType == WheelUpdateType.EditBothAtOnce) { var nextStartTime = (StartTime + diff).RoundToClosestMinute(); giveFeedback = nextStartTime != StartTime; StartTime = nextStartTime; } if (updateType == WheelUpdateType.EditEndTime) { var nextEndTime = (EndTime + diff).RoundToClosestMinute(); giveFeedback = nextEndTime != EndTime; EndTime = nextEndTime; } if (updateType == WheelUpdateType.EditBothAtOnce) { EndTime = StartTime + duration; } if (giveFeedback) { vibrate(); } } private void vibrate() { hapticFeedbackProvider?.ActivateVibration(vibrationDurationInMilliseconds, vibrationAmplitude); } private void finishTouchEditing() { isDragging = false; } #endregion private enum WheelUpdateType { EditStartTime, EditEndTime, EditBothAtOnce } } }
//----------------------------------------------------------------------------- //Cortex //Copyright (c) 2010-2015, Joshua Scoggins //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 Cortex 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 Joshua Scoggins BE LIABLE FOR ANY //DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES //(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; //LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND //ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT //(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS //SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. //----------------------------------------------------------------------------- using System; using System.Reflection; using System.Text; using System.Runtime; using System.Collections.Generic; using System.Linq; using Cortex; using Cortex.Grammar; namespace Cortex.Parsing { public static partial class LR1ParsingTableEntryActionExtensions { public static TableCellAction Parse(string input) { if(input.StartsWith("err")) return TableCellAction.Error; else if(input.StartsWith("acc")) return TableCellAction.Accept; else if(input[0] == 's') return TableCellAction.Shift; else if(input[0] == 'r') return TableCellAction.Reduce; else throw new Exception("Invalid input given"); } public static bool TryParse(string input, out TableCellAction action) { try { action = Parse(input); return true; } catch(Exception) { action = TableCellAction.Error; return false; } } } public class LR1ParsingTableCell { public static readonly LR1ParsingTableCell DEFAULT_ERROR = new LR1ParsingTableCell(TableCellAction.Error); public int TargetState { get; set; } public TableCellAction Action { get; set; } public static LR1ParsingTableCell Parse(string input) { var result = LR1ParsingTableEntryActionExtensions.Parse(input); switch(result) { case TableCellAction.Shift: case TableCellAction.Reduce: return new LR1ParsingTableCell(result, int.Parse(input.Substring(1))); default: return new LR1ParsingTableCell(result); } } public LR1ParsingTableCell(string input) { Action = LR1ParsingTableEntryActionExtensions.Parse(input); switch(Action) { case TableCellAction.Shift: case TableCellAction.Reduce: TargetState = int.Parse(input.Substring(1)); break; default: TargetState = 0; break; } } public LR1ParsingTableCell() { } public LR1ParsingTableCell(TableCellAction action) : this(action, 0) { } public LR1ParsingTableCell(TableCellAction action, int targetState) { Action = action; TargetState = targetState; } public override bool Equals(object other) { LR1ParsingTableCell cell0 = (LR1ParsingTableCell)other; return cell0.Action.Equals(Action) && TargetState == cell0.TargetState; } public override int GetHashCode() { return Action.GetHashCode() + TargetState.GetHashCode(); } public override string ToString() { string fmt = (TargetState == -1) ? "{0}" : "{0}{1}"; return string.Format(fmt, TranslateAction(Action), TargetState); } private string TranslateAction(TableCellAction act) { switch(act) { case TableCellAction.Shift: return "s"; case TableCellAction.Reduce: return "r"; case TableCellAction.Accept: return "acc"; case TableCellAction.Error: return "err"; default: return ""; } } public static explicit operator LR1ParsingTableCell(string input) { return LR1ParsingTableCell.Parse(input); } } //TODO: Rewrite this to use a Dictionary<string, List<T>> instead //of the current List<Dictionary<string, T>> public abstract class GenericTable<T> : List<Dictionary<string, T>> { public T this[int i, string a] { get { return this[i][a]; } } public void Add(int state) { if(state >= Count) Add(new Dictionary<string, T>()); } public void AddRange(int state, IEnumerable<string> symbols) { foreach(var v in symbols) Add(state, v); } protected virtual T GetDefaultValue() { return default(T); } public void Add(int state, string symbol) { Add(state, symbol, GetDefaultValue()); } public void Add(int state, string symbol, T cell) { Add(state); var st = this[state]; st[symbol] = cell; } public void CleanUp() { int oldCount = Count; var rev = GetSimplistics(); Clear(); Dictionary<string, T>[] collec = new Dictionary<string, T>[oldCount]; foreach(var v in rev) { var dict = v.Key; var list = v.Value; foreach(var l in list) collec[l] = dict; } AddRange(collec); Console.WriteLine("rev.Count = {0}", rev.Count); } public Dictionary<Dictionary<string, T>, List<int>> GetSimplistics() { Dictionary<Dictionary<string, T>, List<int>> rev = new Dictionary<Dictionary<string, T>, List<int>>( new DictionaryEqualityComparison()); for(int i = 0; i < Count; i++) { var dict = this[i]; if(rev.ContainsKey(dict)) rev[dict].Add(i); else rev[dict] = new List<int> { i }; } return rev; } public abstract string MakeQuine(Dictionary<string,string> symbolTable); class DictionaryEqualityComparison : EqualityComparer<Dictionary<string, T>> { public override bool Equals(Dictionary<string, T> a, Dictionary<string, T> b) { if(a.Count == b.Count) { var total = from x in a join y in b on x.Key equals y.Key where x.Value.Equals(y.Value) select x; return total.Count() == a.Count; } else return false; } public override int GetHashCode(Dictionary<string, T> dict) { long value = 0L; foreach(var v in dict) value += v.Key.GetHashCode() + v.Value.GetHashCode(); return (int)value; } } } public class LR1ParsingTable : GenericTable<LR1ParsingTableCell> { protected override LR1ParsingTableCell GetDefaultValue() { return LR1ParsingTableCell.DEFAULT_ERROR; } public override string MakeQuine(Dictionary<string,string> symbolTable) { int size = Count; var simp = GetSimplistics(); Dictionary<string, string> cellNames = new Dictionary<string, string>(); Dictionary<Dictionary<string, LR1ParsingTableCell>, string> binding = new Dictionary<Dictionary<string, LR1ParsingTableCell>, string>(); StringBuilder cellCreation = new StringBuilder(); StringBuilder initCells = new StringBuilder(); initCells.AppendLine("static void InitCells()"); initCells.AppendLine("{"); foreach(var r in this) { foreach(var v in r) { string oName = v.Value.ToString(); string name = string.Format("cell_{0}", oName); if(!cellNames.ContainsKey(v.Value.ToString())) { cellNames[v.Value.ToString()] = name; cellCreation.AppendFormat("static LR1ParsingTableCell {0};", name); initCells.AppendFormat("{0} = new LR1ParsingTableCell(\"{1}\");\n", name, oName); } } } initCells.AppendLine("}"); //TODO: Break up each table into a separte function // to get around the "method too complex" error StringBuilder methodMaker = new StringBuilder(); StringBuilder tableCreation = new StringBuilder(); StringBuilder initGroupsFunction = new StringBuilder(); initGroupsFunction.AppendLine("static void InitGroups()"); initGroupsFunction.AppendLine("{"); int index = 0; foreach(var v in simp) { var dict = v.Key; string name = string.Format("tab{0}", index); binding[dict] = name; tableCreation.AppendFormat("static Dictionary<string, LR1ParsingTableCell> {0};\n ", name); initGroupsFunction.AppendLine( MakeMethod(name, methodMaker, symbolTable, cellNames, dict)); index++; } initGroupsFunction.AppendLine("}"); StringBuilder sb = new StringBuilder(); sb.AppendLine("static Tables()"); sb.AppendLine("{"); sb.AppendLine("InitCells();"); sb.AppendLine("InitGroups();"); sb.AppendLine("InitParseTable();"); sb.AppendLine("}"); sb.Append(methodMaker.ToString()); sb.Append(initGroupsFunction.ToString()); sb.Append(initCells.ToString()); sb.Append(cellCreation.ToString()); sb.Append(tableCreation.ToString()); sb.Append("public static LR1ParsingTable parseTable;\n"); sb.AppendLine("static void InitParseTable() {\n"); sb.Append("parseTable = new LR1ParsingTable \n{\n"); string[] result = new string[size]; //for(int i = 0; i < simp.Count; i++) foreach(var s in simp) { string name = binding[s.Key]; foreach(var v in s.Value) result[v] = name; } for(int j = 0; j < result.Length; j++) { sb.AppendFormat("{0},\n",result[j]); } sb.Append("\n};\n"); sb.Append("}\n"); return sb.ToString(); } private string MakeMethod( string name, StringBuilder fn, Dictionary<string,string> symbolTable, Dictionary<string,string> cellNames, Dictionary<string, LR1ParsingTableCell> dict) { fn.AppendFormat("static void init{0}() ", name); fn.Append("{ \n"); fn.AppendFormat("{0} = new Dictionary<string, LR1ParsingTableCell>", name); fn.Append("{\n"); foreach(var q in dict) { string _name = symbolTable[q.Key]; //Console.WriteLine("Looking for {0}", q.Value.ToString()); string val = cellNames[q.Value.ToString()]; fn.AppendFormat("{0} {1}, {2} {3},\n", "{", _name, val, "}"); } fn.Append("};\n}\n"); return string.Format("init{0}();", name); } } public class LR1GotoTable : GenericTable<int> { protected override int GetDefaultValue() { return 0; } public override string MakeQuine(Dictionary<string,string> symbolTable) { int size = Count; var simp = GetSimplistics(); Dictionary<string, string> cellNames = new Dictionary<string, string>(); Dictionary<Dictionary<string, int>, string> binding = new Dictionary<Dictionary<string, int>, string>(); StringBuilder cellCreation = new StringBuilder(); foreach(var r in this) { foreach(var v in r) { string oName = (v.Value == -1) ? "NegativeOne" : v.Value.ToString(); string name = string.Format("id_{0}", oName); if(!cellNames.ContainsKey(oName)) { cellNames[oName] = name; cellCreation.AppendFormat("public static readonly int {0} = {1};\n", name, oName); } } } StringBuilder tableCreation = new StringBuilder(); int index = 0; foreach(var v in simp) { var dict = v.Key; string name = string.Format("gtab{0}", index); binding[dict] = name; tableCreation.AppendFormat("public static readonly Dictionary<string, int> {0} = ", name); tableCreation.AppendLine("new Dictionary<string, int> {"); foreach(var q in dict) { string sName = string.Format("{0}", q.Key); if(symbolTable.ContainsKey(q.Key)) sName = symbolTable[q.Key]; else { symbolTable[q.Key] = q.Key; cellCreation.AppendFormat("public static readonly string {0} = \"{0}\";\n", q.Key); } string sValue = cellNames[q.Value.ToString()]; tableCreation.AppendFormat("{0} {1}, {2} {3},\n", "{", sName, sValue, "}"); } tableCreation.Append("};\n"); index++; } StringBuilder sb = new StringBuilder(); sb.Append(cellCreation.ToString()); sb.Append(tableCreation.ToString()); sb.Append("public static LR1GotoTable gotoTable = new LR1GotoTable\n{\n"); string[] result = new string[size]; //for(int i = 0; i < simp.Count; i++) foreach(var s in simp) { string name = binding[s.Key]; foreach(var v in s.Value) result[v] = name; } for(int j = 0; j < result.Length; j++) { sb.AppendFormat("{0},\n",result[j]); } sb.Append("\n};"); return sb.ToString(); } } }
// Copyright 2009 The Noda Time Authors. All rights reserved. // Use of this source code is governed by the Apache License 2.0, // as found in the LICENSE.txt file. using JetBrains.Annotations; using NodaTime.Annotations; using NodaTime.Text; using NodaTime.Utility; using System; using System.ComponentModel; using System.Globalization; using System.Runtime.CompilerServices; using System.Xml; using System.Xml.Schema; using System.Xml.Serialization; using static NodaTime.NodaConstants; namespace NodaTime { /// <summary> /// An offset from UTC in seconds. A positive value means that the local time is /// ahead of UTC (e.g. for Europe); a negative value means that the local time is behind /// UTC (e.g. for America). /// </summary> /// <remarks> /// <para> /// Offsets are always in the range of [-18, +18] hours. (Note that the ends are inclusive, /// so an offset of 18 hours can be represented, but an offset of 18 hours and one second cannot.) /// This allows all offsets within TZDB to be represented. The BCL <see cref="DateTimeOffset"/> type /// only allows offsets up to 14 hours, which means some historical data within TZDB could not be /// represented. /// </para> /// <para>Offsets are represented with a granularity of one second. This allows all offsets within TZDB /// to be represented. It is possible that it could present issues to some other time zone data sources, /// but only in very rare historical cases (or fictional ones).</para> /// <para>Equality and ordering are defined in the natural way by comparing the underlying number /// of seconds. For example, this means that offsets for America are ordered before offsets in Europe.</para> /// </remarks> /// <threadsafety>This type is an immutable value type. See the thread safety section of the user guide for more information.</threadsafety> [TypeConverter(typeof(OffsetTypeConverter))] [XmlSchemaProvider(nameof(AddSchema))] public readonly struct Offset : IEquatable<Offset>, IComparable<Offset>, IFormattable, IComparable, IXmlSerializable { /// <summary> /// An offset of zero seconds - effectively the permanent offset for UTC. /// </summary> public static readonly Offset Zero = FromSeconds(0); /// <summary> /// The minimum permitted offset; 18 hours before UTC. /// </summary> public static readonly Offset MinValue = FromHours(-18); /// <summary> /// The maximum permitted offset; 18 hours after UTC. /// </summary> public static readonly Offset MaxValue = FromHours(18); private const int MinHours = -18; private const int MaxHours = 18; internal const int MinSeconds = -18 * SecondsPerHour; internal const int MaxSeconds = 18 * SecondsPerHour; private const int MinMilliseconds = -18 * MillisecondsPerHour; private const int MaxMilliseconds = 18 * MillisecondsPerHour; private const long MinTicks = -18 * TicksPerHour; private const long MaxTicks = 18 * TicksPerHour; private const long MinNanoseconds = -18 * NanosecondsPerHour; private const long MaxNanoseconds = 18 * NanosecondsPerHour; private readonly int seconds; /// <summary> /// Initializes a new instance of the <see cref="Offset" /> struct. /// </summary> /// <param name="seconds">The number of seconds in the offset.</param> internal Offset([Trusted] int seconds) { Preconditions.DebugCheckArgumentRange(nameof(seconds), seconds, MinSeconds, MaxSeconds); this.seconds = seconds; } /// <summary> /// Gets the number of seconds represented by this offset, which may be negative. /// </summary> /// <value>The number of seconds represented by this offset, which may be negative.</value> public int Seconds => seconds; /// <summary> /// Gets the number of milliseconds represented by this offset, which may be negative. /// </summary> /// <remarks> /// Offsets are only accurate to second precision; the number of seconds is simply multiplied /// by 1,000 to give the number of milliseconds. /// </remarks> /// <value>The number of milliseconds represented by this offset, which may be negative.</value> public int Milliseconds => unchecked(seconds * MillisecondsPerSecond); /// <summary> /// Gets the number of ticks represented by this offset, which may be negative. /// </summary> /// <remarks> /// Offsets are only accurate to second precision; the number of seconds is simply multiplied /// by 10,000,000 to give the number of ticks. /// </remarks> /// <value>The number of ticks.</value> public long Ticks => unchecked(seconds * TicksPerSecond); /// <summary> /// Gets the number of nanoseconds represented by this offset, which may be negative. /// </summary> /// <remarks> /// Offsets are only accurate to second precision; the number of seconds is simply multiplied /// by 1,000,000,000 to give the number of nanoseconds. /// </remarks> /// <value>The number of nanoseconds.</value> public long Nanoseconds => unchecked(seconds * NanosecondsPerSecond); /// <summary> /// Returns the greater offset of the given two, i.e. the one which will give a later local /// time when added to an instant. /// </summary> /// <param name="x">The first offset</param> /// <param name="y">The second offset</param> /// <returns>The greater offset of <paramref name="x"/> and <paramref name="y"/>.</returns> public static Offset Max(Offset x, Offset y) => x > y ? x : y; /// <summary> /// Returns the lower offset of the given two, i.e. the one which will give an earlier local /// time when added to an instant. /// </summary> /// <param name="x">The first offset</param> /// <param name="y">The second offset</param> /// <returns>The lower offset of <paramref name="x"/> and <paramref name="y"/>.</returns> public static Offset Min(Offset x, Offset y) => x < y ? x : y; #region Operators /// <summary> /// Implements the unary operator - (negation). /// </summary> /// <param name="offset">The offset to negate.</param> /// <returns>A new <see cref="Offset" /> instance with a negated value.</returns> public static Offset operator -(Offset offset) => // Guaranteed to still be in range. new Offset(-offset.Seconds); /// <summary> /// Returns the negation of the specified offset. This is the method form of the unary minus operator. /// </summary> /// <param name="offset">The offset to negate.</param> /// <returns>The negation of the specified offset.</returns> public static Offset Negate(Offset offset) => -offset; /// <summary> /// Implements the unary operator + . /// </summary> /// <param name="offset">The operand.</param> /// <remarks>There is no method form of this operator; the <see cref="Plus"/> method is an instance /// method for addition, and is more useful than a method form of this would be.</remarks> /// <returns>The same <see cref="Offset" /> instance</returns> public static Offset operator +(Offset offset) => offset; /// <summary> /// Implements the operator + (addition). /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> /// <returns>A new <see cref="Offset" /> representing the sum of the given values.</returns> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> public static Offset operator +(Offset left, Offset right) => FromSeconds(left.Seconds + right.Seconds); /// <summary> /// Adds one Offset to another. Friendly alternative to <c>operator+()</c>. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> /// <returns>A new <see cref="Offset" /> representing the sum of the given values.</returns> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> public static Offset Add(Offset left, Offset right) => left + right; /// <summary> /// Returns the result of adding another Offset to this one, for a fluent alternative to <c>operator+()</c>. /// </summary> /// <param name="other">The offset to add</param> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> /// <returns>The result of adding the other offset to this one.</returns> [Pure] public Offset Plus(Offset other) => this + other; /// <summary> /// Implements the operator - (subtraction). /// </summary> /// <param name="minuend">The left hand side of the operator.</param> /// <param name="subtrahend">The right hand side of the operator.</param> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> /// <returns>A new <see cref="Offset" /> representing the difference of the given values.</returns> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> public static Offset operator -(Offset minuend, Offset subtrahend) => FromSeconds(minuend.Seconds - subtrahend.Seconds); /// <summary> /// Subtracts one Offset from another. Friendly alternative to <c>operator-()</c>. /// </summary> /// <param name="minuend">The left hand side of the operator.</param> /// <param name="subtrahend">The right hand side of the operator.</param> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> /// <returns>A new <see cref="Offset" /> representing the difference of the given values.</returns> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> public static Offset Subtract(Offset minuend, Offset subtrahend) => minuend - subtrahend; /// <summary> /// Returns the result of subtracting another Offset from this one, for a fluent alternative to <c>operator-()</c>. /// </summary> /// <param name="other">The offset to subtract</param> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> /// <returns>The result of subtracting the other offset from this one.</returns> [Pure] public Offset Minus(Offset other) => this - other; /// <summary> /// Implements the operator == (equality). /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if values are equal to each other, otherwise <c>false</c>.</returns> public static bool operator ==(Offset left, Offset right) => left.Equals(right); /// <summary> /// Implements the operator != (inequality). /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if values are not equal to each other, otherwise <c>false</c>.</returns> public static bool operator !=(Offset left, Offset right) => !(left == right); /// <summary> /// Implements the operator &lt; (less than). /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if the left value is less than the right value, otherwise <c>false</c>.</returns> public static bool operator <(Offset left, Offset right) => left.CompareTo(right) < 0; /// <summary> /// Implements the operator &lt;= (less than or equal). /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if the left value is less than or equal to the right value, otherwise <c>false</c>.</returns> public static bool operator <=(Offset left, Offset right) => left.CompareTo(right) <= 0; /// <summary> /// Implements the operator &gt; (greater than). /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if the left value is greater than the right value, otherwise <c>false</c>.</returns> public static bool operator >(Offset left, Offset right) => left.CompareTo(right) > 0; /// <summary> /// Implements the operator &gt;= (greater than or equal). /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="left">The left hand side of the operator.</param> /// <param name="right">The right hand side of the operator.</param> /// <returns><c>true</c> if the left value is greater than or equal to the right value, otherwise <c>false</c>.</returns> public static bool operator >=(Offset left, Offset right) => left.CompareTo(right) >= 0; #endregion // Operators #region IComparable<Offset> Members /// <summary> /// Compares the current object with another object of the same type. /// See the type documentation for a description of ordering semantics. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// A 32-bit signed integer that indicates the relative order of the objects being compared. /// The return value has the following meanings: /// <list type = "table"> /// <listheader> /// <term>Value</term> /// <description>Meaning</description> /// </listheader> /// <item> /// <term>&lt; 0</term> /// <description>This object is less than the <paramref name = "other" /> parameter.</description> /// </item> /// <item> /// <term>0</term> /// <description>This object is equal to <paramref name = "other" />.</description> /// </item> /// <item> /// <term>&gt; 0</term> /// <description>This object is greater than <paramref name = "other" />.</description> /// </item> /// </list> /// </returns> public int CompareTo(Offset other) => Seconds.CompareTo(other.Seconds); /// <summary> /// Implementation of <see cref="IComparable.CompareTo"/> to compare two offsets. /// See the type documentation for a description of ordering semantics. /// </summary> /// <remarks> /// This uses explicit interface implementation to avoid it being called accidentally. The generic implementation should usually be preferred. /// </remarks> /// <exception cref="ArgumentException"><paramref name="obj"/> is non-null but does not refer to an instance of <see cref="Offset"/>.</exception> /// <param name="obj">The object to compare this value with.</param> /// <returns>The result of comparing this instant with another one; see <see cref="CompareTo(NodaTime.Offset)"/> for general details. /// If <paramref name="obj"/> is null, this method returns a value greater than 0. /// </returns> int IComparable.CompareTo(object obj) { if (obj is null) { return 1; } Preconditions.CheckArgument(obj is Offset, nameof(obj), "Object must be of type NodaTime.Offset."); return CompareTo((Offset) obj); } #endregion #region IEquatable<Offset> Members /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns> /// true if the current object is equal to the <paramref name = "other" /> parameter; /// otherwise, false. /// </returns> public bool Equals(Offset other) => Seconds == other.Seconds; #endregion #region Object overrides /// <summary> /// Determines whether the specified <see cref="System.Object" /> is equal to this instance. /// See the type documentation for a description of equality semantics. /// </summary> /// <param name="obj">The <see cref="System.Object" /> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object" /> is equal to this instance; /// otherwise, <c>false</c>. /// </returns> public override bool Equals(object? obj) => obj is Offset other && Equals(other); /// <summary> /// Returns a hash code for this instance. /// See the type documentation for a description of equality semantics. /// </summary> /// <returns> /// A hash code for this instance, suitable for use in hashing algorithms and data /// structures like a hash table. /// </returns> public override int GetHashCode() => Seconds.GetHashCode(); #endregion // Object overrides #region Formatting /// <summary> /// Returns a <see cref="System.String" /> that represents this instance. /// </summary> /// <returns> /// The value of the current instance in the default format pattern ("g"), using the current thread's /// culture to obtain a format provider. /// </returns> public override string ToString() => OffsetPattern.BclSupport.Format(this, null, CultureInfo.CurrentCulture); /// <summary> /// Formats the value of the current instance using the specified pattern. /// </summary> /// <returns> /// A <see cref="System.String" /> containing the value of the current instance in the specified format. /// </returns> /// <param name="patternText">The <see cref="System.String" /> specifying the pattern to use, /// or null to use the default format pattern ("g"). /// </param> /// <param name="formatProvider">The <see cref="System.IFormatProvider" /> to use when formatting the value, /// or null to use the current thread's culture to obtain a format provider. /// </param> /// <filterpriority>2</filterpriority> public string ToString(string? patternText, IFormatProvider? formatProvider) => OffsetPattern.BclSupport.Format(this, patternText, formatProvider); #endregion Formatting #region Construction /// <summary> /// Returns an offset for the given seconds value, which may be negative. /// </summary> /// <param name="seconds">The int seconds value.</param> /// <returns>An offset representing the given number of seconds.</returns> /// <exception cref="ArgumentOutOfRangeException">The specified number of seconds is outside the range of /// [-18, +18] hours.</exception> public static Offset FromSeconds(int seconds) { Preconditions.CheckArgumentRange(nameof(seconds), seconds, MinSeconds, MaxSeconds); return new Offset(seconds); } /// <summary> /// Returns an offset for the given milliseconds value, which may be negative. /// </summary> /// <remarks> /// Offsets are only accurate to second precision; the given number of milliseconds is simply divided /// by 1,000 to give the number of seconds - any remainder is truncated. /// </remarks> /// <param name="milliseconds">The int milliseconds value.</param> /// <returns>An offset representing the given number of milliseconds, to the (truncated) second.</returns> /// <exception cref="ArgumentOutOfRangeException">The specified number of milliseconds is outside the range of /// [-18, +18] hours.</exception> public static Offset FromMilliseconds(int milliseconds) { Preconditions.CheckArgumentRange(nameof(milliseconds), milliseconds, MinMilliseconds, MaxMilliseconds); return new Offset(milliseconds / MillisecondsPerSecond); } /// <summary> /// Returns an offset for the given number of ticks, which may be negative. /// </summary> /// <remarks> /// Offsets are only accurate to second precision; the given number of ticks is simply divided /// by 10,000,000 to give the number of seconds - any remainder is truncated. /// </remarks> /// <param name="ticks">The number of ticks specifying the length of the new offset.</param> /// <returns>An offset representing the given number of ticks, to the (truncated) second.</returns> /// <exception cref="ArgumentOutOfRangeException">The specified number of ticks is outside the range of /// [-18, +18] hours.</exception> public static Offset FromTicks(long ticks) { Preconditions.CheckArgumentRange(nameof(ticks), ticks, MinTicks, MaxTicks); return new Offset((int) (ticks / TicksPerSecond)); } /// <summary> /// Returns an offset for the given number of nanoseconds, which may be negative. /// </summary> /// <remarks> /// Offsets are only accurate to second precision; the given number of nanoseconds is simply divided /// by 1,000,000,000 to give the number of seconds - any remainder is truncated towards zero. /// </remarks> /// <param name="nanoseconds">The number of nanoseconds specifying the length of the new offset.</param> /// <returns>An offset representing the given number of nanoseconds, to the (truncated) second.</returns> /// <exception cref="ArgumentOutOfRangeException">The specified number of nanoseconds is outside the range of /// [-18, +18] hours.</exception> public static Offset FromNanoseconds(long nanoseconds) { Preconditions.CheckArgumentRange(nameof(nanoseconds), nanoseconds, MinNanoseconds, MaxNanoseconds); return new Offset((int) (nanoseconds / NanosecondsPerSecond)); } /// <summary> /// Returns an offset for the specified number of hours, which may be negative. /// </summary> /// <param name="hours">The number of hours to represent in the new offset.</param> /// <returns>An offset representing the given value.</returns> /// <exception cref="ArgumentOutOfRangeException">The specified number of hours is outside the range of /// [-18, +18].</exception> public static Offset FromHours(int hours) { Preconditions.CheckArgumentRange(nameof(hours), hours, MinHours, MaxHours); return new Offset(hours * SecondsPerHour); } /// <summary> /// Returns an offset for the specified number of hours and minutes. /// </summary> /// <remarks> /// The result simply takes the hours and minutes and converts each component into milliseconds /// separately. As a result, a negative offset should usually be obtained by making both arguments /// negative. For example, to obtain "three hours and ten minutes behind UTC" you might call /// <c>Offset.FromHoursAndMinutes(-3, -10)</c>. /// </remarks> /// <param name="hours">The number of hours to represent in the new offset.</param> /// <param name="minutes">The number of minutes to represent in the new offset.</param> /// <returns>An offset representing the given value.</returns> /// <exception cref="ArgumentOutOfRangeException">The result of the operation is outside the range of Offset.</exception> public static Offset FromHoursAndMinutes(int hours, int minutes) => FromSeconds(hours * SecondsPerHour + minutes * SecondsPerMinute); #endregion #region Conversion /// <summary> /// Converts this offset to a .NET standard <see cref="TimeSpan" /> value. /// </summary> /// <returns>An equivalent <see cref="TimeSpan"/> to this value.</returns> [Pure] public TimeSpan ToTimeSpan() => TimeSpan.FromSeconds(seconds); /// <summary> /// Converts the given <see cref="TimeSpan"/> to an offset, with fractional seconds truncated. /// </summary> /// <param name="timeSpan">The timespan to convert</param> /// <exception cref="ArgumentOutOfRangeException">The given time span falls outside the range of +/- 18 hours.</exception> /// <returns>An offset for the same time as the given time span.</returns> public static Offset FromTimeSpan(TimeSpan timeSpan) { long ticks = timeSpan.Ticks; Preconditions.CheckArgumentRange(nameof(timeSpan), ticks, MinTicks, MaxTicks); return FromTicks(ticks); } #endregion #region XML serialization /// <summary> /// Adds the XML schema type describing the structure of the <see cref="Offset"/> XML serialization to the given <paramref name="xmlSchemaSet"/>. /// </summary> /// <param name="xmlSchemaSet">The XML schema set provided by <see cref="XmlSchemaExporter"/>.</param> /// <returns>The qualified name of the schema type that was added to the <paramref name="xmlSchemaSet"/>.</returns> public static XmlQualifiedName AddSchema(XmlSchemaSet xmlSchemaSet) => Xml.XmlSchemaDefinition.AddOffsetSchemaType(xmlSchemaSet); /// <inheritdoc /> XmlSchema IXmlSerializable.GetSchema() => null!; // TODO(nullable): Return XmlSchema? when docfx works with that /// <inheritdoc /> void IXmlSerializable.ReadXml(XmlReader reader) { Preconditions.CheckNotNull(reader, nameof(reader)); var pattern = OffsetPattern.GeneralInvariant; string text = reader.ReadElementContentAsString(); Unsafe.AsRef(this) = pattern.Parse(text).Value; } /// <inheritdoc /> void IXmlSerializable.WriteXml(XmlWriter writer) { Preconditions.CheckNotNull(writer, nameof(writer)); writer.WriteString(OffsetPattern.GeneralInvariant.Format(this)); } #endregion } }
namespace BgPeople.Services.Areas.HelpPage { using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.IO; using System.Linq; using System.Net.Http; using System.Net.Http.Formatting; using System.Net.Http.Headers; using System.Web.Http.Description; using System.Xml.Linq; using Newtonsoft.Json; /// <summary> /// This class will generate the samples for the help page. /// </summary> public class HelpPageSampleGenerator { /// <summary> /// Initializes a new instance of the <see cref="HelpPageSampleGenerator"/> class. /// </summary> public HelpPageSampleGenerator() { this.ActualHttpMessageTypes = new Dictionary<HelpPageSampleKey, Type>(); this.ActionSamples = new Dictionary<HelpPageSampleKey, object>(); this.SampleObjects = new Dictionary<Type, object>(); this.SampleObjectFactories = new List<Func<HelpPageSampleGenerator, Type, object>> { DefaultSampleObjectFactory, }; } /// <summary> /// Gets CLR types that are used as the content of <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/>. /// </summary> public IDictionary<HelpPageSampleKey, Type> ActualHttpMessageTypes { get; internal set; } /// <summary> /// Gets the objects that are used directly as samples for certain actions. /// </summary> public IDictionary<HelpPageSampleKey, object> ActionSamples { get; internal set; } /// <summary> /// Gets the objects that are serialized as samples by the supported formatters. /// </summary> public IDictionary<Type, object> SampleObjects { get; internal set; } /// <summary> /// Gets factories for the objects that the supported formatters will serialize as samples. Processed in order, /// stopping when the factory successfully returns a non-<see langref="null"/> object. /// </summary> /// <remarks> /// Collection includes just <see cref="ObjectGenerator.GenerateObject(Type)"/> initially. Use /// <code>SampleObjectFactories.Insert(0, func)</code> to provide an override and /// <code>SampleObjectFactories.Add(func)</code> to provide a fallback.</remarks> [SuppressMessage("Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "This is an appropriate nesting of generic types")] public IList<Func<HelpPageSampleGenerator, Type, object>> SampleObjectFactories { get; private set; } /// <summary> /// Gets the request body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleRequests(ApiDescription api) { return this.GetSample(api, SampleDirection.Request); } /// <summary> /// Gets the response body samples for a given <see cref="ApiDescription"/>. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The samples keyed by media type.</returns> public IDictionary<MediaTypeHeaderValue, object> GetSampleResponses(ApiDescription api) { return this.GetSample(api, SampleDirection.Response); } /// <summary> /// Gets the request or response body samples. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The samples keyed by media type.</returns> public virtual IDictionary<MediaTypeHeaderValue, object> GetSample(ApiDescription api, SampleDirection sampleDirection) { if (api == null) { throw new ArgumentNullException("api"); } string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; Type type = this.ResolveType(api, controllerName, actionName, parameterNames, sampleDirection, out formatters); var samples = new Dictionary<MediaTypeHeaderValue, object>(); // Use the samples provided directly for actions var actionSamples = this.GetAllActionSamples(controllerName, actionName, parameterNames, sampleDirection); foreach (var actionSample in actionSamples) { samples.Add(actionSample.Key.MediaType, WrapSampleIfString(actionSample.Value)); } // Do the sample generation based on formatters only if an action doesn't return an HttpResponseMessage. // Here we cannot rely on formatters because we don't know what's in the HttpResponseMessage, it might not even use formatters. if (type != null && !typeof(HttpResponseMessage).IsAssignableFrom(type)) { object sampleObject = this.GetSampleObject(type); foreach (var formatter in formatters) { foreach (MediaTypeHeaderValue mediaType in formatter.SupportedMediaTypes) { if (!samples.ContainsKey(mediaType)) { object sample = this.GetActionSample(controllerName, actionName, parameterNames, type, formatter, mediaType, sampleDirection); // If no sample found, try generate sample using formatter and sample object if (sample == null && sampleObject != null) { sample = this.WriteSampleObjectUsingFormatter(formatter, sampleObject, type, mediaType); } samples.Add(mediaType, WrapSampleIfString(sample)); } } } } return samples; } /// <summary> /// Search for samples that are provided directly through <see cref="ActionSamples"/>. /// </summary> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="type">The CLR type.</param> /// <param name="formatter">The formatter.</param> /// <param name="mediaType">The media type.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or for a response.</param> /// <returns>The sample that matches the parameters.</returns> public virtual object GetActionSample(string controllerName, string actionName, IEnumerable<string> parameterNames, Type type, MediaTypeFormatter formatter, MediaTypeHeaderValue mediaType, SampleDirection sampleDirection) { object sample; // First, try to get the sample provided for the specified mediaType, sampleDirection, controllerName, actionName and parameterNames. // If not found, try to get the sample provided for the specified mediaType, sampleDirection, controllerName and actionName regardless of the parameterNames. // If still not found, try to get the sample provided for the specified mediaType and type. // Finally, try to get the sample provided for the specified mediaType. if (this.ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, parameterNames), out sample) || this.ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, sampleDirection, controllerName, actionName, new[] { "*" }), out sample) || this.ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType, type), out sample) || this.ActionSamples.TryGetValue(new HelpPageSampleKey(mediaType), out sample)) { return sample; } return null; } /// <summary> /// Gets the sample object that will be serialized by the formatters. /// First, it will look at the <see cref="SampleObjects"/>. If no sample object is found, it will try to create /// one using <see cref="DefaultSampleObjectFactory"/> (which wraps an <see cref="ObjectGenerator"/>) and other /// factories in <see cref="SampleObjectFactories"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>The sample object.</returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Even if all items in SampleObjectFactories throw, problem will be visible as missing sample.")] public virtual object GetSampleObject(Type type) { object sampleObject; if (!this.SampleObjects.TryGetValue(type, out sampleObject)) { // No specific object available, try our factories. foreach (Func<HelpPageSampleGenerator, Type, object> factory in this.SampleObjectFactories) { if (factory == null) { continue; } try { sampleObject = factory(this, type); if (sampleObject != null) { break; } } catch { // Ignore any problems encountered in the factory; go on to the next one (if any). } } } return sampleObject; } /// <summary> /// Resolves the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <returns>The type.</returns> public virtual Type ResolveHttpRequestMessageType(ApiDescription api) { string controllerName = api.ActionDescriptor.ControllerDescriptor.ControllerName; string actionName = api.ActionDescriptor.ActionName; IEnumerable<string> parameterNames = api.ParameterDescriptions.Select(p => p.Name); Collection<MediaTypeFormatter> formatters; return this.ResolveType(api, controllerName, actionName, parameterNames, SampleDirection.Request, out formatters); } /// <summary> /// Resolves the type of the action parameter or return value when <see cref="HttpRequestMessage"/> or <see cref="HttpResponseMessage"/> is used. /// </summary> /// <param name="api">The <see cref="ApiDescription"/>.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> /// <param name="sampleDirection">The value indicating whether the sample is for a request or a response.</param> /// <param name="formatters">The formatters.</param> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", Justification = "This is only used in advanced scenarios.")] public virtual Type ResolveType(ApiDescription api, string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection, out Collection<MediaTypeFormatter> formatters) { if (!Enum.IsDefined(typeof(SampleDirection), sampleDirection)) { throw new InvalidEnumArgumentException("sampleDirection", (int)sampleDirection, typeof(SampleDirection)); } if (api == null) { throw new ArgumentNullException("api"); } Type type; if (this.ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, parameterNames), out type) || this.ActualHttpMessageTypes.TryGetValue(new HelpPageSampleKey(sampleDirection, controllerName, actionName, new[] { "*" }), out type)) { // Re-compute the supported formatters based on type Collection<MediaTypeFormatter> newFormatters = new Collection<MediaTypeFormatter>(); foreach (var formatter in api.ActionDescriptor.Configuration.Formatters) { if (IsFormatSupported(sampleDirection, formatter, type)) { newFormatters.Add(formatter); } } formatters = newFormatters; } else { switch (sampleDirection) { case SampleDirection.Request: ApiParameterDescription requestBodyParameter = api.ParameterDescriptions.FirstOrDefault(p => p.Source == ApiParameterSource.FromBody); type = requestBodyParameter == null ? null : requestBodyParameter.ParameterDescriptor.ParameterType; formatters = api.SupportedRequestBodyFormatters; break; case SampleDirection.Response: default: type = api.ResponseDescription.ResponseType ?? api.ResponseDescription.DeclaredType; formatters = api.SupportedResponseFormatters; break; } } return type; } /// <summary> /// Writes the sample object using formatter. /// </summary> /// <param name="formatter">The formatter.</param> /// <param name="value">The value.</param> /// <param name="type">The type.</param> /// <param name="mediaType">Type of the media.</param> /// <returns></returns> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as InvalidSample.")] public virtual object WriteSampleObjectUsingFormatter(MediaTypeFormatter formatter, object value, Type type, MediaTypeHeaderValue mediaType) { if (formatter == null) { throw new ArgumentNullException("formatter"); } if (mediaType == null) { throw new ArgumentNullException("mediaType"); } object sample = string.Empty; MemoryStream ms = null; HttpContent content = null; try { if (formatter.CanWriteType(type)) { ms = new MemoryStream(); content = new ObjectContent(type, value, formatter, mediaType); formatter.WriteToStreamAsync(type, value, ms, content, null).Wait(); ms.Position = 0; StreamReader reader = new StreamReader(ms); string serializedSampleString = reader.ReadToEnd(); if (mediaType.MediaType.ToUpperInvariant().Contains("XML")) { serializedSampleString = TryFormatXml(serializedSampleString); } else if (mediaType.MediaType.ToUpperInvariant().Contains("JSON")) { serializedSampleString = TryFormatJson(serializedSampleString); } sample = new TextSample(serializedSampleString); } else { sample = new InvalidSample(string.Format( CultureInfo.CurrentCulture, "Failed to generate the sample for media type '{0}'. Cannot use formatter '{1}' to write type '{2}'.", mediaType, formatter.GetType().Name, type.Name)); } } catch (Exception e) { sample = new InvalidSample(string.Format( CultureInfo.CurrentCulture, "An exception has occurred while using the formatter '{0}' to generate sample for media type '{1}'. Exception message: {2}", formatter.GetType().Name, mediaType.MediaType, UnwrapException(e).Message)); } finally { if (ms != null) { ms.Dispose(); } if (content != null) { content.Dispose(); } } return sample; } internal static Exception UnwrapException(Exception exception) { AggregateException aggregateException = exception as AggregateException; if (aggregateException != null) { return aggregateException.Flatten().InnerException; } return exception; } // Default factory for sample objects private static object DefaultSampleObjectFactory(HelpPageSampleGenerator sampleGenerator, Type type) { // Try to create a default sample object ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatJson(string str) { try { object parsedJson = JsonConvert.DeserializeObject(str); return JsonConvert.SerializeObject(parsedJson, Formatting.Indented); } catch { // can't parse JSON, return the original string return str; } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Handling the failure by returning the original string.")] private static string TryFormatXml(string str) { try { XDocument xml = XDocument.Parse(str); return xml.ToString(); } catch { // can't parse XML, return the original string return str; } } private static bool IsFormatSupported(SampleDirection sampleDirection, MediaTypeFormatter formatter, Type type) { switch (sampleDirection) { case SampleDirection.Request: return formatter.CanReadType(type); case SampleDirection.Response: return formatter.CanWriteType(type); } return false; } private static object WrapSampleIfString(object sample) { string stringSample = sample as string; if (stringSample != null) { return new TextSample(stringSample); } return sample; } private IEnumerable<KeyValuePair<HelpPageSampleKey, object>> GetAllActionSamples(string controllerName, string actionName, IEnumerable<string> parameterNames, SampleDirection sampleDirection) { HashSet<string> parameterNamesSet = new HashSet<string>(parameterNames, StringComparer.OrdinalIgnoreCase); foreach (var sample in this.ActionSamples) { HelpPageSampleKey sampleKey = sample.Key; if (string.Equals(controllerName, sampleKey.ControllerName, StringComparison.OrdinalIgnoreCase) && string.Equals(actionName, sampleKey.ActionName, StringComparison.OrdinalIgnoreCase) && (sampleKey.ParameterNames.SetEquals(new[] { "*" }) || parameterNamesSet.SetEquals(sampleKey.ParameterNames)) && sampleDirection == sampleKey.SampleDirection) { yield return sample; } } } } }
// 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 Microsoft.CodeAnalysis.CodeGen; using Microsoft.CodeAnalysis.CSharp.Symbols.Metadata.PE; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.VisualStudio.Debugger.Evaluation; using Roslyn.Test.Utilities; using System; using System.Collections.Immutable; using System.Linq; using System.Reflection.Metadata; using Xunit; using Resources = Microsoft.CodeAnalysis.ExpressionEvaluator.UnitTests.Resources; using Roslyn.Test.PdbUtilities; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class WinMdTests : ExpressionCompilerTestBase { /// <summary> /// Handle runtime assemblies rather than Windows.winmd /// (compile-time assembly) since those are the assemblies /// loaded in the debuggee. /// </summary> [WorkItem(981104)] [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"); Assert.True(runtimeAssemblies.Length >= 2); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd exeBytes, new SymReader(pdbBytes)); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("(p == null) ? f : null", out resultProperties, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.1 IL_0001: brfalse.s IL_0005 IL_0003: ldnull IL_0004: ret IL_0005: ldarg.0 IL_0006: ret }"); } [ConditionalFact(typeof(OSVersionWin8))] public void Win8RuntimeAssemblies_ExternAlias() { var source = @"extern alias X; class C { static void M(X::Windows.Storage.StorageFolder f) { } }"; var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: WinRtRefs.Select(r => r.Display == "Windows" ? r.WithAliases(new[] { "X" }) : r)); var runtimeAssemblies = ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage"); Assert.True(runtimeAssemblies.Length >= 1); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); var runtime = CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), ImmutableArray.Create(MscorlibRef).Concat(runtimeAssemblies), // no reference to Windows.winmd exeBytes, new SymReader(pdbBytes)); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("X::Windows.Storage.FileProperties.PhotoOrientation.Unspecified", out resultProperties, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldc.i4.0 IL_0001: ret }"); } [Fact] public void Win8OnWin8() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [Fact] public void Win8OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_3(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows.Storage"); } [WorkItem(1108135)] [Fact] public void Win10OnWin10() { CompileTimeAndRuntimeAssemblies( ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Data)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows_Storage)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), ImmutableArray.Create( MscorlibRef, AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.Windows)).GetReference(), AssemblyMetadata.CreateFromImage(ToVersion1_4(Resources.LibraryA)).GetReference(), AssemblyMetadata.CreateFromImage(Resources.LibraryB).GetReference()), "Windows"); } private void CompileTimeAndRuntimeAssemblies( ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences, string storageAssemblyName) { var source = @"class C { static void M(LibraryA.A a, LibraryB.B b, Windows.Data.Text.TextSegment t, Windows.Storage.StorageFolder f) { } }"; var runtime = CreateRuntime(source, compileReferences, runtimeReferences); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); context.CompileExpression("(object)a ?? (object)b ?? (object)t ?? f", out resultProperties, out error, testData); Assert.Null(error); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 17 (0x11) .maxstack 2 IL_0000: ldarg.0 IL_0001: dup IL_0002: brtrue.s IL_0010 IL_0004: pop IL_0005: ldarg.1 IL_0006: dup IL_0007: brtrue.s IL_0010 IL_0009: pop IL_000a: ldarg.2 IL_000b: dup IL_000c: brtrue.s IL_0010 IL_000e: pop IL_000f: ldarg.3 IL_0010: ret }"); testData = new CompilationTestData(); var result = context.CompileExpression("default(Windows.Storage.StorageFolder)", out resultProperties, out error, testData); Assert.Null(error); var methodData = testData.GetMethodData("<>x.<>m0"); methodData.VerifyIL( @"{ // Code size 2 (0x2) .maxstack 1 IL_0000: ldnull IL_0001: ret }"); // Check return type is from runtime assembly. var assemblyReference = AssemblyMetadata.CreateFromImage(result.Assembly).GetReference(); var compilation = CSharpCompilation.Create( assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: runtimeReferences.Concat(ImmutableArray.Create<MetadataReference>(assemblyReference))); var assembly = ImmutableArray.CreateRange(result.Assembly); using (var metadata = ModuleMetadata.CreateFromImage(ImmutableArray.CreateRange(assembly))) { var reader = metadata.MetadataReader; var typeDef = reader.GetTypeDef("<>x"); var methodHandle = reader.GetMethodDefHandle(typeDef, "<>m0"); var module = (PEModuleSymbol)compilation.GetMember("<>x").ContainingModule; var metadataDecoder = new MetadataDecoder(module); SignatureHeader signatureHeader; BadImageFormatException metadataException; var parameters = metadataDecoder.GetSignatureForMethod(methodHandle, out signatureHeader, out metadataException); Assert.Equal(parameters.Length, 5); var actualReturnType = parameters[0].Type; Assert.Equal(actualReturnType.TypeKind, TypeKind.Class); // not error var expectedReturnType = compilation.GetMember("Windows.Storage.StorageFolder"); Assert.Equal(expectedReturnType, actualReturnType); Assert.Equal(storageAssemblyName, actualReturnType.ContainingAssembly.Name); } } /// <summary> /// Assembly-qualified name containing "ContentType=WindowsRuntime", /// and referencing runtime assembly. /// </summary> [WorkItem(1116143)] [ConditionalFact(typeof(OSVersionWin8))] public void AssemblyQualifiedName() { var source = @"class C { static void M(Windows.Storage.StorageFolder f, Windows.Foundation.Collections.PropertySet p) { } }"; var runtime = CreateRuntime( source, ImmutableArray.CreateRange(WinRtRefs), ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Storage", "Windows.Foundation.Collections"))); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( InspectionContextFactory.Empty. Add("s", "Windows.Storage.StorageFolder, Windows.Storage, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"). Add("d", "Windows.Foundation.DateTime, Windows.Foundation, Version=255.255.255.255, Culture=neutral, PublicKeyToken=null, ContentType=WindowsRuntime"), "(object)s.Attributes ?? d.UniversalTime", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); } [WorkItem(1117084)] [Fact(Skip = "1114866")] public void OtherFrameworkAssembly() { var source = @"class C { static void M(Windows.UI.Xaml.FrameworkElement f) { } }"; var runtime = CreateRuntime( source, ImmutableArray.CreateRange(WinRtRefs), ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.Foundation", "Windows.UI", "Windows.UI.Xaml"))); var context = CreateMethodContext(runtime, "C.M"); ResultProperties resultProperties; string error; var testData = new CompilationTestData(); ImmutableArray<AssemblyIdentity> missingAssemblyIdentities; context.CompileExpression( InspectionContextFactory.Empty, "f.RenderSize", DkmEvaluationFlags.TreatAsExpression, DiagnosticFormatter.Instance, out resultProperties, out error, out missingAssemblyIdentities, EnsureEnglishUICulture.PreferredOrNull, testData); Assert.Empty(missingAssemblyIdentities); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 55 (0x37) .maxstack 2 IL_0000: ldstr ""s"" IL_0005: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_000a: castclass ""Windows.Storage.StorageFolder"" IL_000f: callvirt ""Windows.Storage.FileAttributes Windows.Storage.StorageFolder.Attributes.get"" IL_0014: box ""Windows.Storage.FileAttributes"" IL_0019: dup IL_001a: brtrue.s IL_0036 IL_001c: pop IL_001d: ldstr ""d"" IL_0022: call ""object Microsoft.VisualStudio.Debugger.Clr.IntrinsicMethods.GetObjectByAlias(string)"" IL_0027: unbox.any ""Windows.Foundation.DateTime"" IL_002c: ldfld ""long Windows.Foundation.DateTime.UniversalTime"" IL_0031: box ""long"" IL_0036: ret }"); } [WorkItem(1154988)] [ConditionalFact(typeof(OSVersionWin8))] public void WinMdAssemblyReferenceRequiresRedirect() { var source = @"class C : Windows.UI.Xaml.Controls.UserControl { static void M(C c) { } }"; var runtime = CreateRuntime(source, ImmutableArray.Create(WinRtRefs), ImmutableArray.Create(MscorlibRef).Concat(ExpressionCompilerTestHelpers.GetRuntimeWinMds("Windows.UI", "Windows.UI.Xaml"))); string errorMessage; var testData = new CompilationTestData(); ExpressionCompilerTestHelpers.CompileExpressionWithRetry( runtime.Modules.SelectAsArray(m => m.MetadataBlock), "c.Dispatcher", (metadataBlocks, _) => { return CreateMethodContext(runtime, "C.M"); }, (AssemblyIdentity assembly, out uint size) => { // Compilation should succeed without retry if we redirect assembly refs correctly. // Throwing so that we don't loop forever (as we did before fix)... throw ExceptionUtilities.Unreachable; }, out errorMessage, out testData); Assert.Null(errorMessage); testData.GetMethodData("<>x.<>m0").VerifyIL( @"{ // Code size 7 (0x7) .maxstack 1 IL_0000: ldarg.0 IL_0001: callvirt ""Windows.UI.Core.CoreDispatcher Windows.UI.Xaml.DependencyObject.Dispatcher.get"" IL_0006: ret }"); } private RuntimeInstance CreateRuntime( string source, ImmutableArray<MetadataReference> compileReferences, ImmutableArray<MetadataReference> runtimeReferences) { var compilation0 = CreateCompilationWithMscorlib( source, options: TestOptions.DebugDll, assemblyName: ExpressionCompilerUtilities.GenerateUniqueName(), references: compileReferences); byte[] exeBytes; byte[] pdbBytes; ImmutableArray<MetadataReference> references; compilation0.EmitAndGetReferences(out exeBytes, out pdbBytes, out references); return CreateRuntimeInstance( ExpressionCompilerUtilities.GenerateUniqueName(), runtimeReferences.AddIntrinsicAssembly(), exeBytes, new SymReader(pdbBytes)); } private static byte[] ToVersion1_3(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_3(bytes); } private static byte[] ToVersion1_4(byte[] bytes) { return ExpressionCompilerTestHelpers.ToVersion1_4(bytes); } } }
using System; using UnityEngine; using System.Collections.Generic; namespace Night { public class DualGridGenerator { private OctreeNode root; private LinkedList<DualCell> dualCells = new LinkedList<DualCell>(); private IsoSurface iso; private MeshBuilder mb; private bool saveDualCells; /// The maximum distance where to generate the skirts. private float maxMSDistance; private Vector3 totalFrom; private Vector3 totalTo; public class DualCell { Vector3[] c; public DualCell(Vector3 c0, Vector3 c1, Vector3 c2, Vector3 c3, Vector3 c4, Vector3 c5, Vector3 c6, Vector3 c7) { c = new Vector3[8]; c[0] = c0; c[1] = c1; c[2] = c2; c[3] = c3; c[4] = c4; c[5] = c5; c[6] = c6; c[7] = c7; } } public void nodeProc(OctreeNode n) { if(n.isSubdivided()) { for(int i=0;i<8;i++) { nodeProc(n.getChild(i)); } faceProcXY(n.getChild(0),n.getChild(3)); faceProcXY(n.getChild(1),n.getChild(2)); faceProcXY(n.getChild(4),n.getChild(7)); faceProcXY(n.getChild(5),n.getChild(6)); faceProcZY(n.getChild(0),n.getChild(1)); faceProcZY(n.getChild(3),n.getChild(2)); faceProcZY(n.getChild(4),n.getChild(5)); faceProcZY(n.getChild(7),n.getChild(6)); faceProcXZ(n.getChild(4),n.getChild(0)); faceProcXZ(n.getChild(5),n.getChild(1)); faceProcXZ(n.getChild(7),n.getChild(3)); faceProcXZ(n.getChild(6),n.getChild(2)); edgeProcX(n.getChild(0), n.getChild(3), n.getChild(7), n.getChild(4)); edgeProcX(n.getChild(1), n.getChild(2), n.getChild(6), n.getChild(5)); edgeProcY(n.getChild(0), n.getChild(1), n.getChild(2), n.getChild(3)); edgeProcY(n.getChild(4), n.getChild(5), n.getChild(6), n.getChild(7)); edgeProcZ(n.getChild(7), n.getChild(6), n.getChild(2), n.getChild(3)); edgeProcZ(n.getChild(4), n.getChild(5), n.getChild(1), n.getChild(0)); vertProc(n.getChild(0), n.getChild(1), n.getChild(2), n.getChild(3), n.getChild(4), n.getChild(5), n.getChild(6), n.getChild(7)); } } private void faceProcXY(OctreeNode n0, OctreeNode n1) { if (n0.isSubdivided() || n1.isSubdivided()) { OctreeNode c0 = n0.isSubdivided() ? n0.getChild(3) : n0; OctreeNode c1 = n0.isSubdivided() ? n0.getChild(2) : n0; OctreeNode c2 = n1.isSubdivided() ? n1.getChild(1) : n1; OctreeNode c3 = n1.isSubdivided() ? n1.getChild(0) : n1; OctreeNode c4 = n0.isSubdivided() ? n0.getChild(7) : n0; OctreeNode c5 = n0.isSubdivided() ? n0.getChild(6) : n0; OctreeNode c6 = n1.isSubdivided() ? n1.getChild(5) : n1; OctreeNode c7 = n1.isSubdivided() ? n1.getChild(4) : n1; faceProcXY(c0, c3); faceProcXY(c1, c2); faceProcXY(c4, c7); faceProcXY(c5, c6); edgeProcX(c0, c3, c7, c4); edgeProcX(c1, c2, c6, c5); edgeProcY(c0, c1, c2, c3); edgeProcY(c4, c5, c6, c7); vertProc(c0, c1, c2, c3, c4, c5, c6, c7); } } private void faceProcZY(OctreeNode n0, OctreeNode n1) { if (n0.isSubdivided() || n1.isSubdivided()) { OctreeNode c0 = n0.isSubdivided() ? n0.getChild(1) : n0; OctreeNode c1 = n1.isSubdivided() ? n1.getChild(0) : n1; OctreeNode c2 = n1.isSubdivided() ? n1.getChild(3) : n1; OctreeNode c3 = n0.isSubdivided() ? n0.getChild(2) : n0; OctreeNode c4 = n0.isSubdivided() ? n0.getChild(5) : n0; OctreeNode c5 = n1.isSubdivided() ? n1.getChild(4) : n1; OctreeNode c6 = n1.isSubdivided() ? n1.getChild(7) : n1; OctreeNode c7 = n0.isSubdivided() ? n0.getChild(6) : n0; faceProcZY(c0, c1); faceProcZY(c3, c2); faceProcZY(c4, c5); faceProcZY(c7, c6); edgeProcY(c0, c1, c2, c3); edgeProcY(c4, c5, c6, c7); edgeProcZ(c7, c6, c2, c3); edgeProcZ(c4, c5, c1, c0); vertProc(c0, c1, c2, c3, c4, c5, c6, c7); } } private void faceProcXZ(OctreeNode n0, OctreeNode n1) { if (n0.isSubdivided() || n1.isSubdivided()) { OctreeNode c0 = n1.isSubdivided() ? n1.getChild(4) : n1; OctreeNode c1 = n1.isSubdivided() ? n1.getChild(5) : n1; OctreeNode c2 = n1.isSubdivided() ? n1.getChild(6) : n1; OctreeNode c3 = n1.isSubdivided() ? n1.getChild(7) : n1; OctreeNode c4 = n0.isSubdivided() ? n0.getChild(0) : n0; OctreeNode c5 = n0.isSubdivided() ? n0.getChild(1) : n0; OctreeNode c6 = n0.isSubdivided() ? n0.getChild(2) : n0; OctreeNode c7 = n0.isSubdivided() ? n0.getChild(3) : n0; faceProcXZ(c4, c0); faceProcXZ(c5, c1); faceProcXZ(c7, c3); faceProcXZ(c6, c2); edgeProcX(c0, c3, c7, c4); edgeProcX(c1, c2, c6, c5); edgeProcZ(c7, c6, c2, c3); edgeProcZ(c4, c5, c1, c0); vertProc(c0, c1, c2, c3, c4, c5, c6, c7); } } private void edgeProcX(OctreeNode n0, OctreeNode n1, OctreeNode n2, OctreeNode n3) { if (n0.isSubdivided() || n1.isSubdivided() || n2.isSubdivided() || n3.isSubdivided()) { OctreeNode c0 = n0.isSubdivided() ? n0.getChild(7) : n0; OctreeNode c1 = n0.isSubdivided() ? n0.getChild(6) : n0; OctreeNode c2 = n1.isSubdivided() ? n1.getChild(5) : n1; OctreeNode c3 = n1.isSubdivided() ? n1.getChild(4) : n1; OctreeNode c4 = n3.isSubdivided() ? n3.getChild(3) : n3; OctreeNode c5 = n3.isSubdivided() ? n3.getChild(2) : n3; OctreeNode c6 = n2.isSubdivided() ? n2.getChild(1) : n2; OctreeNode c7 = n2.isSubdivided() ? n2.getChild(0) : n2; edgeProcX(c0, c3, c7, c4); edgeProcX(c1, c2, c6, c5); vertProc(c0, c1, c2, c3, c4, c5, c6, c7); } } private void edgeProcY(OctreeNode n0, OctreeNode n1, OctreeNode n2, OctreeNode n3) { if (n0.isSubdivided() || n1.isSubdivided() || n2.isSubdivided() || n3.isSubdivided()) { OctreeNode c0 = n0.isSubdivided() ? n0.getChild(2) : n0; OctreeNode c1 = n1.isSubdivided() ? n1.getChild(3) : n1; OctreeNode c2 = n2.isSubdivided() ? n2.getChild(0) : n2; OctreeNode c3 = n3.isSubdivided() ? n3.getChild(1) : n3; OctreeNode c4 = n0.isSubdivided() ? n0.getChild(6) : n0; OctreeNode c5 = n1.isSubdivided() ? n1.getChild(7) : n1; OctreeNode c6 = n2.isSubdivided() ? n2.getChild(4) : n2; OctreeNode c7 = n3.isSubdivided() ? n3.getChild(5) : n3; edgeProcY(c0, c1, c2, c3); edgeProcY(c4, c5, c6, c7); vertProc(c0, c1, c2, c3, c4, c5, c6, c7); } } private void edgeProcZ(OctreeNode n0, OctreeNode n1, OctreeNode n2, OctreeNode n3) { if (n0.isSubdivided() || n1.isSubdivided() || n2.isSubdivided() || n3.isSubdivided()) { OctreeNode c0 = n3.isSubdivided() ? n3.getChild(5) : n3; OctreeNode c1 = n2.isSubdivided() ? n2.getChild(4) : n2; OctreeNode c2 = n2.isSubdivided() ? n2.getChild(7) : n2; OctreeNode c3 = n3.isSubdivided() ? n3.getChild(6) : n3; OctreeNode c4 = n0.isSubdivided() ? n0.getChild(1) : n0; OctreeNode c5 = n1.isSubdivided() ? n1.getChild(0) : n1; OctreeNode c6 = n1.isSubdivided() ? n1.getChild(3) : n1; OctreeNode c7 = n0.isSubdivided() ? n0.getChild(2) : n0; edgeProcZ(c7, c6, c2, c3); edgeProcZ(c4, c5, c1, c0); vertProc(c0, c1, c2, c3, c4, c5, c6, c7); } } private void vertProc(OctreeNode n0, OctreeNode n1, OctreeNode n2, OctreeNode n3, OctreeNode n4, OctreeNode n5, OctreeNode n6, OctreeNode n7) { if (n0.isSubdivided() || n1.isSubdivided() || n2.isSubdivided() || n3.isSubdivided() || n4.isSubdivided() || n5.isSubdivided() || n6.isSubdivided() || n7.isSubdivided()) { OctreeNode c0 = n0.isSubdivided() ? n0.getChild(6) : n0; OctreeNode c1 = n1.isSubdivided() ? n1.getChild(7) : n1; OctreeNode c2 = n2.isSubdivided() ? n2.getChild(4) : n2; OctreeNode c3 = n3.isSubdivided() ? n3.getChild(5) : n3; OctreeNode c4 = n4.isSubdivided() ? n4.getChild(2) : n4; OctreeNode c5 = n5.isSubdivided() ? n5.getChild(3) : n5; OctreeNode c6 = n6.isSubdivided() ? n6.getChild(0) : n6; OctreeNode c7 = n7.isSubdivided() ? n7.getChild(1) : n7; vertProc(c0, c1, c2, c3, c4, c5, c6, c7); } else { if (!n0.isIsoSurfaceNear() && !n1.isIsoSurfaceNear() && !n2.isIsoSurfaceNear() && !n3.isIsoSurfaceNear() && !n4.isIsoSurfaceNear() && !n5.isIsoSurfaceNear() && !n6.isIsoSurfaceNear() && !n7.isIsoSurfaceNear()) { return; } float[] values = new float[8]; values[0] = n0.getCenterValue(); values[1] = n1.getCenterValue(); values[2] = n2.getCenterValue(); values[3] = n3.getCenterValue(); values[4] = n4.getCenterValue(); values[5] = n5.getCenterValue(); values[6] = n6.getCenterValue(); values[7] = n7.getCenterValue(); Vector3[] gradients = new Vector3[8]; gradients[0] = n0.getCenterGradient(); gradients[1] = n1.getCenterGradient(); gradients[2] = n2.getCenterGradient(); gradients[3] = n3.getCenterGradient(); gradients[4] = n4.getCenterGradient(); gradients[5] = n5.getCenterGradient(); gradients[6] = n6.getCenterGradient(); gradients[7] = n7.getCenterGradient(); addDualCell(n0.getCenter(), n1.getCenter(), n2.getCenter(), n3.getCenter(), n4.getCenter(), n5.getCenter(), n6.getCenter(), n7.getCenter(), values, gradients); createBorderCells(n0, n1, n2, n3, n4, n5, n6, n7); } } private void createBorderCells(OctreeNode n0, OctreeNode n1, OctreeNode n2, OctreeNode n3, OctreeNode n4, OctreeNode n5, OctreeNode n6, OctreeNode n7) { if (n0.isBorderBack(root) && n1.isBorderBack(root) && n4.isBorderBack(root) && n5.isBorderBack(root)) { addDualCell(n0.getCenterBack(), n1.getCenterBack(), n1.getCenter(), n0.getCenter(), n4.getCenterBack(), n5.getCenterBack(), n5.getCenter(), n4.getCenter()); // Generate back edge border cells if (n4.isBorderTop(root) && n5.isBorderTop(root)) { addDualCell(n4.getCenterBack(), n5.getCenterBack(), n5.getCenter(), n4.getCenter(), n4.getCenterBackTop(), n5.getCenterBackTop(), n5.getCenterTop(), n4.getCenterTop()); // Generate back top corner cells if (n4.isBorderLeft(root)) { addDualCell(n4.getCenterBackLeft(), n4.getCenterBack(), n4.getCenter(), n4.getCenterLeft(), n4.getCorner4(), n4.getCenterBackTop(), n4.getCenterTop(), n4.getCenterLeftTop()); } if (n5.isBorderRight(root)) { addDualCell(n5.getCenterBack(), n5.getCenterBackRight(), n5.getCenterRight(), n5.getCenter(), n5.getCenterBackTop(), n5.getCorner5(), n5.getCenterRightTop(), n5.getCenterTop()); } } if (n0.isBorderBottom(root) && n1.isBorderBottom(root)) { addDualCell(n0.getCenterBackBottom(), n1.getCenterBackBottom(), n1.getCenterBottom(), n0.getCenterBottom(), n0.getCenterBack(), n1.getCenterBack(), n1.getCenter(), n0.getCenter()); // Generate back bottom corner cells if (n0.isBorderLeft(root)) { addDualCell(n0.getFrom(), n0.getCenterBackBottom(), n0.getCenterBottom(), n0.getCenterLeftBottom(), n0.getCenterBackLeft(), n0.getCenterBack(), n0.getCenter(), n0.getCenterLeft()); } if (n1.isBorderRight(root)) { addDualCell(n1.getCenterBackBottom(), n1.getCorner1(), n1.getCenterRightBottom(), n1.getCenterBottom(), n1.getCenterBack(), n1.getCenterBackRight(), n1.getCenterRight(), n1.getCenter()); } } } if (n2.isBorderFront(root) && n3.isBorderFront(root) && n6.isBorderFront(root) && n7.isBorderFront(root)) { addDualCell(n3.getCenter(), n2.getCenter(), n2.getCenterFront(), n3.getCenterFront(), n7.getCenter(), n6.getCenter(), n6.getCenterFront(), n7.getCenterFront()); // Generate front edge border cells if (n6.isBorderTop(root) && n7.isBorderTop(root)) { addDualCell(n7.getCenter(), n6.getCenter(), n6.getCenterFront(), n7.getCenterFront(), n7.getCenterTop(), n6.getCenterTop(), n6.getCenterFrontTop(), n7.getCenterFrontTop()); // Generate back bottom corner cells if (n7.isBorderLeft(root)) { addDualCell(n7.getCenterLeft(), n7.getCenter(), n7.getCenterFront(), n7.getCenterFrontLeft(), n7.getCenterLeftTop(), n7.getCenterTop(), n7.getCenterFrontTop(), n7.getCorner7()); } if (n6.isBorderRight(root)) { addDualCell(n6.getCenter(), n6.getCenterRight(), n6.getCenterFrontRight(), n6.getCenterFront(), n6.getCenterTop(), n6.getCenterRightTop(), n6.getTo(), n6.getCenterFrontTop()); } } if (n3.isBorderBottom(root) && n2.isBorderBottom(root)) { addDualCell(n3.getCenterBottom(), n2.getCenterBottom(), n2.getCenterFrontBottom(), n3.getCenterFrontBottom(), n3.getCenter(), n2.getCenter(), n2.getCenterFront(), n3.getCenterFront()); // Generate back bottom corner cells if (n3.isBorderLeft(root)) { addDualCell(n3.getCenterLeftBottom(), n3.getCenterBottom(), n3.getCenterFrontBottom(), n3.getCorner3(), n3.getCenterLeft(), n3.getCenter(), n3.getCenterFront(), n3.getCenterFrontLeft()); } if (n2.isBorderRight(root)) { addDualCell(n2.getCenterBottom(), n2.getCenterRightBottom(), n2.getCorner2(), n2.getCenterFrontBottom(), n2.getCenter(), n2.getCenterRight(), n2.getCenterFrontRight(), n2.getCenterFront()); } } } if (n0.isBorderLeft(root) && n3.isBorderLeft(root) && n4.isBorderLeft(root) && n7.isBorderLeft(root)) { addDualCell(n0.getCenterLeft(), n0.getCenter(), n3.getCenter(), n3.getCenterLeft(), n4.getCenterLeft(), n4.getCenter(), n7.getCenter(), n7.getCenterLeft()); // Generate left edge border cells if (n4.isBorderTop(root) && n7.isBorderTop(root)) { addDualCell(n4.getCenterLeft(), n4.getCenter(), n7.getCenter(), n7.getCenterLeft(), n4.getCenterLeftTop(), n4.getCenterTop(), n7.getCenterTop(), n7.getCenterLeftTop()); } if (n0.isBorderBottom(root) && n3.isBorderBottom(root)) { addDualCell(n0.getCenterLeftBottom(), n0.getCenterBottom(), n3.getCenterBottom(), n3.getCenterLeftBottom(), n0.getCenterLeft(), n0.getCenter(), n3.getCenter(), n3.getCenterLeft()); } if (n0.isBorderBack(root) && n4.isBorderBack(root)) { addDualCell(n0.getCenterBackLeft(), n0.getCenterBack(), n0.getCenter(), n0.getCenterLeft(), n4.getCenterBackLeft(), n4.getCenterBack(), n4.getCenter(), n4.getCenterLeft()); } if (n3.isBorderFront(root) && n7.isBorderFront(root)) { addDualCell(n3.getCenterLeft(), n3.getCenter(), n3.getCenterFront(), n3.getCenterFrontLeft(), n7.getCenterLeft(), n7.getCenter(), n7.getCenterFront(), n7.getCenterFrontLeft()); } } if (n1.isBorderRight(root) && n2.isBorderRight(root) && n5.isBorderRight(root) && n6.isBorderRight(root)) { addDualCell(n1.getCenter(), n1.getCenterRight(), n2.getCenterRight(), n2.getCenter(), n5.getCenter(), n5.getCenterRight(), n6.getCenterRight(), n6.getCenter()); // Generate right edge border cells if (n5.isBorderTop(root) && n6.isBorderTop(root)) { addDualCell(n5.getCenter(), n5.getCenterRight(), n6.getCenterRight(), n6.getCenter(), n5.getCenterTop(), n5.getCenterRightTop(), n6.getCenterRightTop(), n6.getCenterTop()); } if (n1.isBorderBottom(root) && n2.isBorderBottom(root)) { addDualCell(n1.getCenterBottom(), n1.getCenterRightBottom(), n2.getCenterRightBottom(), n2.getCenterBottom(), n1.getCenter(), n1.getCenterRight(), n2.getCenterRight(), n2.getCenter()); } if (n1.isBorderBack(root) && n5.isBorderBack(root)) { addDualCell(n1.getCenterBack(), n1.getCenterBackRight(), n1.getCenterRight(), n1.getCenter(), n5.getCenterBack(), n5.getCenterBackRight(), n5.getCenterRight(), n5.getCenter()); } if (n2.isBorderFront(root) && n6.isBorderFront(root)) { addDualCell(n2.getCenter(), n2.getCenterRight(), n2.getCenterFrontRight(), n2.getCenterFront(), n6.getCenter(), n6.getCenterRight(), n6.getCenterFrontRight(), n6.getCenterFront()); } } if (n4.isBorderTop(root) && n5.isBorderTop(root) && n6.isBorderTop(root) && n7.isBorderTop(root)) { addDualCell(n4.getCenter(), n5.getCenter(), n6.getCenter(), n7.getCenter(), n4.getCenterTop(), n5.getCenterTop(), n6.getCenterTop(), n7.getCenterTop()); } if (n0.isBorderBottom(root) && n1.isBorderBottom(root) && n2.isBorderBottom(root) && n3.isBorderBottom(root)) { addDualCell(n0.getCenterBottom(), n1.getCenterBottom(), n2.getCenterBottom(), n3.getCenterBottom(), n0.getCenter(), n1.getCenter(), n2.getCenter(), n3.getCenter()); } } public void addDualCell(Vector3 c0, Vector3 c1, Vector3 c2, Vector3 c3, Vector3 c4, Vector3 c5, Vector3 c6, Vector3 c7) { addDualCell(c0, c1, c2, c3, c4, c5, c6, c7, null, null); } public void addDualCell(Vector3 c0, Vector3 c1, Vector3 c2, Vector3 c3, Vector3 c4, Vector3 c5, Vector3 c6, Vector3 c7, float[] values, Vector3[] gradients) { if (saveDualCells) { dualCells.AddLast(new DualCell(c0, c1, c2, c3, c4, c5, c6, c7)); } Vector3[] corners = new Vector3[8]; corners[0] = c0; corners[1] = c1; corners[2] = c2; corners[3] = c3; corners[4] = c4; corners[5] = c5; corners[6] = c6; corners[7] = c7; iso.addMarchingCubesTriangles(corners, values,gradients, mb); Vector3 from = root.getFrom(); Vector3 to = root.getTo(); if (corners[0].z == from.z && corners[0].z != totalFrom.z) { iso.addMarchingSquaresTriangles(corners, values, gradients, IsoSurface.MS_CORNERS_BACK, maxMSDistance, mb); } if (corners[2].z == to.z && corners[2].z != totalTo.z) { iso.addMarchingSquaresTriangles(corners, values,gradients, IsoSurface.MS_CORNERS_FRONT, maxMSDistance, mb); } if (corners[0].x == from.x && corners[0].x != totalFrom.x) { iso.addMarchingSquaresTriangles(corners, values,gradients, IsoSurface.MS_CORNERS_LEFT, maxMSDistance, mb); } if (corners[1].x == to.x && corners[1].x != totalTo.x) { iso.addMarchingSquaresTriangles(corners, values,gradients, IsoSurface.MS_CORNERS_RIGHT, maxMSDistance, mb); } if (corners[5].y == to.y && corners[5].y != totalTo.y) { iso.addMarchingSquaresTriangles(corners, values,gradients, IsoSurface.MS_CORNERS_TOP, maxMSDistance, mb); } if (corners[0].y == from.y && corners[0].y != totalFrom.y) { iso.addMarchingSquaresTriangles(corners, values,gradients, IsoSurface.MS_CORNERS_BOTTOM, maxMSDistance, mb); } } public void generateDualGrid(OctreeNode root, IsoSurface iso, MeshBuilder mb, float maxMSDistance, Vector3 totalFrom, Vector3 totalTo, bool saveDualCells) { this.root = root; this.iso = iso; this.mb = mb; this.maxMSDistance = maxMSDistance; this.totalFrom = totalFrom; this.totalTo = totalTo; this.saveDualCells = saveDualCells; nodeProc(root); // Build up a minimal dualgrid for octrees without children. if (!root.isSubdivided()) { addDualCell(root.getFrom(), root.getCenterBackBottom(), root.getCenterBottom(), root.getCenterLeftBottom(), root.getCenterBackLeft(), root.getCenterBack(), root.getCenter(), root.getCenterLeft()); addDualCell(root.getCenterBackBottom(), root.getCorner1(), root.getCenterRightBottom(), root.getCenterBottom(), root.getCenterBack(), root.getCenterBackRight(), root.getCenterRight(), root.getCenter()); addDualCell(root.getCenterBottom(), root.getCenterRightBottom(), root.getCorner2(), root.getCenterFrontBottom(), root.getCenter(), root.getCenterRight(), root.getCenterFrontRight(), root.getCenterFront()); addDualCell(root.getCenterLeftBottom(), root.getCenterBottom(), root.getCenterFrontBottom(), root.getCorner3(), root.getCenterLeft(), root.getCenter(), root.getCenterFront(), root.getCenterFrontLeft()); addDualCell(root.getCenterBackLeft(), root.getCenterBack(), root.getCenter(), root.getCenterLeft(), root.getCorner4(), root.getCenterBackTop(), root.getCenterTop(), root.getCenterLeftTop()); addDualCell(root.getCenterBack(), root.getCenterBackRight(), root.getCenterRight(), root.getCenter(), root.getCenterBackTop(), root.getCorner5(), root.getCenterRightTop(), root.getCenterTop()); addDualCell(root.getCenter(), root.getCenterRight(), root.getCenterFrontRight(), root.getCenterFront(), root.getCenterTop(), root.getCenterRightTop(), root.getTo(), root.getCenterFrontTop()); addDualCell(root.getCenterLeft(), root.getCenter(), root.getCenterFront(), root.getCenterFrontLeft(), root.getCenterLeftTop(), root.getCenterTop(), root.getCenterFrontTop(), root.getCorner7()); } } public LinkedList<DualCell> getDualCells() { return dualCells; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System; using System.Diagnostics.Contracts; namespace System.Globalization { // // Property Default Description // PositiveSign '+' Character used to indicate positive values. // NegativeSign '-' Character used to indicate negative values. // NumberDecimalSeparator '.' The character used as the decimal separator. // NumberGroupSeparator ',' The character used to separate groups of // digits to the left of the decimal point. // NumberDecimalDigits 2 The default number of decimal places. // NumberGroupSizes 3 The number of digits in each group to the // left of the decimal point. // NaNSymbol "NaN" The string used to represent NaN values. // PositiveInfinitySymbol"Infinity" The string used to represent positive // infinities. // NegativeInfinitySymbol"-Infinity" The string used to represent negative // infinities. // // // // Property Default Description // CurrencyDecimalSeparator '.' The character used as the decimal // separator. // CurrencyGroupSeparator ',' The character used to separate groups // of digits to the left of the decimal // point. // CurrencyDecimalDigits 2 The default number of decimal places. // CurrencyGroupSizes 3 The number of digits in each group to // the left of the decimal point. // CurrencyPositivePattern 0 The format of positive values. // CurrencyNegativePattern 0 The format of negative values. // CurrencySymbol "$" String used as local monetary symbol. // [System.Runtime.InteropServices.ComVisible(true)] sealed public class NumberFormatInfo : IFormatProvider, ICloneable { // invariantInfo is constant irrespective of your current culture. private static volatile NumberFormatInfo s_invariantInfo; // READTHIS READTHIS READTHIS // This class has an exact mapping onto a native structure defined in COMNumber.cpp // DO NOT UPDATE THIS WITHOUT UPDATING THAT STRUCTURE. IF YOU ADD BOOL, ADD THEM AT THE END. // ALSO MAKE SURE TO UPDATE mscorlib.h in the VM directory to check field offsets. // READTHIS READTHIS READTHIS internal int[] numberGroupSizes = new int[] { 3 }; internal int[] currencyGroupSizes = new int[] { 3 }; internal int[] percentGroupSizes = new int[] { 3 }; internal String positiveSign = "+"; internal String negativeSign = "-"; internal String numberDecimalSeparator = "."; internal String numberGroupSeparator = ","; internal String currencyGroupSeparator = ","; internal String currencyDecimalSeparator = "."; internal String currencySymbol = "\x00a4"; // U+00a4 is the symbol for International Monetary Fund. internal String nanSymbol = "NaN"; internal String positiveInfinitySymbol = "Infinity"; internal String negativeInfinitySymbol = "-Infinity"; internal String percentDecimalSeparator = "."; internal String percentGroupSeparator = ","; internal String percentSymbol = "%"; internal String perMilleSymbol = "\u2030"; internal String[] nativeDigits = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9" }; internal int numberDecimalDigits = 2; internal int currencyDecimalDigits = 2; internal int currencyPositivePattern = 0; internal int currencyNegativePattern = 0; internal int numberNegativePattern = 1; internal int percentPositivePattern = 0; internal int percentNegativePattern = 0; internal int percentDecimalDigits = 2; internal bool isReadOnly = false; // Is this NumberFormatInfo for invariant culture? internal bool m_isInvariant = false; public NumberFormatInfo() : this(null) { } static private void VerifyDecimalSeparator(String decSep, String propertyName) { if (decSep == null) { throw new ArgumentNullException(propertyName, SR.ArgumentNull_String); } if (decSep.Length == 0) { throw new ArgumentException(SR.Argument_EmptyDecString); } Contract.EndContractBlock(); } static private void VerifyGroupSeparator(String groupSep, String propertyName) { if (groupSep == null) { throw new ArgumentNullException(propertyName, SR.ArgumentNull_String); } Contract.EndContractBlock(); } internal NumberFormatInfo(CultureData cultureData) { if (cultureData != null) { // We directly use fields here since these data is coming from data table or Win32, so we // don't need to verify their values (except for invalid parsing situations). cultureData.GetNFIValues(this); if (cultureData.IsInvariantCulture) { // For invariant culture this.m_isInvariant = true; } } } [Pure] private void VerifyWritable() { if (isReadOnly) { throw new InvalidOperationException(SR.InvalidOperation_ReadOnly); } Contract.EndContractBlock(); } // Returns a default NumberFormatInfo that will be universally // supported and constant irrespective of the current culture. // Used by FromString methods. // public static NumberFormatInfo InvariantInfo { get { if (s_invariantInfo == null) { // Lazy create the invariant info. This cannot be done in a .cctor because exceptions can // be thrown out of a .cctor stack that will need this. NumberFormatInfo nfi = new NumberFormatInfo(); nfi.m_isInvariant = true; s_invariantInfo = ReadOnly(nfi); } return s_invariantInfo; } } public static NumberFormatInfo GetInstance(IFormatProvider formatProvider) { // Fast case for a regular CultureInfo NumberFormatInfo info; CultureInfo cultureProvider = formatProvider as CultureInfo; if (cultureProvider != null && !cultureProvider.m_isInherited) { info = cultureProvider.numInfo; if (info != null) { return info; } else { return cultureProvider.NumberFormat; } } // Fast case for an NFI; info = formatProvider as NumberFormatInfo; if (info != null) { return info; } if (formatProvider != null) { info = formatProvider.GetFormat(typeof(NumberFormatInfo)) as NumberFormatInfo; if (info != null) { return info; } } return CurrentInfo; } public Object Clone() { NumberFormatInfo n = (NumberFormatInfo)MemberwiseClone(); n.isReadOnly = false; return n; } public int CurrencyDecimalDigits { get { return currencyDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( "CurrencyDecimalDigits", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); currencyDecimalDigits = value; } } public String CurrencyDecimalSeparator { get { return currencyDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "CurrencyDecimalSeparator"); currencyDecimalSeparator = value; } } public bool IsReadOnly { get { return isReadOnly; } } // // Check the values of the groupSize array. // // Every element in the groupSize array should be between 1 and 9 // excpet the last element could be zero. // static internal void CheckGroupSize(String propName, int[] groupSize) { for (int i = 0; i < groupSize.Length; i++) { if (groupSize[i] < 1) { if (i == groupSize.Length - 1 && groupSize[i] == 0) return; throw new ArgumentException(SR.Argument_InvalidGroupSize, propName); } else if (groupSize[i] > 9) { throw new ArgumentException(SR.Argument_InvalidGroupSize, propName); } } } public int[] CurrencyGroupSizes { get { return ((int[])currencyGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException("CurrencyGroupSizes", SR.ArgumentNull_Obj); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize("CurrencyGroupSizes", inputSizes); currencyGroupSizes = inputSizes; } } public int[] NumberGroupSizes { get { return ((int[])numberGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException("NumberGroupSizes", SR.ArgumentNull_Obj); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize("NumberGroupSizes", inputSizes); numberGroupSizes = inputSizes; } } public int[] PercentGroupSizes { get { return ((int[])percentGroupSizes.Clone()); } set { if (value == null) { throw new ArgumentNullException("PercentGroupSizes", SR.ArgumentNull_Obj); } Contract.EndContractBlock(); VerifyWritable(); Int32[] inputSizes = (Int32[])value.Clone(); CheckGroupSize("PercentGroupSizes", inputSizes); percentGroupSizes = inputSizes; } } public String CurrencyGroupSeparator { get { return currencyGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "CurrencyGroupSeparator"); currencyGroupSeparator = value; } } public String CurrencySymbol { get { return currencySymbol; } set { if (value == null) { throw new ArgumentNullException("CurrencySymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); currencySymbol = value; } } // Returns the current culture's NumberFormatInfo. Used by Parse methods. // public static NumberFormatInfo CurrentInfo { get { System.Globalization.CultureInfo culture = CultureInfo.CurrentCulture; if (!culture.m_isInherited) { NumberFormatInfo info = culture.numInfo; if (info != null) { return info; } } return ((NumberFormatInfo)culture.GetFormat(typeof(NumberFormatInfo))); } } public String NaNSymbol { get { return nanSymbol; } set { if (value == null) { throw new ArgumentNullException("NaNSymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); nanSymbol = value; } } public int CurrencyNegativePattern { get { return currencyNegativePattern; } set { if (value < 0 || value > 15) { throw new ArgumentOutOfRangeException( "CurrencyNegativePattern", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 15)); } Contract.EndContractBlock(); VerifyWritable(); currencyNegativePattern = value; } } public int NumberNegativePattern { get { return numberNegativePattern; } set { // // NOTENOTE: the range of value should correspond to negNumberFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 4) { throw new ArgumentOutOfRangeException( "NumberNegativePattern", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 4)); } Contract.EndContractBlock(); VerifyWritable(); numberNegativePattern = value; } } public int PercentPositivePattern { get { return percentPositivePattern; } set { // // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( "PercentPositivePattern", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 3)); } Contract.EndContractBlock(); VerifyWritable(); percentPositivePattern = value; } } public int PercentNegativePattern { get { return percentNegativePattern; } set { // // NOTENOTE: the range of value should correspond to posPercentFormats[] in vm\COMNumber.cpp. // if (value < 0 || value > 11) { throw new ArgumentOutOfRangeException( "PercentNegativePattern", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 11)); } Contract.EndContractBlock(); VerifyWritable(); percentNegativePattern = value; } } public String NegativeInfinitySymbol { get { return negativeInfinitySymbol; } set { if (value == null) { throw new ArgumentNullException("NegativeInfinitySymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); negativeInfinitySymbol = value; } } public String NegativeSign { get { return negativeSign; } set { if (value == null) { throw new ArgumentNullException("NegativeSign", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); negativeSign = value; } } public int NumberDecimalDigits { get { return numberDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( "NumberDecimalDigits", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); numberDecimalDigits = value; } } public String NumberDecimalSeparator { get { return numberDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "NumberDecimalSeparator"); numberDecimalSeparator = value; } } public String NumberGroupSeparator { get { return numberGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "NumberGroupSeparator"); numberGroupSeparator = value; } } public int CurrencyPositivePattern { get { return currencyPositivePattern; } set { if (value < 0 || value > 3) { throw new ArgumentOutOfRangeException( "CurrencyPositivePattern", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 3)); } Contract.EndContractBlock(); VerifyWritable(); currencyPositivePattern = value; } } public String PositiveInfinitySymbol { get { return positiveInfinitySymbol; } set { if (value == null) { throw new ArgumentNullException("PositiveInfinitySymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); positiveInfinitySymbol = value; } } public String PositiveSign { get { return positiveSign; } set { if (value == null) { throw new ArgumentNullException("PositiveSign", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); positiveSign = value; } } public int PercentDecimalDigits { get { return percentDecimalDigits; } set { if (value < 0 || value > 99) { throw new ArgumentOutOfRangeException( "PercentDecimalDigits", String.Format( CultureInfo.CurrentCulture, SR.ArgumentOutOfRange_Range, 0, 99)); } Contract.EndContractBlock(); VerifyWritable(); percentDecimalDigits = value; } } public String PercentDecimalSeparator { get { return percentDecimalSeparator; } set { VerifyWritable(); VerifyDecimalSeparator(value, "PercentDecimalSeparator"); percentDecimalSeparator = value; } } public String PercentGroupSeparator { get { return percentGroupSeparator; } set { VerifyWritable(); VerifyGroupSeparator(value, "PercentGroupSeparator"); percentGroupSeparator = value; } } public String PercentSymbol { get { return percentSymbol; } set { if (value == null) { throw new ArgumentNullException("PercentSymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); percentSymbol = value; } } public String PerMilleSymbol { get { return perMilleSymbol; } set { if (value == null) { throw new ArgumentNullException("PerMilleSymbol", SR.ArgumentNull_String); } Contract.EndContractBlock(); VerifyWritable(); perMilleSymbol = value; } } public Object GetFormat(Type formatType) { return formatType == typeof(NumberFormatInfo) ? this : null; } public static NumberFormatInfo ReadOnly(NumberFormatInfo nfi) { if (nfi == null) { throw new ArgumentNullException("nfi"); } Contract.EndContractBlock(); if (nfi.IsReadOnly) { return (nfi); } NumberFormatInfo info = (NumberFormatInfo)(nfi.MemberwiseClone()); info.isReadOnly = true; return info; } // private const NumberStyles InvalidNumberStyles = unchecked((NumberStyles) 0xFFFFFC00); private const NumberStyles InvalidNumberStyles = ~(NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign | NumberStyles.AllowTrailingSign | NumberStyles.AllowParentheses | NumberStyles.AllowDecimalPoint | NumberStyles.AllowThousands | NumberStyles.AllowExponent | NumberStyles.AllowCurrencySymbol | NumberStyles.AllowHexSpecifier); internal static void ValidateParseStyleInteger(NumberStyles style) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style"); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number if ((style & ~NumberStyles.HexNumber) != 0) { throw new ArgumentException(SR.Arg_InvalidHexStyle); } } } internal static void ValidateParseStyleFloatingPoint(NumberStyles style) { // Check for undefined flags if ((style & InvalidNumberStyles) != 0) { throw new ArgumentException(SR.Argument_InvalidNumberStyles, "style"); } Contract.EndContractBlock(); if ((style & NumberStyles.AllowHexSpecifier) != 0) { // Check for hex number throw new ArgumentException(SR.Arg_HexStyleNotSupported); } } } // NumberFormatInfo }
// 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.ObjectModel; using System.Diagnostics; using System.Text; using Microsoft.CodeAnalysis.Collections; using Microsoft.CodeAnalysis.ExpressionEvaluator; using Microsoft.VisualStudio.Debugger.Evaluation.ClrCompilation; using Roslyn.Utilities; using Type = Microsoft.VisualStudio.Debugger.Metadata.Type; namespace Microsoft.CodeAnalysis.CSharp.ExpressionEvaluator { internal sealed partial class CSharpFormatter : Formatter { private void AppendEnumTypeAndName(StringBuilder builder, Type typeToDisplayOpt, string name) { if (typeToDisplayOpt != null) { AppendQualifiedTypeName(builder, typeToDisplayOpt, escapeKeywordIdentifiers: true); builder.Append('.'); AppendIdentifierEscapingPotentialKeywords(builder, name); } else { builder.Append(name); } } internal override string GetArrayDisplayString(Type lmrType, ReadOnlyCollection<int> sizes, ReadOnlyCollection<int> lowerBounds, ObjectDisplayOptions options) { Debug.Assert(lmrType.IsArray); Type originalLmrType = lmrType; // Strip off all array types. We'll process them at the end. while (lmrType.IsArray) { lmrType = lmrType.GetElementType(); } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append('{'); builder.Append(GetTypeName(lmrType)); // NOTE: call our impl directly, since we're coupled anyway. var numSizes = sizes.Count; builder.Append('['); for (int i = 0; i < numSizes; i++) { if (i > 0) { builder.Append(", "); } var lowerBound = lowerBounds[i]; var size = sizes[i]; if (lowerBound == 0) { builder.Append(FormatLiteral(size, options)); } else { builder.Append(FormatLiteral(lowerBound, options)); builder.Append(".."); builder.Append(FormatLiteral(size + lowerBound - 1, options)); } } builder.Append(']'); lmrType = originalLmrType.GetElementType(); // Strip off one layer (already handled). while (lmrType.IsArray) { builder.Append('['); builder.Append(',', lmrType.GetArrayRank() - 1); builder.Append(']'); lmrType = lmrType.GetElementType(); } builder.Append('}'); return pooled.ToStringAndFree(); } internal override string GetArrayIndexExpression(int[] indices) { Debug.Assert(indices != null); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append('['); bool any = false; foreach (var index in indices) { if (any) { builder.Append(", "); } builder.Append(index); any = true; } builder.Append(']'); return pooled.ToStringAndFree(); } internal override string GetCastExpression(string argument, string type, bool parenthesizeArgument = false, bool parenthesizeEntireExpression = false) { Debug.Assert(!string.IsNullOrEmpty(argument)); Debug.Assert(!string.IsNullOrEmpty(type)); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; if (parenthesizeEntireExpression) { builder.Append('('); } var castExpressionFormat = parenthesizeArgument ? "({0})({1})" : "({0}){1}"; builder.AppendFormat(castExpressionFormat, type, argument); if (parenthesizeEntireExpression) { builder.Append(')'); } return pooled.ToStringAndFree(); } internal override string GetNamesForFlagsEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt) { var usedFields = ArrayBuilder<EnumField>.GetInstance(); FillUsedEnumFields(usedFields, fields, underlyingValue); if (usedFields.Count == 0) { return null; } var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; for (int i = usedFields.Count - 1; i >= 0; i--) // Backwards to list smallest first. { AppendEnumTypeAndName(builder, typeToDisplayOpt, usedFields[i].Name); if (i > 0) { builder.Append(" | "); } } usedFields.Free(); return pooled.ToStringAndFree(); } internal override string GetNameForEnumValue(ArrayBuilder<EnumField> fields, object value, ulong underlyingValue, ObjectDisplayOptions options, Type typeToDisplayOpt) { foreach (var field in fields) { // First match wins (deterministic since sorted). if (underlyingValue == field.Value) { var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; AppendEnumTypeAndName(builder, typeToDisplayOpt, field.Name); return pooled.ToStringAndFree(); } } return null; } internal override string GetObjectCreationExpression(string type, string arguments) { Debug.Assert(!string.IsNullOrEmpty(type)); var pooled = PooledStringBuilder.GetInstance(); var builder = pooled.Builder; builder.Append("new "); builder.Append(type); builder.Append('('); builder.Append(arguments); builder.Append(')'); return pooled.ToStringAndFree(); } internal override string FormatLiteral(char c, ObjectDisplayOptions options) { return ObjectDisplay.FormatLiteral(c, options); } internal override string FormatLiteral(int value, ObjectDisplayOptions options) { return ObjectDisplay.FormatLiteral(value, options & ~ObjectDisplayOptions.UseQuotes); } internal override string FormatPrimitiveObject(object value, ObjectDisplayOptions options) { return ObjectDisplay.FormatPrimitive(value, options); } internal override string FormatString(string str, ObjectDisplayOptions options) { return ObjectDisplay.FormatString(str, useQuotes: options.IncludesOption(ObjectDisplayOptions.UseQuotes)); } } }
// // Copyright (c) Microsoft and contributors. All rights reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // // See the License for the specific language governing permissions and // limitations under the License. // // Warning: This code was generated by a tool. // // Changes to this file may cause incorrect behavior and will be lost if the // code is regenerated. using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Microsoft.WindowsAzure; using Microsoft.WindowsAzure.Common; using Microsoft.WindowsAzure.Common.Internals; using Microsoft.WindowsAzure.Management.Compute; using Microsoft.WindowsAzure.Management.Compute.Models; namespace Microsoft.WindowsAzure.Management.Compute { /// <summary> /// The Service Management API provides programmatic access to much of the /// functionality available through the Management Portal. The Service /// Management API is a REST API. All API operations are performed over /// SSL and mutually authenticated using X.509 v3 certificates. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460799.aspx for /// more information) /// </summary> public partial class ComputeManagementClient : ServiceClient<ComputeManagementClient>, IComputeManagementClient { private Uri _baseUri; /// <summary> /// The URI used as the base for all Service Management requests. /// </summary> public Uri BaseUri { get { return this._baseUri; } } private SubscriptionCloudCredentials _credentials; /// <summary> /// When you create a Windows Azure subscription, it is uniquely /// identified by a subscription ID. The subscription ID forms part of /// the URI for every call that you make to the Service Management /// API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests /// are allowed. /// </summary> public SubscriptionCloudCredentials Credentials { get { return this._credentials; } } private IDeploymentOperations _deployments; /// <summary> /// The Service Management API includes operations for managing the /// deployments beneath your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx /// for more information) /// </summary> public virtual IDeploymentOperations Deployments { get { return this._deployments; } } private IHostedServiceOperations _hostedServices; /// <summary> /// The Service Management API includes operations for managing the /// hosted services beneath your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460812.aspx /// for more information) /// </summary> public virtual IHostedServiceOperations HostedServices { get { return this._hostedServices; } } private IOperatingSystemOperations _operatingSystems; /// <summary> /// Operations for determining the version of the Windows Azure Guest /// Operating System on which your service is running. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ff684169.aspx /// for more information) /// </summary> public virtual IOperatingSystemOperations OperatingSystems { get { return this._operatingSystems; } } private IServiceCertificateOperations _serviceCertificates; /// <summary> /// Operations for managing service certificates for your subscription. /// (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee795178.aspx /// for more information) /// </summary> public virtual IServiceCertificateOperations ServiceCertificates { get { return this._serviceCertificates; } } private IVirtualMachineDiskOperations _virtualMachineDisks; /// <summary> /// The Service Management API includes operations for managing the /// disks in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157188.aspx /// for more information) /// </summary> public virtual IVirtualMachineDiskOperations VirtualMachineDisks { get { return this._virtualMachineDisks; } } private IVirtualMachineImageOperations _virtualMachineImages; /// <summary> /// The Service Management API includes operations for managing the OS /// images in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157175.aspx /// for more information) /// </summary> public virtual IVirtualMachineImageOperations VirtualMachineImages { get { return this._virtualMachineImages; } } private IVirtualMachineOperations _virtualMachines; /// <summary> /// The Service Management API includes operations for managing the /// virtual machines in your subscription. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/jj157206.aspx /// for more information) /// </summary> public virtual IVirtualMachineOperations VirtualMachines { get { return this._virtualMachines; } } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> private ComputeManagementClient() : base() { this._deployments = new DeploymentOperations(this); this._hostedServices = new HostedServiceOperations(this); this._operatingSystems = new OperatingSystemOperations(this); this._serviceCertificates = new ServiceCertificateOperations(this); this._virtualMachineDisks = new VirtualMachineDiskOperations(this); this._virtualMachineImages = new VirtualMachineImageOperations(this); this._virtualMachines = new VirtualMachineOperations(this); this.HttpClient.Timeout = TimeSpan.FromSeconds(300); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='credentials'> /// When you create a Windows Azure subscription, it is uniquely /// identified by a subscription ID. The subscription ID forms part of /// the URI for every call that you make to the Service Management /// API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests /// are allowed. /// </param> /// <param name='baseUri'> /// The URI used as the base for all Service Management requests. /// </param> public ComputeManagementClient(SubscriptionCloudCredentials credentials, Uri baseUri) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this._credentials = credentials; this._baseUri = baseUri; this.Credentials.InitializeServiceClient(this); } /// <summary> /// Initializes a new instance of the ComputeManagementClient class. /// </summary> /// <param name='credentials'> /// When you create a Windows Azure subscription, it is uniquely /// identified by a subscription ID. The subscription ID forms part of /// the URI for every call that you make to the Service Management /// API. The Windows Azure Service ManagementAPI use mutual /// authentication of management certificates over SSL to ensure that /// a request made to the service is secure. No anonymous requests /// are allowed. /// </param> public ComputeManagementClient(SubscriptionCloudCredentials credentials) : this() { if (credentials == null) { throw new ArgumentNullException("credentials"); } this._credentials = credentials; this._baseUri = new Uri("https://management.core.windows.net"); this.Credentials.InitializeServiceClient(this); } /// <summary> /// The Get Operation Status operation returns the status of /// thespecified operation. After calling an asynchronous operation, /// you can call Get Operation Status to determine whether the /// operation has succeeded, failed, or is still in progress. (see /// http://msdn.microsoft.com/en-us/library/windowsazure/ee460783.aspx /// for more information) /// </summary> /// <param name='requestId'> /// The request ID for the request you wish to track. The request ID is /// returned in the x-ms-request-id response header for every request. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The response body contains the status of the specified asynchronous /// operation, indicating whether it has succeeded, is inprogress, or /// has failed. Note that this status is distinct from the HTTP status /// code returned for the Get Operation Status operation itself. If /// the asynchronous operation succeeded, the response body includes /// the HTTP status code for the successful request. If the /// asynchronous operation failed, the response body includes the HTTP /// status code for the failed request, and also includes error /// information regarding the failure. /// </returns> public async Task<ComputeOperationStatusResponse> GetOperationStatusAsync(string requestId, CancellationToken cancellationToken) { // Validate if (requestId == null) { throw new ArgumentNullException("requestId"); } // Tracing bool shouldTrace = CloudContext.Configuration.Tracing.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = Tracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("requestId", requestId); Tracing.Enter(invocationId, this, "GetOperationStatusAsync", tracingParameters); } // Construct URL string url = this.BaseUri + "/" + this.Credentials.SubscriptionId + "/operations/" + requestId; // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-11-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { Tracing.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { Tracing.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false), CloudExceptionType.Xml); if (shouldTrace) { Tracing.Error(invocationId, ex); } throw ex; } // Create Result ComputeOperationStatusResponse result = null; // Deserialize Response cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new ComputeOperationStatusResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement operationElement = responseDoc.Element(XName.Get("Operation", "http://schemas.microsoft.com/windowsazure")); if (operationElement != null) { XElement idElement = operationElement.Element(XName.Get("ID", "http://schemas.microsoft.com/windowsazure")); if (idElement != null) { string idInstance = idElement.Value; result.Id = idInstance; } XElement statusElement = operationElement.Element(XName.Get("Status", "http://schemas.microsoft.com/windowsazure")); if (statusElement != null) { OperationStatus statusInstance = (OperationStatus)Enum.Parse(typeof(OperationStatus), statusElement.Value, false); result.Status = statusInstance; } XElement httpStatusCodeElement = operationElement.Element(XName.Get("HttpStatusCode", "http://schemas.microsoft.com/windowsazure")); if (httpStatusCodeElement != null) { HttpStatusCode httpStatusCodeInstance = (HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpStatusCodeElement.Value, false); result.HttpStatusCode = httpStatusCodeInstance; } XElement errorElement = operationElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { ComputeOperationStatusResponse.ErrorDetails errorInstance = new ComputeOperationStatusResponse.ErrorDetails(); result.Error = errorInstance; XElement codeElement = errorElement.Element(XName.Get("Code", "http://schemas.microsoft.com/windowsazure")); if (codeElement != null) { string codeInstance = codeElement.Value; errorInstance.Code = codeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { Tracing.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Parse enum values for type CertificateFormat. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static CertificateFormat ParseCertificateFormat(string value) { if (value == "pfx") { return CertificateFormat.Pfx; } if (value == "cer") { return CertificateFormat.Cer; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type CertificateFormat to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string CertificateFormatToString(CertificateFormat value) { if (value == CertificateFormat.Pfx) { return "pfx"; } if (value == CertificateFormat.Cer) { return "cer"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type HostingResources. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static HostingResources ParseHostingResources(string value) { if (value == "WebRole") { return HostingResources.WebRole; } if (value == "WorkerRole") { return HostingResources.WorkerRole; } if (value == "WebRole|WorkerRole") { return HostingResources.WebOrWorkerRole; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type HostingResources to a string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string HostingResourcesToString(HostingResources value) { if (value == HostingResources.WebRole) { return "WebRole"; } if (value == HostingResources.WorkerRole) { return "WorkerRole"; } if (value == HostingResources.WebOrWorkerRole) { return "WebRole|WorkerRole"; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Parse enum values for type LoadBalancerProbeTransportProtocol. /// </summary> /// <param name='value'> /// The value to parse. /// </param> /// <returns> /// The enum value. /// </returns> internal static LoadBalancerProbeTransportProtocol ParseLoadBalancerProbeTransportProtocol(string value) { if (value == "tcp") { return LoadBalancerProbeTransportProtocol.Tcp; } if (value == "http") { return LoadBalancerProbeTransportProtocol.Http; } throw new ArgumentOutOfRangeException("value"); } /// <summary> /// Convert an enum of type LoadBalancerProbeTransportProtocol to a /// string. /// </summary> /// <param name='value'> /// The value to convert to a string. /// </param> /// <returns> /// The enum value as a string. /// </returns> internal static string LoadBalancerProbeTransportProtocolToString(LoadBalancerProbeTransportProtocol value) { if (value == LoadBalancerProbeTransportProtocol.Tcp) { return "tcp"; } if (value == LoadBalancerProbeTransportProtocol.Http) { return "http"; } throw new ArgumentOutOfRangeException("value"); } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Bond { using System; // Tag types used to annotate Bond schema types via Type attribute // ReSharper disable InconsistentNaming // ReSharper disable UnusedTypeParameter namespace Tag { /// <summary> /// Represents wstring Bond schema type /// </summary> public abstract class wstring { } /// <summary> /// Represents blob Bond schema type /// </summary> public abstract class blob { } /// <summary> /// Represents nullable&lt;T> Bond schema type /// </summary> public abstract class nullable<T> { } /// <summary> /// Represents bonded&lt;T> Bond schema type /// </summary> public abstract class bonded<T> { } /// <summary> /// Represents a type parameter constrained to value types /// </summary> public struct structT { } /// <summary> /// Represents unconstrained type parameter /// </summary> public abstract class classT { } } // ReSharper restore InconsistentNaming // ReSharper restore UnusedTypeParameter /// <summary> /// Specifies that a type represents Bond schema /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface, Inherited = false)] public sealed class SchemaAttribute : Attribute { } /// <summary> /// Specifies namespace of the schema, required only if different than C# namespace of the class /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface | AttributeTargets.Enum, Inherited = false)] public sealed class NamespaceAttribute : Attribute { public NamespaceAttribute(string value) { Value = value; } internal string Value { get; private set; } } /// <summary> /// Specifies field identifier. Required for all Bond fields /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] public sealed class IdAttribute : Attribute { public IdAttribute(ushort id) { Value = id; } internal ushort Value { get; private set; } } /// <summary> /// Specifies type of a field in Bond schema /// </summary> /// <remarks> /// If absent the type is inferred from C# type using the following rules: /// - numeric types map in the obvious way /// - IList, ICollection -> BT_LIST /// - IDictionary -> BT_MAP /// - ISet -> BT_SET /// - string -> BT_STRING (Utf8) /// - Bond struct fields initialized to null map to nullable /// - other fields initialized to null map to default of nothing /// The Type attribute is necessary in the following cases: /// - nullable types, e.g. Type[typeof(list&lt;nullable&lt;string>>)] /// - Utf16 string (BT_WSTRING), e.g. Type[typeof(wstring)] /// - user specified type aliases /// </remarks> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] public sealed class TypeAttribute : Attribute { public TypeAttribute(Type type) { Value = type; } internal Type Value { get; private set; } } /// <summary> /// Specifies the default value of a field /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] public sealed class DefaultAttribute : Attribute { public DefaultAttribute(object value) { Value = value; } public object Value { get; private set; } } /// <summary> /// Specifies that a field is required /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] public sealed class RequiredAttribute : Attribute { } /// <summary> /// Specifies that a field is required_optional /// </summary> [AttributeUsage(AttributeTargets.Field | AttributeTargets.Property, Inherited = false)] public sealed class RequiredOptionalAttribute : Attribute { } /// <summary> /// Specifies user defined schema attribute /// </summary> [AttributeUsage( AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Field | AttributeTargets.Interface | AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Struct , AllowMultiple = true, Inherited = false)] public sealed class AttributeAttribute : Attribute { public AttributeAttribute(string name, string value) { Name = name; Value = value; } public string Name { get; private set; } public string Value { get; private set; } } /// <summary> /// Applied to protocol readers to indicate the IParser implementation used for parsing the protocol /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class ParserAttribute : Attribute { public ParserAttribute(Type parserType) { ParserType = parserType; } internal Type ParserType { get; private set; } } /// <summary> /// Applied to protocol writers to indicate the reader type for the protocol /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class ReaderAttribute : Attribute { public ReaderAttribute(Type readerType) { ReaderType = readerType; } internal Type ReaderType { get; private set; } } /// <summary> /// Applied to protocol writers to indicate the implementation of ISerializerGenerator used to generate serializer /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class SerializerAttribute : Attribute { public SerializerAttribute(Type type) { Type = type; } internal Type Type { get; private set; } } /// <summary> /// Applied to 2-pass protocol writers to indicate the implementation of IProtocolWriter used to generate the first-pass serializer /// </summary> [AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Interface)] public sealed class FirstPassWriterAttribute : Attribute { public FirstPassWriterAttribute(Type type) { Type = type; } internal Type Type { get; private set; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Globalization; namespace System.DirectoryServices.AccountManagement { #if TESTHOOK public class PasswordInfo #else internal class PasswordInfo #endif { // // Properties exposed to the public through AuthenticablePrincipal // // LastPasswordSet private Nullable<DateTime> _lastPasswordSet = null; private LoadState _lastPasswordSetLoaded = LoadState.NotSet; public Nullable<DateTime> LastPasswordSet { [System.Security.SecurityCritical] get { return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _lastPasswordSet, PropertyNames.PwdInfoLastPasswordSet, ref _lastPasswordSetLoaded); } } // LastBadPasswordAttempt private Nullable<DateTime> _lastBadPasswordAttempt = null; private LoadState _lastBadPasswordAttemptLoaded = LoadState.NotSet; public Nullable<DateTime> LastBadPasswordAttempt { [System.Security.SecurityCritical] get { return _owningPrincipal.HandleGet<Nullable<DateTime>>(ref _lastBadPasswordAttempt, PropertyNames.PwdInfoLastBadPasswordAttempt, ref _lastBadPasswordAttemptLoaded); } } // PasswordNotRequired private bool _passwordNotRequired = false; private LoadState _passwordNotRequiredChanged = LoadState.NotSet; public bool PasswordNotRequired { [System.Security.SecurityCritical] get { return _owningPrincipal.HandleGet<bool>(ref _passwordNotRequired, PropertyNames.PwdInfoPasswordNotRequired, ref _passwordNotRequiredChanged); } [System.Security.SecurityCritical] set { _owningPrincipal.HandleSet<bool>(ref _passwordNotRequired, value, ref _passwordNotRequiredChanged, PropertyNames.PwdInfoPasswordNotRequired); } } // PasswordNeverExpires private bool _passwordNeverExpires = false; private LoadState _passwordNeverExpiresChanged = LoadState.NotSet; public bool PasswordNeverExpires { [System.Security.SecurityCritical] get { return _owningPrincipal.HandleGet<bool>(ref _passwordNeverExpires, PropertyNames.PwdInfoPasswordNeverExpires, ref _passwordNeverExpiresChanged); } [System.Security.SecurityCritical] set { _owningPrincipal.HandleSet<bool>(ref _passwordNeverExpires, value, ref _passwordNeverExpiresChanged, PropertyNames.PwdInfoPasswordNeverExpires); } } // UserCannotChangePassword private bool _cannotChangePassword = false; private LoadState _cannotChangePasswordChanged = LoadState.NotSet; private bool _cannotChangePasswordRead = false; // For this property we are doing an on demand load. The store will not load this property when load is called beacuse // the loading of this property is perf intensive. HandleGet still needs to be called to load the other object properties if // needed. We read the status directly from the store and then cache it for use later. public bool UserCannotChangePassword { [System.Security.SecurityCritical] get { _owningPrincipal.HandleGet<bool>(ref _cannotChangePassword, PropertyNames.PwdInfoCannotChangePassword, ref _cannotChangePasswordChanged); if ((_cannotChangePasswordChanged != LoadState.Changed) && !_cannotChangePasswordRead && !_owningPrincipal.unpersisted) { _cannotChangePassword = _owningPrincipal.GetStoreCtxToUse().AccessCheck(_owningPrincipal, PrincipalAccessMask.ChangePassword); _cannotChangePasswordRead = true; } return _cannotChangePassword; } [System.Security.SecurityCritical] set { _owningPrincipal.HandleSet<bool>(ref _cannotChangePassword, value, ref _cannotChangePasswordChanged, PropertyNames.PwdInfoCannotChangePassword); } } // AllowReversiblePasswordEncryption private bool _allowReversiblePasswordEncryption = false; private LoadState _allowReversiblePasswordEncryptionChanged = LoadState.NotSet; public bool AllowReversiblePasswordEncryption { [System.Security.SecurityCritical] get { return _owningPrincipal.HandleGet<bool>(ref _allowReversiblePasswordEncryption, PropertyNames.PwdInfoAllowReversiblePasswordEncryption, ref _allowReversiblePasswordEncryptionChanged); } [System.Security.SecurityCritical] set { _owningPrincipal.HandleSet<bool>(ref _allowReversiblePasswordEncryption, value, ref _allowReversiblePasswordEncryptionChanged, PropertyNames.PwdInfoAllowReversiblePasswordEncryption); } } // // Methods exposed to the public through AuthenticablePrincipal // private string _storedNewPassword = null; [System.Security.SecurityCritical] public void SetPassword(string newPassword) { if (newPassword == null) throw new ArgumentNullException("newPassword"); // If we're not persisted, we just save up the change until we're Saved if (_owningPrincipal.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "SetPassword: saving until persisted"); _storedNewPassword = newPassword; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "SetPassword: sending request"); _owningPrincipal.GetStoreCtxToUse().SetPassword(_owningPrincipal, newPassword); } } [System.Security.SecurityCritical] public void ChangePassword(string oldPassword, string newPassword) { if (oldPassword == null) throw new ArgumentNullException("oldPassword"); if (newPassword == null) throw new ArgumentNullException("newPassword"); // While you can reset the password on an unpersisted principal (and it will be used as the initial password // for the pricipal), changing the password on a principal that doesn't exist yet doesn't make sense if (_owningPrincipal.unpersisted) throw new InvalidOperationException(SR.PasswordInfoChangePwdOnUnpersistedPrinc); GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "ChangePassword: sending request"); _owningPrincipal.GetStoreCtxToUse().ChangePassword(_owningPrincipal, oldPassword, newPassword); } private bool _expirePasswordImmediately = false; [System.Security.SecurityCritical] public void ExpirePasswordNow() { // If we're not persisted, we just save up the change until we're Saved if (_owningPrincipal.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "ExpirePasswordNow: saving until persisted"); _expirePasswordImmediately = true; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "ExpirePasswordNow: sending request"); _owningPrincipal.GetStoreCtxToUse().ExpirePassword(_owningPrincipal); } } [System.Security.SecurityCritical] public void RefreshExpiredPassword() { // If we're not persisted, we undo the expiration we saved up when ExpirePasswordNow was called (if it was). if (_owningPrincipal.unpersisted) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "RefreshExpiredPassword: saving until persisted"); _expirePasswordImmediately = false; } else { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "RefreshExpiredPassword: sending request"); _owningPrincipal.GetStoreCtxToUse().UnexpirePassword(_owningPrincipal); } } // // Internal constructor // [System.Security.SecurityCritical] internal PasswordInfo(AuthenticablePrincipal principal) { _owningPrincipal = principal; } // // Private implementation // private AuthenticablePrincipal _owningPrincipal; /* // These methods implement the logic shared by all the get/set accessors for the internal properties T HandleGet<T>(ref T currentValue, string name) { // Check that we actually support this propery in our store //this.owningPrincipal.CheckSupportedProperty(name); return currentValue; } void HandleSet<T>(ref T currentValue, T newValue, ref bool changed, string name) { // Check that we actually support this propery in our store //this.owningPrincipal.CheckSupportedProperty(name); currentValue = newValue; changed = true; } */ // // Load/Store // // // Loading with query results // internal void LoadValueIntoProperty(string propertyName, object value) { if (value != null) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "LoadValueIntoProperty: name=" + propertyName + " value=" + value.ToString()); } switch (propertyName) { case (PropertyNames.PwdInfoLastPasswordSet): _lastPasswordSet = (Nullable<DateTime>)value; _lastPasswordSetLoaded = LoadState.Loaded; break; case (PropertyNames.PwdInfoLastBadPasswordAttempt): _lastBadPasswordAttempt = (Nullable<DateTime>)value; _lastBadPasswordAttemptLoaded = LoadState.Loaded; break; case (PropertyNames.PwdInfoPasswordNotRequired): _passwordNotRequired = (bool)value; _passwordNotRequiredChanged = LoadState.Loaded; break; case (PropertyNames.PwdInfoPasswordNeverExpires): _passwordNeverExpires = (bool)value; _passwordNeverExpiresChanged = LoadState.Loaded; break; case (PropertyNames.PwdInfoCannotChangePassword): _cannotChangePassword = (bool)value; _cannotChangePasswordChanged = LoadState.Loaded; break; case (PropertyNames.PwdInfoAllowReversiblePasswordEncryption): _allowReversiblePasswordEncryption = (bool)value; _allowReversiblePasswordEncryptionChanged = LoadState.Loaded; break; default: Debug.Fail(String.Format(CultureInfo.CurrentCulture, "PasswordInfo.LoadValueIntoProperty: fell off end looking for {0}", propertyName)); break; } } // // Getting changes to persist (or to build a query from a QBE filter) // // Given a property name, returns true if that property has changed since it was loaded, false otherwise. internal bool GetChangeStatusForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "GetChangeStatusForProperty: name=" + propertyName); switch (propertyName) { case (PropertyNames.PwdInfoPasswordNotRequired): return _passwordNotRequiredChanged == LoadState.Changed; case (PropertyNames.PwdInfoPasswordNeverExpires): return _passwordNeverExpiresChanged == LoadState.Changed; case (PropertyNames.PwdInfoCannotChangePassword): return _cannotChangePasswordChanged == LoadState.Changed; case (PropertyNames.PwdInfoAllowReversiblePasswordEncryption): return _allowReversiblePasswordEncryptionChanged == LoadState.Changed; case (PropertyNames.PwdInfoPassword): return (_storedNewPassword != null); case (PropertyNames.PwdInfoExpireImmediately): return (_expirePasswordImmediately != false); default: Debug.Fail(String.Format(CultureInfo.CurrentCulture, "PasswordInfo.GetChangeStatusForProperty: fell off end looking for {0}", propertyName)); return false; } } // Given a property name, returns the current value for the property. internal object GetValueForProperty(string propertyName) { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "GetValueForProperty: name=" + propertyName); switch (propertyName) { case (PropertyNames.PwdInfoPasswordNotRequired): return _passwordNotRequired; case (PropertyNames.PwdInfoPasswordNeverExpires): return _passwordNeverExpires; case (PropertyNames.PwdInfoCannotChangePassword): return _cannotChangePassword; case (PropertyNames.PwdInfoAllowReversiblePasswordEncryption): return _allowReversiblePasswordEncryption; case (PropertyNames.PwdInfoPassword): return _storedNewPassword; case (PropertyNames.PwdInfoExpireImmediately): return _expirePasswordImmediately; default: Debug.Fail(String.Format(CultureInfo.CurrentCulture, "PasswordInfo.GetValueForProperty: fell off end looking for {0}", propertyName)); return null; } } // Reset all change-tracking status for all properties on the object to "unchanged". internal void ResetAllChangeStatus() { GlobalDebug.WriteLineIf(GlobalDebug.Info, "PasswordInfo", "ResetAllChangeStatus"); _passwordNotRequiredChanged = (_passwordNotRequiredChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _passwordNeverExpiresChanged = (_passwordNeverExpiresChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _cannotChangePasswordChanged = (_cannotChangePasswordChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _allowReversiblePasswordEncryptionChanged = (_allowReversiblePasswordEncryptionChanged == LoadState.Changed) ? LoadState.Loaded : LoadState.NotSet; _storedNewPassword = null; _expirePasswordImmediately = false; } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.DocAsCode.Dfm { using System; using System.Collections.Immutable; using System.IO; using System.Linq; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.MarkdownLite; public class DfmRenderer : HtmlRenderer, IDisposable { private readonly DfmInclusionLoader _inlineInclusionHelper = new DfmInlineInclusionLoader(true); private readonly DfmInclusionLoader _blockInclusionHelper = new DfmInclusionLoader(); private readonly DfmCodeRenderer _codeRenderer = new DfmCodeRenderer(); public ImmutableDictionary<string, string> Tokens { get; set; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmXrefInlineToken token, MarkdownInlineContext context) { StringBuffer result = "<xref"; result = AppendAttribute(result, "href", token.Href); result = AppendAttribute(result, "title", token.Title); result = AppendAttribute(result, "data-throw-if-not-resolved", token.ThrowIfNotResolved.ToString()); result = AppendAttribute(result, "data-raw-source", token.SourceInfo.Markdown); result = AppendSourceInfo(result, renderer, token); result += ">"; foreach (var item in token.Content) { result += renderer.Render(item); } result += "</xref>"; return result; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmIncludeBlockToken token, MarkdownBlockContext context) { lock (_blockInclusionHelper) { return _blockInclusionHelper.Load(renderer, token.Src, token.SourceInfo, context, (DfmEngine)renderer.Engine); } } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmIncludeInlineToken token, MarkdownInlineContext context) { lock (_inlineInclusionHelper) { return _inlineInclusionHelper.Load(renderer, token.Src, token.SourceInfo, context, (DfmEngine)renderer.Engine); } } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmYamlHeaderBlockToken token, MarkdownBlockContext context) { if (string.IsNullOrEmpty(token.Content)) { return StringBuffer.Empty; } var startLine = token.SourceInfo.LineNumber; var endLine = token.SourceInfo.LineNumber + token.SourceInfo.ValidLineCount - 1; var sourceFile = token.SourceInfo.File; StringBuffer result = $"<yamlheader start=\"{startLine}\" end=\"{endLine}\""; if (!string.IsNullOrEmpty(sourceFile)) { sourceFile = StringHelper.HtmlEncode(sourceFile); result += $" sourceFile=\"{sourceFile}\""; } result += ">"; result += StringHelper.HtmlEncode(token.Content); return result + "</yamlheader>"; } public override StringBuffer Render(IMarkdownRenderer renderer, MarkdownBlockquoteBlockToken token, MarkdownBlockContext context) { StringBuffer content = string.Empty; var splitTokens = DfmBlockquoteHelper.SplitBlockquoteTokens(token.Tokens); foreach (var splitToken in splitTokens) { if (splitToken.Token is DfmSectionBlockToken) { if (!splitToken.Token.SourceInfo.Markdown.EndsWith("\n")) { Logger.LogWarning("The content part of [!div] syntax is suggested to start in a new line.", file: splitToken.Token.SourceInfo.File, line: splitToken.Token.SourceInfo.LineNumber.ToString()); } content += "<div"; content += ((DfmSectionBlockToken)splitToken.Token).Attributes; content = AppendSourceInfo(content, renderer, splitToken.Token); content += ">"; foreach (var item in splitToken.InnerTokens) { content += renderer.Render(item); } content += "</div>\n"; } else if (splitToken.Token is DfmNoteBlockToken) { if (!splitToken.Token.SourceInfo.Markdown.EndsWith("\n")) { Logger.LogWarning("The content part of NOTE/WARNING/CAUTION/IMPORTANT/NEXT syntax is suggested to start in a new line.", file: splitToken.Token.SourceInfo.File, line: splitToken.Token.SourceInfo.LineNumber.ToString()); } var noteToken = (DfmNoteBlockToken)splitToken.Token; content += "<div class=\""; content += noteToken.NoteType.ToUpper(); content += "\""; content = AppendSourceInfo(content, renderer, splitToken.Token); content += ">"; string heading; if (Tokens != null && Tokens.TryGetValue(noteToken.NoteType.ToLower(), out heading)) { content += heading; } else { content += "<h5>"; content += noteToken.NoteType.ToUpper(); content += "</h5>"; } foreach (var item in splitToken.InnerTokens) { content += renderer.Render(item); } content += "</div>\n"; } else if (splitToken.Token is DfmVideoBlockToken) { var videoToken = splitToken.Token as DfmVideoBlockToken; content += "<div class=\"embeddedvideo\"><iframe src=\""; content += videoToken.Link; content += "\" frameborder=\"0\" allowfullscreen=\"true\""; content = AppendSourceInfo(content, renderer, splitToken.Token); content += "></iframe></div>\n"; continue; } else { content += "<blockquote"; content = AppendSourceInfo(content, renderer, splitToken.Token); content += ">"; foreach (var item in splitToken.InnerTokens) { content += renderer.Render(item); } content += "</blockquote>\n"; } } return content; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmFencesToken token, IMarkdownContext context) { return _codeRenderer.Render(renderer, token, context); } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmFencesBlockToken token, MarkdownBlockContext context) { return Render(renderer, token, (IMarkdownContext)context); } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmNoteBlockToken token, MarkdownBlockContext context) { return token.Content; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmVideoBlockToken token, MarkdownBlockContext context) { return token.SourceInfo.Markdown; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmTabGroupBlockToken token, MarkdownBlockContext context) { StringBuffer sb = @"<div class=""tabGroup"" id=""tabgroup_"; var groupId = StringHelper.Escape(token.Id); sb += groupId; sb += "\""; sb = AppendSourceInfo(sb, renderer, token); sb += ">\n"; sb = RenderTabHeaders(renderer, token, sb, groupId); sb = RenderSections(renderer, token, sb, groupId); sb += "</div>\n"; return sb; } private static StringBuffer RenderTabHeaders(IMarkdownRenderer renderer, DfmTabGroupBlockToken token, StringBuffer sb, string groupId) { sb += "<ul role=\"tablist\">\n"; for (int i = 0; i < token.Items.Length; i++) { var item = token.Items[i]; sb += "<li role=\"presentation\""; if (!item.Visible) { sb += " aria-hidden=\"true\" hidden=\"hidden\""; } sb += ">\n"; sb += @"<a href=""#tabpanel_"; sb = AppendGroupId(sb, groupId, item); sb += @""" role=""tab"" aria-controls=""tabpanel_"; sb = AppendGroupId(sb, groupId, item); sb += @""" data-tab="""; sb += item.Id; if (!string.IsNullOrEmpty(item.Condition)) { sb += @""" data-condition="""; sb += item.Condition; } if (i == token.ActiveTabIndex) { sb += "\" tabindex=\"0\" aria-selected=\"true\""; } else { sb += "\" tabindex=\"-1\""; } sb = AppendSourceInfo(sb, renderer, item.Title); sb += ">"; sb += renderer.Render(item.Title); sb += "</a>\n"; sb += "</li>\n"; } sb += "</ul>\n"; return sb; } private static StringBuffer RenderSections(IMarkdownRenderer renderer, DfmTabGroupBlockToken token, StringBuffer sb, string groupId) { for (int i = 0; i < token.Items.Length; i++) { var item = token.Items[i]; sb += @"<section id=""tabpanel_"; sb = AppendGroupId(sb, groupId, item); sb += @""" role=""tabpanel"" data-tab="""; sb += item.Id; if (!string.IsNullOrEmpty(item.Condition)) { sb += @""" data-condition="""; sb += item.Condition; } if (i == token.ActiveTabIndex) { sb += "\">\n"; } else { sb += "\" aria-hidden=\"true\" hidden=\"hidden\">\n"; } sb += renderer.Render(item.Content); sb += "</section>\n"; } return sb; } private static StringBuffer AppendGroupId(StringBuffer sb, string groupId, DfmTabItemBlockToken item) { sb += groupId; sb += "_"; sb += item.Id; if (!string.IsNullOrEmpty(item.Condition)) { sb += "_"; sb += item.Condition; } return sb; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmTabTitleBlockToken token, IMarkdownContext context) { var sb = StringBuffer.Empty; foreach (var item in token.Content.Tokens) { sb += renderer.Render(item); } return sb; } public virtual StringBuffer Render(IMarkdownRenderer renderer, DfmTabContentBlockToken token, IMarkdownContext context) { var sb = StringBuffer.Empty; foreach (var item in token.Content) { sb += renderer.Render(item); } return sb; } public void Dispose() { _inlineInclusionHelper.Dispose(); _blockInclusionHelper.Dispose(); } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace WebApiDocumentation.HelpPage.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }
using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using System.Xml; namespace Orleans.Runtime.Configuration { /// <summary> /// Individual node-specific silo configuration parameters. /// </summary> [Serializable] public class NodeConfiguration : ITraceConfiguration, IStatisticsConfiguration { private readonly DateTime creationTimestamp; private string siloName; /// <summary> /// The name of this silo. /// </summary> public string SiloName { get { return siloName; } set { siloName = value; ConfigUtilities.SetTraceFileName(this, siloName, creationTimestamp); } } /// <summary> /// The DNS host name of this silo. /// This is a true host name, no IP address. It is NOT settable, equals Dns.GetHostName(). /// </summary> public string DNSHostName { get; private set; } /// <summary> /// The host name or IP address of this silo. /// This is a configurable IP address or Hostname. /// </summary> public string HostNameOrIPAddress { get; set; } private IPAddress Address { get { return ClusterConfiguration.ResolveIPAddress(HostNameOrIPAddress, Subnet, AddressType).GetResult(); } } /// <summary> /// The port this silo uses for silo-to-silo communication. /// </summary> public int Port { get; set; } /// <summary> /// The epoch generation number for this silo. /// </summary> public int Generation { get; set; } /// <summary> /// The IPEndPoint this silo uses for silo-to-silo communication. /// </summary> public IPEndPoint Endpoint { get { return new IPEndPoint(Address, Port); } } /// <summary> /// The AddressFamilyof the IP address of this silo. /// </summary> public AddressFamily AddressType { get; set; } /// <summary> /// The IPEndPoint this silo uses for (gateway) silo-to-client communication. /// </summary> public IPEndPoint ProxyGatewayEndpoint { get; set; } internal byte[] Subnet { get; set; } // from global /// <summary> /// Whether this is a primary silo (applies for dev settings only). /// </summary> public bool IsPrimaryNode { get; internal set; } /// <summary> /// Whether this is one of the seed silos (applies for dev settings only). /// </summary> public bool IsSeedNode { get; internal set; } /// <summary> /// Whether this is silo is a proxying gateway silo. /// </summary> public bool IsGatewayNode { get { return ProxyGatewayEndpoint != null; } } /// <summary> /// The MaxActiveThreads attribute specifies the maximum number of simultaneous active threads the scheduler will allow. /// Generally this number should be roughly equal to the number of cores on the node. /// Using a value of 0 will look at System.Environment.ProcessorCount to decide the number instead. /// </summary> public int MaxActiveThreads { get; set; } /// <summary> /// The DelayWarningThreshold attribute specifies the work item queuing delay threshold, at which a warning log message is written. /// That is, if the delay between enqueuing the work item and executing the work item is greater than DelayWarningThreshold, a warning log is written. /// The default value is 10 seconds. /// </summary> public TimeSpan DelayWarningThreshold { get; set; } /// <summary> /// ActivationSchedulingQuantum is a soft time limit on the duration of activation macro-turn (a number of micro-turns). /// If a activation was running its micro-turns longer than this, we will give up the thread. /// If this is set to zero or a negative number, then the full work queue is drained (MaxWorkItemsPerTurn allowing). /// </summary> public TimeSpan ActivationSchedulingQuantum { get; set; } /// <summary> /// TurnWarningLengthThreshold is a soft time limit to generate trace warning when the micro-turn executes longer then this period in CPU. /// </summary> public TimeSpan TurnWarningLengthThreshold { get; set; } internal bool InjectMoreWorkerThreads { get; set; } /// <summary> /// The LoadShedding element specifies the gateway load shedding configuration for the node. /// If it does not appear, gateway load shedding is disabled. /// </summary> public bool LoadSheddingEnabled { get; set; } /// <summary> /// The LoadLimit attribute specifies the system load, in CPU%, at which load begins to be shed. /// Note that this value is in %, so valid values range from 1 to 100, and a reasonable value is /// typically between 80 and 95. /// This value is ignored if load shedding is disabled, which is the default. /// If load shedding is enabled and this attribute does not appear, then the default limit is 95%. /// </summary> public int LoadSheddingLimit { get; set; } /// <summary> /// The values for various silo limits. /// </summary> public LimitManager LimitManager { get; private set; } private string traceFilePattern; /// <summary> /// </summary> public Severity DefaultTraceLevel { get; set; } /// <summary> /// </summary> public IList<Tuple<string, Severity>> TraceLevelOverrides { get; private set; } /// <summary> /// </summary> public bool TraceToConsole { get; set; } /// <summary> /// </summary> public string TraceFilePattern { get { return traceFilePattern; } set { traceFilePattern = value; ConfigUtilities.SetTraceFileName(this, siloName, creationTimestamp); } } /// <summary> /// </summary> public string TraceFileName { get; set; } /// <summary> /// </summary> public int LargeMessageWarningThreshold { get; set; } /// <summary> /// </summary> public bool PropagateActivityId { get; set; } /// <summary> /// </summary> public int BulkMessageLimit { get; set; } /// <summary> /// Specifies the name of the Startup class in the configuration file. /// </summary> public string StartupTypeName { get; set; } public string StatisticsProviderName { get; set; } /// <summary> /// The MetricsTableWriteInterval attribute specifies the frequency of updating the metrics in Azure table. /// The default is 30 seconds. /// </summary> public TimeSpan StatisticsMetricsTableWriteInterval { get; set; } /// <summary> /// The PerfCounterWriteInterval attribute specifies the frequency of updating the windows performance counters. /// The default is 30 seconds. /// </summary> public TimeSpan StatisticsPerfCountersWriteInterval { get; set; } /// <summary> /// The LogWriteInterval attribute specifies the frequency of updating the statistics in the log file. /// The default is 5 minutes. /// </summary> public TimeSpan StatisticsLogWriteInterval { get; set; } /// <summary> /// The WriteLogStatisticsToTable attribute specifies whether log statistics should also be written into a separate, special Azure table. /// The default is yes. /// </summary> public bool StatisticsWriteLogStatisticsToTable { get; set; } /// <summary> /// </summary> public StatisticsLevel StatisticsCollectionLevel { get; set; } private string workingStoreDir; /// <summary> /// </summary> internal string WorkingStorageDirectory { get { return workingStoreDir ?? (workingStoreDir = GetDefaultWorkingStoreDirectory()); } set { workingStoreDir = value; } } /// <summary> /// </summary> public int MinDotNetThreadPoolSize { get; set; } /// <summary> /// </summary> public bool Expect100Continue { get; set; } /// <summary> /// </summary> public int DefaultConnectionLimit { get; set; } /// <summary> /// </summary> public bool UseNagleAlgorithm { get; set; } public Dictionary<string, SearchOption> AdditionalAssemblyDirectories { get; set; } public string SiloShutdownEventName { get; set; } internal const string DEFAULT_NODE_NAME = "default"; private static readonly TimeSpan DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD = TimeSpan.FromSeconds(30); private static readonly TimeSpan DEFAULT_STATS_LOG_WRITE_PERIOD = TimeSpan.FromMinutes(5); internal static readonly StatisticsLevel DEFAULT_STATS_COLLECTION_LEVEL = StatisticsLevel.Info; private static readonly int DEFAULT_MAX_ACTIVE_THREADS = Math.Max(4, System.Environment.ProcessorCount); internal static readonly int DEFAULT_MAX_LOCAL_ACTIVATIONS = System.Environment.ProcessorCount; private const int DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE = 200; private static readonly int DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT = DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE; private static readonly TimeSpan DEFAULT_ACTIVATION_SCHEDULING_QUANTUM = TimeSpan.FromMilliseconds(100); internal const bool INJECT_MORE_WORKER_THREADS = false; public NodeConfiguration() { creationTimestamp = DateTime.UtcNow; SiloName = ""; HostNameOrIPAddress = ""; DNSHostName = Dns.GetHostName(); Port = 0; Generation = 0; AddressType = AddressFamily.InterNetwork; ProxyGatewayEndpoint = null; MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS; DelayWarningThreshold = TimeSpan.FromMilliseconds(10000); // 10,000 milliseconds ActivationSchedulingQuantum = DEFAULT_ACTIVATION_SCHEDULING_QUANTUM; TurnWarningLengthThreshold = TimeSpan.FromMilliseconds(200); InjectMoreWorkerThreads = INJECT_MORE_WORKER_THREADS; LoadSheddingEnabled = false; LoadSheddingLimit = 95; DefaultTraceLevel = Severity.Info; TraceLevelOverrides = new List<Tuple<string, Severity>>(); TraceToConsole = true; TraceFilePattern = "{0}-{1}.log"; LargeMessageWarningThreshold = Constants.LARGE_OBJECT_HEAP_THRESHOLD; PropagateActivityId = Constants.DEFAULT_PROPAGATE_E2E_ACTIVITY_ID; BulkMessageLimit = Constants.DEFAULT_LOGGER_BULK_MESSAGE_LIMIT; StatisticsMetricsTableWriteInterval = DEFAULT_STATS_METRICS_TABLE_WRITE_PERIOD; StatisticsPerfCountersWriteInterval = DEFAULT_STATS_PERF_COUNTERS_WRITE_PERIOD; StatisticsLogWriteInterval = DEFAULT_STATS_LOG_WRITE_PERIOD; StatisticsWriteLogStatisticsToTable = true; StatisticsCollectionLevel = DEFAULT_STATS_COLLECTION_LEVEL; LimitManager = new LimitManager(); MinDotNetThreadPoolSize = DEFAULT_MIN_DOT_NET_THREAD_POOL_SIZE; // .NET ServicePointManager settings / optimizations Expect100Continue = false; DefaultConnectionLimit = DEFAULT_MIN_DOT_NET_CONNECTION_LIMIT; UseNagleAlgorithm = false; AdditionalAssemblyDirectories = new Dictionary<string, SearchOption>(); } public NodeConfiguration(NodeConfiguration other) { creationTimestamp = other.creationTimestamp; SiloName = other.SiloName; HostNameOrIPAddress = other.HostNameOrIPAddress; DNSHostName = other.DNSHostName; Port = other.Port; Generation = other.Generation; AddressType = other.AddressType; ProxyGatewayEndpoint = other.ProxyGatewayEndpoint; MaxActiveThreads = other.MaxActiveThreads; DelayWarningThreshold = other.DelayWarningThreshold; ActivationSchedulingQuantum = other.ActivationSchedulingQuantum; TurnWarningLengthThreshold = other.TurnWarningLengthThreshold; InjectMoreWorkerThreads = other.InjectMoreWorkerThreads; LoadSheddingEnabled = other.LoadSheddingEnabled; LoadSheddingLimit = other.LoadSheddingLimit; DefaultTraceLevel = other.DefaultTraceLevel; TraceLevelOverrides = new List<Tuple<string, Severity>>(other.TraceLevelOverrides); TraceToConsole = other.TraceToConsole; TraceFilePattern = other.TraceFilePattern; TraceFileName = other.TraceFileName; LargeMessageWarningThreshold = other.LargeMessageWarningThreshold; PropagateActivityId = other.PropagateActivityId; BulkMessageLimit = other.BulkMessageLimit; StatisticsProviderName = other.StatisticsProviderName; StatisticsMetricsTableWriteInterval = other.StatisticsMetricsTableWriteInterval; StatisticsPerfCountersWriteInterval = other.StatisticsPerfCountersWriteInterval; StatisticsLogWriteInterval = other.StatisticsLogWriteInterval; StatisticsWriteLogStatisticsToTable = other.StatisticsWriteLogStatisticsToTable; StatisticsCollectionLevel = other.StatisticsCollectionLevel; LimitManager = new LimitManager(other.LimitManager); // Shallow copy Subnet = other.Subnet; MinDotNetThreadPoolSize = other.MinDotNetThreadPoolSize; Expect100Continue = other.Expect100Continue; DefaultConnectionLimit = other.DefaultConnectionLimit; UseNagleAlgorithm = other.UseNagleAlgorithm; StartupTypeName = other.StartupTypeName; AdditionalAssemblyDirectories = other.AdditionalAssemblyDirectories; } public override string ToString() { var sb = new StringBuilder(); sb.Append(" Silo Name: ").AppendLine(SiloName); sb.Append(" Generation: ").Append(Generation).AppendLine(); sb.Append(" Host Name or IP Address: ").AppendLine(HostNameOrIPAddress); sb.Append(" DNS Host Name: ").AppendLine(DNSHostName); sb.Append(" Port: ").Append(Port).AppendLine(); sb.Append(" Subnet: ").Append(Subnet == null ? "" : Subnet.ToStrings(x => x.ToString(), ".")).AppendLine(); sb.Append(" Preferred Address Family: ").Append(AddressType).AppendLine(); if (IsGatewayNode) { sb.Append(" Proxy Gateway: ").Append(ProxyGatewayEndpoint.ToString()).AppendLine(); } else { sb.Append(" IsGatewayNode: ").Append(IsGatewayNode).AppendLine(); } sb.Append(" IsPrimaryNode: ").Append(IsPrimaryNode).AppendLine(); sb.Append(" Scheduler: ").AppendLine(); sb.Append(" ").Append(" Max Active Threads: ").Append(MaxActiveThreads).AppendLine(); sb.Append(" ").Append(" Processor Count: ").Append(System.Environment.ProcessorCount).AppendLine(); sb.Append(" ").Append(" Delay Warning Threshold: ").Append(DelayWarningThreshold).AppendLine(); sb.Append(" ").Append(" Activation Scheduling Quantum: ").Append(ActivationSchedulingQuantum).AppendLine(); sb.Append(" ").Append(" Turn Warning Length Threshold: ").Append(TurnWarningLengthThreshold).AppendLine(); sb.Append(" ").Append(" Inject More Worker Threads: ").Append(InjectMoreWorkerThreads).AppendLine(); sb.Append(" ").Append(" MinDotNetThreadPoolSize: ").Append(MinDotNetThreadPoolSize).AppendLine(); int workerThreads; int completionPortThreads; ThreadPool.GetMinThreads(out workerThreads, out completionPortThreads); sb.Append(" ").AppendFormat(" .NET thread pool sizes - Min: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); ThreadPool.GetMaxThreads(out workerThreads, out completionPortThreads); sb.Append(" ").AppendFormat(" .NET thread pool sizes - Max: Worker Threads={0} Completion Port Threads={1}", workerThreads, completionPortThreads).AppendLine(); sb.Append(" ").AppendFormat(" .NET ServicePointManager - DefaultConnectionLimit={0} Expect100Continue={1} UseNagleAlgorithm={2}", DefaultConnectionLimit, Expect100Continue, UseNagleAlgorithm).AppendLine(); sb.Append(" Load Shedding Enabled: ").Append(LoadSheddingEnabled).AppendLine(); sb.Append(" Load Shedding Limit: ").Append(LoadSheddingLimit).AppendLine(); sb.Append(" SiloShutdownEventName: ").Append(SiloShutdownEventName).AppendLine(); sb.Append(" Debug: ").AppendLine(); sb.Append(ConfigUtilities.TraceConfigurationToString(this)); sb.Append(ConfigUtilities.IStatisticsConfigurationToString(this)); sb.Append(LimitManager); return sb.ToString(); } internal void Load(XmlElement root) { SiloName = root.LocalName.Equals("Override") ? root.GetAttribute("Node") : DEFAULT_NODE_NAME; foreach (XmlNode c in root.ChildNodes) { var child = c as XmlElement; if (child == null) continue; // Skip comment lines switch (child.LocalName) { case "Networking": if (child.HasAttribute("Address")) { HostNameOrIPAddress = child.GetAttribute("Address"); } if (child.HasAttribute("Port")) { Port = ConfigUtilities.ParseInt(child.GetAttribute("Port"), "Non-numeric Port attribute value on Networking element for " + SiloName); } if (child.HasAttribute("PreferredFamily")) { AddressType = ConfigUtilities.ParseEnum<AddressFamily>(child.GetAttribute("PreferredFamily"), "Invalid preferred address family on Networking node. Valid choices are 'InterNetwork' and 'InterNetworkV6'"); } break; case "ProxyingGateway": ProxyGatewayEndpoint = ConfigUtilities.ParseIPEndPoint(child, Subnet).GetResult(); break; case "Scheduler": if (child.HasAttribute("MaxActiveThreads")) { MaxActiveThreads = ConfigUtilities.ParseInt(child.GetAttribute("MaxActiveThreads"), "Non-numeric MaxActiveThreads attribute value on Scheduler element for " + SiloName); if (MaxActiveThreads < 1) { MaxActiveThreads = DEFAULT_MAX_ACTIVE_THREADS; } } if (child.HasAttribute("DelayWarningThreshold")) { DelayWarningThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("DelayWarningThreshold"), "Non-numeric DelayWarningThreshold attribute value on Scheduler element for " + SiloName); } if (child.HasAttribute("ActivationSchedulingQuantum")) { ActivationSchedulingQuantum = ConfigUtilities.ParseTimeSpan(child.GetAttribute("ActivationSchedulingQuantum"), "Non-numeric ActivationSchedulingQuantum attribute value on Scheduler element for " + SiloName); } if (child.HasAttribute("TurnWarningLengthThreshold")) { TurnWarningLengthThreshold = ConfigUtilities.ParseTimeSpan(child.GetAttribute("TurnWarningLengthThreshold"), "Non-numeric TurnWarningLengthThreshold attribute value on Scheduler element for " + SiloName); } if (child.HasAttribute("MinDotNetThreadPoolSize")) { MinDotNetThreadPoolSize = ConfigUtilities.ParseInt(child.GetAttribute("MinDotNetThreadPoolSize"), "Invalid ParseInt MinDotNetThreadPoolSize value on Scheduler element for " + SiloName); } if (child.HasAttribute("Expect100Continue")) { Expect100Continue = ConfigUtilities.ParseBool(child.GetAttribute("Expect100Continue"), "Invalid ParseBool Expect100Continue value on Scheduler element for " + SiloName); } if (child.HasAttribute("DefaultConnectionLimit")) { DefaultConnectionLimit = ConfigUtilities.ParseInt(child.GetAttribute("DefaultConnectionLimit"), "Invalid ParseInt DefaultConnectionLimit value on Scheduler element for " + SiloName); } if (child.HasAttribute("UseNagleAlgorithm ")) { UseNagleAlgorithm = ConfigUtilities.ParseBool(child.GetAttribute("UseNagleAlgorithm "), "Invalid ParseBool UseNagleAlgorithm value on Scheduler element for " + SiloName); } break; case "LoadShedding": if (child.HasAttribute("Enabled")) { LoadSheddingEnabled = ConfigUtilities.ParseBool(child.GetAttribute("Enabled"), "Invalid boolean value for Enabled attribute on LoadShedding attribute for " + SiloName); } if (child.HasAttribute("LoadLimit")) { LoadSheddingLimit = ConfigUtilities.ParseInt(child.GetAttribute("LoadLimit"), "Invalid integer value for LoadLimit attribute on LoadShedding attribute for " + SiloName); if (LoadSheddingLimit < 0) { LoadSheddingLimit = 0; } if (LoadSheddingLimit > 100) { LoadSheddingLimit = 100; } } break; case "Tracing": ConfigUtilities.ParseTracing(this, child, SiloName); break; case "Statistics": ConfigUtilities.ParseStatistics(this, child, SiloName); break; case "Limits": ConfigUtilities.ParseLimitValues(LimitManager, child, SiloName); break; case "Startup": if (child.HasAttribute("Type")) { StartupTypeName = child.GetAttribute("Type"); } break; case "Telemetry": ConfigUtilities.ParseTelemetry(child); break; case "AdditionalAssemblyDirectories": ConfigUtilities.ParseAdditionalAssemblyDirectories(AdditionalAssemblyDirectories, child); break; } } } private string GetDefaultWorkingStoreDirectory() { string workingStoreLocation = Environment.GetFolderPath(Environment.SpecialFolder.LocalApplicationData, Environment.SpecialFolderOption.DoNotVerify); string cacheDirBase = Path.Combine(workingStoreLocation, "OrleansData"); return cacheDirBase; } } }
// 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.Text; using System.Threading; using System.Security; using System.IO; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.CompilerServices; using System.Globalization; using System.Runtime.Versioning; namespace System.Diagnostics { // READ ME: // Modifying the order or fields of this object may require other changes // to the unmanaged definition of the StackFrameHelper class, in // VM\DebugDebugger.h. The binder will catch some of these layout problems. internal class StackFrameHelper : IDisposable { private Thread targetThread; private int[] rgiOffset; private int[] rgiILOffset; #pragma warning disable 414 // dynamicMethods is an array of System.Resolver objects, used to keep // DynamicMethodDescs alive for the lifetime of StackFrameHelper. private Object dynamicMethods; // Field is not used from managed. private IntPtr[] rgMethodHandle; private String[] rgAssemblyPath; private IntPtr[] rgLoadedPeAddress; private int[] rgiLoadedPeSize; private IntPtr[] rgInMemoryPdbAddress; private int[] rgiInMemoryPdbSize; // if rgiMethodToken[i] == 0, then don't attempt to get the portable PDB source/info private int[] rgiMethodToken; private String[] rgFilename; private int[] rgiLineNumber; private int[] rgiColumnNumber; private bool[] rgiLastFrameFromForeignExceptionStackTrace; private GetSourceLineInfoDelegate getSourceLineInfo; private int iFrameCount; #pragma warning restore 414 private delegate void GetSourceLineInfoDelegate(string assemblyPath, IntPtr loadedPeAddress, int loadedPeSize, IntPtr inMemoryPdbAddress, int inMemoryPdbSize, int methodToken, int ilOffset, out string sourceFile, out int sourceLine, out int sourceColumn); private static Type s_symbolsType = null; private static MethodInfo s_symbolsMethodInfo = null; [ThreadStatic] private static int t_reentrancy = 0; public StackFrameHelper(Thread target) { targetThread = target; rgMethodHandle = null; rgiMethodToken = null; rgiOffset = null; rgiILOffset = null; rgAssemblyPath = null; rgLoadedPeAddress = null; rgiLoadedPeSize = null; rgInMemoryPdbAddress = null; rgiInMemoryPdbSize = null; dynamicMethods = null; rgFilename = null; rgiLineNumber = null; rgiColumnNumber = null; getSourceLineInfo = null; rgiLastFrameFromForeignExceptionStackTrace = null; // 0 means capture all frames. For StackTraces from an Exception, the EE always // captures all frames. For other uses of StackTraces, we can abort stack walking after // some limit if we want to by setting this to a non-zero value. In Whidbey this was // hard-coded to 512, but some customers complained. There shouldn't be any need to limit // this as memory/CPU is no longer allocated up front. If there is some reason to provide a // limit in the future, then we should expose it in the managed API so applications can // override it. iFrameCount = 0; } // // Initializes the stack trace helper. If fNeedFileInfo is true, initializes rgFilename, // rgiLineNumber and rgiColumnNumber fields using the portable PDB reader if not already // done by GetStackFramesInternal (on Windows for old PDB format). // internal void InitializeSourceInfo(int iSkip, bool fNeedFileInfo, Exception exception) { StackTrace.GetStackFramesInternal(this, iSkip, fNeedFileInfo, exception); if (!fNeedFileInfo) return; // Check if this function is being reentered because of an exception in the code below if (t_reentrancy > 0) return; t_reentrancy++; try { if (s_symbolsMethodInfo == null) { s_symbolsType = Type.GetType( "System.Diagnostics.StackTraceSymbols, System.Diagnostics.StackTrace, Version=4.0.1.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a", throwOnError: false); if (s_symbolsType == null) return; s_symbolsMethodInfo = s_symbolsType.GetMethod("GetSourceLineInfo", BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); if (s_symbolsMethodInfo == null) return; } if (getSourceLineInfo == null) { // Create an instance of System.Diagnostics.Stacktrace.Symbols object target = Activator.CreateInstance(s_symbolsType); // Create an instance delegate for the GetSourceLineInfo method getSourceLineInfo = (GetSourceLineInfoDelegate)s_symbolsMethodInfo.CreateDelegate(typeof(GetSourceLineInfoDelegate), target); } for (int index = 0; index < iFrameCount; index++) { // If there was some reason not to try get the symbols from the portable PDB reader like the module was // ENC or the source/line info was already retrieved, the method token is 0. if (rgiMethodToken[index] != 0) { getSourceLineInfo(rgAssemblyPath[index], rgLoadedPeAddress[index], rgiLoadedPeSize[index], rgInMemoryPdbAddress[index], rgiInMemoryPdbSize[index], rgiMethodToken[index], rgiILOffset[index], out rgFilename[index], out rgiLineNumber[index], out rgiColumnNumber[index]); } } } catch { } finally { t_reentrancy--; } } void IDisposable.Dispose() { if (getSourceLineInfo != null) { IDisposable disposable = getSourceLineInfo.Target as IDisposable; if (disposable != null) { disposable.Dispose(); } } } public virtual MethodBase GetMethodBase(int i) { // There may be a better way to do this. // we got RuntimeMethodHandles here and we need to go to MethodBase // but we don't know whether the reflection info has been initialized // or not. So we call GetMethods and GetConstructors on the type // and then we fetch the proper MethodBase!! IntPtr mh = rgMethodHandle[i]; if (mh == IntPtr.Zero) return null; IRuntimeMethodInfo mhReal = RuntimeMethodHandle.GetTypicalMethodDefinition(new RuntimeMethodInfoStub(mh, this)); return RuntimeType.GetMethodBase(mhReal); } public virtual int GetOffset(int i) { return rgiOffset[i]; } public virtual int GetILOffset(int i) { return rgiILOffset[i]; } public virtual String GetFilename(int i) { return rgFilename == null ? null : rgFilename[i]; } public virtual int GetLineNumber(int i) { return rgiLineNumber == null ? 0 : rgiLineNumber[i]; } public virtual int GetColumnNumber(int i) { return rgiColumnNumber == null ? 0 : rgiColumnNumber[i]; } public virtual bool IsLastFrameFromForeignExceptionStackTrace(int i) { return (rgiLastFrameFromForeignExceptionStackTrace == null) ? false : rgiLastFrameFromForeignExceptionStackTrace[i]; } public virtual int GetNumberOfFrames() { return iFrameCount; } } // Class which represents a description of a stack trace // There is no good reason for the methods of this class to be virtual. public class StackTrace { private StackFrame[] frames; private int m_iNumOfFrames; public const int METHODS_TO_SKIP = 0; private int m_iMethodsToSkip; // Constructs a stack trace from the current location. public StackTrace() { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, false, null, null); } // Constructs a stack trace from the current location. // public StackTrace(bool fNeedFileInfo) { m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, null); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(int skipFrames) { if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, false, null, null); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(int skipFrames, bool fNeedFileInfo) { if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, null); } // Constructs a stack trace from the current location. public StackTrace(Exception e) { if (e == null) throw new ArgumentNullException(nameof(e)); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, false, null, e); } // Constructs a stack trace from the current location. // public StackTrace(Exception e, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException(nameof(e)); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(METHODS_TO_SKIP, fNeedFileInfo, null, e); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(Exception e, int skipFrames) { if (e == null) throw new ArgumentNullException(nameof(e)); if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, false, null, e); } // Constructs a stack trace from the current location, in a caller's // frame // public StackTrace(Exception e, int skipFrames, bool fNeedFileInfo) { if (e == null) throw new ArgumentNullException(nameof(e)); if (skipFrames < 0) throw new ArgumentOutOfRangeException(nameof(skipFrames), SR.ArgumentOutOfRange_NeedNonNegNum); m_iNumOfFrames = 0; m_iMethodsToSkip = 0; CaptureStackTrace(skipFrames + METHODS_TO_SKIP, fNeedFileInfo, null, e); } // Constructs a "fake" stack trace, just containing a single frame. // Does not have the overhead of a full stack trace. // public StackTrace(StackFrame frame) { frames = new StackFrame[1]; frames[0] = frame; m_iMethodsToSkip = 0; m_iNumOfFrames = 1; } [MethodImplAttribute(MethodImplOptions.InternalCall)] internal static extern void GetStackFramesInternal(StackFrameHelper sfh, int iSkip, bool fNeedFileInfo, Exception e); internal static int CalculateFramesToSkip(StackFrameHelper StackF, int iNumFrames) { int iRetVal = 0; String PackageName = "System.Diagnostics"; // Check if this method is part of the System.Diagnostics // package. If so, increment counter keeping track of // System.Diagnostics functions for (int i = 0; i < iNumFrames; i++) { MethodBase mb = StackF.GetMethodBase(i); if (mb != null) { Type t = mb.DeclaringType; if (t == null) break; String ns = t.Namespace; if (ns == null) break; if (String.Compare(ns, PackageName, StringComparison.Ordinal) != 0) break; } iRetVal++; } return iRetVal; } // Retrieves an object with stack trace information encoded. // It leaves out the first "iSkip" lines of the stacktrace. // private void CaptureStackTrace(int iSkip, bool fNeedFileInfo, Thread targetThread, Exception e) { m_iMethodsToSkip += iSkip; using (StackFrameHelper StackF = new StackFrameHelper(targetThread)) { StackF.InitializeSourceInfo(0, fNeedFileInfo, e); m_iNumOfFrames = StackF.GetNumberOfFrames(); if (m_iMethodsToSkip > m_iNumOfFrames) m_iMethodsToSkip = m_iNumOfFrames; if (m_iNumOfFrames != 0) { frames = new StackFrame[m_iNumOfFrames]; for (int i = 0; i < m_iNumOfFrames; i++) { bool fDummy1 = true; bool fDummy2 = true; StackFrame sfTemp = new StackFrame(fDummy1, fDummy2); sfTemp.SetMethodBase(StackF.GetMethodBase(i)); sfTemp.SetOffset(StackF.GetOffset(i)); sfTemp.SetILOffset(StackF.GetILOffset(i)); sfTemp.SetIsLastFrameFromForeignExceptionStackTrace(StackF.IsLastFrameFromForeignExceptionStackTrace(i)); if (fNeedFileInfo) { sfTemp.SetFileName(StackF.GetFilename(i)); sfTemp.SetLineNumber(StackF.GetLineNumber(i)); sfTemp.SetColumnNumber(StackF.GetColumnNumber(i)); } frames[i] = sfTemp; } // CalculateFramesToSkip skips all frames in the System.Diagnostics namespace, // but this is not desired if building a stack trace from an exception. if (e == null) m_iMethodsToSkip += CalculateFramesToSkip(StackF, m_iNumOfFrames); m_iNumOfFrames -= m_iMethodsToSkip; if (m_iNumOfFrames < 0) { m_iNumOfFrames = 0; } } // In case this is the same object being re-used, set frames to null else frames = null; } } // Property to get the number of frames in the stack trace // public virtual int FrameCount { get { return m_iNumOfFrames; } } // Returns a given stack frame. Stack frames are numbered starting at // zero, which is the last stack frame pushed. // public virtual StackFrame GetFrame(int index) { if ((frames != null) && (index < m_iNumOfFrames) && (index >= 0)) return frames[index + m_iMethodsToSkip]; return null; } // Returns an array of all stack frames for this stacktrace. // The array is ordered and sized such that GetFrames()[i] == GetFrame(i) // The nth element of this array is the same as GetFrame(n). // The length of the array is the same as FrameCount. // public virtual StackFrame[] GetFrames() { if (frames == null || m_iNumOfFrames <= 0) return null; // We have to return a subset of the array. Unfortunately this // means we have to allocate a new array and copy over. StackFrame[] array = new StackFrame[m_iNumOfFrames]; Array.Copy(frames, m_iMethodsToSkip, array, 0, m_iNumOfFrames); return array; } // Builds a readable representation of the stack trace // public override String ToString() { // Include a trailing newline for backwards compatibility return ToString(TraceFormat.TrailingNewLine); } // TraceFormat is Used to specify options for how the // string-representation of a StackTrace should be generated. internal enum TraceFormat { Normal, TrailingNewLine, // include a trailing new line character NoResourceLookup // to prevent infinite resource recusion } // Builds a readable representation of the stack trace, specifying // the format for backwards compatibility. internal String ToString(TraceFormat traceFormat) { bool displayFilenames = true; // we'll try, but demand may fail String word_At = "at"; String inFileLineNum = "in {0}:line {1}"; if (traceFormat != TraceFormat.NoResourceLookup) { word_At = SR.Word_At; inFileLineNum = SR.StackTrace_InFileLineNumber; } bool fFirstFrame = true; StringBuilder sb = new StringBuilder(255); for (int iFrameIndex = 0; iFrameIndex < m_iNumOfFrames; iFrameIndex++) { StackFrame sf = GetFrame(iFrameIndex); MethodBase mb = sf.GetMethod(); if (mb != null && (ShowInStackTrace(mb) || (iFrameIndex == m_iNumOfFrames - 1))) // Don't filter last frame { // We want a newline at the end of every line except for the last if (fFirstFrame) fFirstFrame = false; else sb.Append(Environment.NewLine); sb.AppendFormat(CultureInfo.InvariantCulture, " {0} ", word_At); Type declaringType = mb.DeclaringType; bool isAsync = (declaringType != null && declaringType.IsDefined(typeof(CompilerGeneratedAttribute)) && typeof(IAsyncStateMachine).IsAssignableFrom(declaringType)); // if there is a type (non global method) print it if (declaringType != null) { // Append t.FullName, replacing '+' with '.' string fullName = declaringType.FullName; for (int i = 0; i < fullName.Length; i++) { char ch = fullName[i]; sb.Append(ch == '+' ? '.' : ch); } sb.Append('.'); } sb.Append(mb.Name); // deal with the generic portion of the method if (mb is MethodInfo && ((MethodInfo)mb).IsGenericMethod) { Type[] typars = ((MethodInfo)mb).GetGenericArguments(); sb.Append('['); int k = 0; bool fFirstTyParam = true; while (k < typars.Length) { if (fFirstTyParam == false) sb.Append(','); else fFirstTyParam = false; sb.Append(typars[k].Name); k++; } sb.Append(']'); } ParameterInfo[] pi = null; try { pi = mb.GetParameters(); } catch { // The parameter info cannot be loaded, so we don't // append the parameter list. } if (pi != null) { // arguments printing sb.Append('('); bool fFirstParam = true; for (int j = 0; j < pi.Length; j++) { if (fFirstParam == false) sb.Append(", "); else fFirstParam = false; String typeName = "<UnknownType>"; if (pi[j].ParameterType != null) typeName = pi[j].ParameterType.Name; sb.Append(typeName); sb.Append(' '); sb.Append(pi[j].Name); } sb.Append(')'); } // source location printing if (displayFilenames && (sf.GetILOffset() != -1)) { // If we don't have a PDB or PDB-reading is disabled for the module, // then the file name will be null. String fileName = null; // Getting the filename from a StackFrame is a privileged operation - we won't want // to disclose full path names to arbitrarily untrusted code. Rather than just omit // this we could probably trim to just the filename so it's still mostly usefull. try { fileName = sf.GetFileName(); } catch (SecurityException) { // If the demand for displaying filenames fails, then it won't // succeed later in the loop. Avoid repeated exceptions by not trying again. displayFilenames = false; } if (fileName != null) { // tack on " in c:\tmp\MyFile.cs:line 5" sb.Append(' '); sb.AppendFormat(CultureInfo.InvariantCulture, inFileLineNum, fileName, sf.GetFileLineNumber()); } } if (sf.GetIsLastFrameFromForeignExceptionStackTrace() && !isAsync) // Skip EDI boundary for async { sb.Append(Environment.NewLine); sb.Append(SR.Exception_EndStackTraceFromPreviousThrow); } } } if (traceFormat == TraceFormat.TrailingNewLine) sb.Append(Environment.NewLine); return sb.ToString(); } private static bool ShowInStackTrace(MethodBase mb) { Debug.Assert(mb != null); return !(mb.IsDefined(typeof(StackTraceHiddenAttribute)) || (mb.DeclaringType?.IsDefined(typeof(StackTraceHiddenAttribute)) ?? false)); } } }
// Generated by the protocol buffer compiler. DO NOT EDIT! // source: booking/history/reservation_creation_summary.proto #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace HOLMS.Types.Booking.History { /// <summary>Holder for reflection information generated from booking/history/reservation_creation_summary.proto</summary> public static partial class ReservationCreationSummaryReflection { #region Descriptor /// <summary>File descriptor for booking/history/reservation_creation_summary.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static ReservationCreationSummaryReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "CjJib29raW5nL2hpc3RvcnkvcmVzZXJ2YXRpb25fY3JlYXRpb25fc3VtbWFy", "eS5wcm90bxIbaG9sbXMudHlwZXMuYm9va2luZy5oaXN0b3J5GiFzdXBwbHkv", "cm9vbV90eXBlcy9yb29tX3R5cGUucHJvdG8aKnByaW1pdGl2ZS9wYl9pbmNs", "dXNpdmVfb3BzZGF0ZV9yYW5nZS5wcm90bxouYm9va2luZy9pbmRpY2F0b3Jz", "L3Jlc2VydmF0aW9uX2luZGljYXRvci5wcm90bxowYm9va2luZy9wcmljaW5n", "L3Jlc2VydmF0aW9uX3ByaWNlX2VzdGltYXRlLnByb3RvIogDChpSZXNlcnZh", "dGlvbkNyZWF0aW9uU3VtbWFyeRJJCgtyZXNlcnZhdGlvbhgBIAEoCzI0Lmhv", "bG1zLnR5cGVzLmJvb2tpbmcuaW5kaWNhdG9ycy5SZXNlcnZhdGlvbkluZGlj", "YXRvchISCgpib29raW5nX2lkGAIgASgJEkIKCmRhdGVfcmFuZ2UYAyABKAsy", "Li5ob2xtcy50eXBlcy5wcmltaXRpdmUuUGJJbmNsdXNpdmVPcHNkYXRlUmFu", "Z2USOgoJcm9vbV90eXBlGAQgASgLMicuaG9sbXMudHlwZXMuc3VwcGx5LnJv", "b21fdHlwZXMuUm9vbVR5cGUSFQoNbnVtYmVyX2FkdWx0cxgFIAEoDRIXCg9u", "dW1iZXJfY2hpbGRyZW4YBiABKA0STQoOcHJpY2VfZXN0aW1hdGUYCCABKAsy", "NS5ob2xtcy50eXBlcy5ib29raW5nLnByaWNpbmcuUmVzZXJ2YXRpb25Qcmlj", "ZUVzdGltYXRlEgwKBHRhZ3MYCSADKAlCHqoCG0hPTE1TLlR5cGVzLkJvb2tp", "bmcuSGlzdG9yeWIGcHJvdG8z")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::HOLMS.Types.Supply.RoomTypes.RoomTypeReflection.Descriptor, global::HOLMS.Types.Primitive.PbInclusiveOpsdateRangeReflection.Descriptor, global::HOLMS.Types.Booking.Indicators.ReservationIndicatorReflection.Descriptor, global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimateReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::HOLMS.Types.Booking.History.ReservationCreationSummary), global::HOLMS.Types.Booking.History.ReservationCreationSummary.Parser, new[]{ "Reservation", "BookingId", "DateRange", "RoomType", "NumberAdults", "NumberChildren", "PriceEstimate", "Tags" }, null, null, null) })); } #endregion } #region Messages public sealed partial class ReservationCreationSummary : pb::IMessage<ReservationCreationSummary> { private static readonly pb::MessageParser<ReservationCreationSummary> _parser = new pb::MessageParser<ReservationCreationSummary>(() => new ReservationCreationSummary()); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<ReservationCreationSummary> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::HOLMS.Types.Booking.History.ReservationCreationSummaryReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationCreationSummary() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationCreationSummary(ReservationCreationSummary other) : this() { Reservation = other.reservation_ != null ? other.Reservation.Clone() : null; bookingId_ = other.bookingId_; DateRange = other.dateRange_ != null ? other.DateRange.Clone() : null; RoomType = other.roomType_ != null ? other.RoomType.Clone() : null; numberAdults_ = other.numberAdults_; numberChildren_ = other.numberChildren_; PriceEstimate = other.priceEstimate_ != null ? other.PriceEstimate.Clone() : null; tags_ = other.tags_.Clone(); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public ReservationCreationSummary Clone() { return new ReservationCreationSummary(this); } /// <summary>Field number for the "reservation" field.</summary> public const int ReservationFieldNumber = 1; private global::HOLMS.Types.Booking.Indicators.ReservationIndicator reservation_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Indicators.ReservationIndicator Reservation { get { return reservation_; } set { reservation_ = value; } } /// <summary>Field number for the "booking_id" field.</summary> public const int BookingIdFieldNumber = 2; private string bookingId_ = ""; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string BookingId { get { return bookingId_; } set { bookingId_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } /// <summary>Field number for the "date_range" field.</summary> public const int DateRangeFieldNumber = 3; private global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange dateRange_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange DateRange { get { return dateRange_; } set { dateRange_ = value; } } /// <summary>Field number for the "room_type" field.</summary> public const int RoomTypeFieldNumber = 4; private global::HOLMS.Types.Supply.RoomTypes.RoomType roomType_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Supply.RoomTypes.RoomType RoomType { get { return roomType_; } set { roomType_ = value; } } /// <summary>Field number for the "number_adults" field.</summary> public const int NumberAdultsFieldNumber = 5; private uint numberAdults_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint NumberAdults { get { return numberAdults_; } set { numberAdults_ = value; } } /// <summary>Field number for the "number_children" field.</summary> public const int NumberChildrenFieldNumber = 6; private uint numberChildren_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public uint NumberChildren { get { return numberChildren_; } set { numberChildren_ = value; } } /// <summary>Field number for the "price_estimate" field.</summary> public const int PriceEstimateFieldNumber = 8; private global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate priceEstimate_; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate PriceEstimate { get { return priceEstimate_; } set { priceEstimate_ = value; } } /// <summary>Field number for the "tags" field.</summary> public const int TagsFieldNumber = 9; private static readonly pb::FieldCodec<string> _repeated_tags_codec = pb::FieldCodec.ForString(74); private readonly pbc::RepeatedField<string> tags_ = new pbc::RepeatedField<string>(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public pbc::RepeatedField<string> Tags { get { return tags_; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as ReservationCreationSummary); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(ReservationCreationSummary other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (!object.Equals(Reservation, other.Reservation)) return false; if (BookingId != other.BookingId) return false; if (!object.Equals(DateRange, other.DateRange)) return false; if (!object.Equals(RoomType, other.RoomType)) return false; if (NumberAdults != other.NumberAdults) return false; if (NumberChildren != other.NumberChildren) return false; if (!object.Equals(PriceEstimate, other.PriceEstimate)) return false; if(!tags_.Equals(other.tags_)) return false; return true; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (reservation_ != null) hash ^= Reservation.GetHashCode(); if (BookingId.Length != 0) hash ^= BookingId.GetHashCode(); if (dateRange_ != null) hash ^= DateRange.GetHashCode(); if (roomType_ != null) hash ^= RoomType.GetHashCode(); if (NumberAdults != 0) hash ^= NumberAdults.GetHashCode(); if (NumberChildren != 0) hash ^= NumberChildren.GetHashCode(); if (priceEstimate_ != null) hash ^= PriceEstimate.GetHashCode(); hash ^= tags_.GetHashCode(); return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (reservation_ != null) { output.WriteRawTag(10); output.WriteMessage(Reservation); } if (BookingId.Length != 0) { output.WriteRawTag(18); output.WriteString(BookingId); } if (dateRange_ != null) { output.WriteRawTag(26); output.WriteMessage(DateRange); } if (roomType_ != null) { output.WriteRawTag(34); output.WriteMessage(RoomType); } if (NumberAdults != 0) { output.WriteRawTag(40); output.WriteUInt32(NumberAdults); } if (NumberChildren != 0) { output.WriteRawTag(48); output.WriteUInt32(NumberChildren); } if (priceEstimate_ != null) { output.WriteRawTag(66); output.WriteMessage(PriceEstimate); } tags_.WriteTo(output, _repeated_tags_codec); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (reservation_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(Reservation); } if (BookingId.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(BookingId); } if (dateRange_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(DateRange); } if (roomType_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(RoomType); } if (NumberAdults != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(NumberAdults); } if (NumberChildren != 0) { size += 1 + pb::CodedOutputStream.ComputeUInt32Size(NumberChildren); } if (priceEstimate_ != null) { size += 1 + pb::CodedOutputStream.ComputeMessageSize(PriceEstimate); } size += tags_.CalculateSize(_repeated_tags_codec); return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(ReservationCreationSummary other) { if (other == null) { return; } if (other.reservation_ != null) { if (reservation_ == null) { reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator(); } Reservation.MergeFrom(other.Reservation); } if (other.BookingId.Length != 0) { BookingId = other.BookingId; } if (other.dateRange_ != null) { if (dateRange_ == null) { dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange(); } DateRange.MergeFrom(other.DateRange); } if (other.roomType_ != null) { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType(); } RoomType.MergeFrom(other.RoomType); } if (other.NumberAdults != 0) { NumberAdults = other.NumberAdults; } if (other.NumberChildren != 0) { NumberChildren = other.NumberChildren; } if (other.priceEstimate_ != null) { if (priceEstimate_ == null) { priceEstimate_ = new global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate(); } PriceEstimate.MergeFrom(other.PriceEstimate); } tags_.Add(other.tags_); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: input.SkipLastField(); break; case 10: { if (reservation_ == null) { reservation_ = new global::HOLMS.Types.Booking.Indicators.ReservationIndicator(); } input.ReadMessage(reservation_); break; } case 18: { BookingId = input.ReadString(); break; } case 26: { if (dateRange_ == null) { dateRange_ = new global::HOLMS.Types.Primitive.PbInclusiveOpsdateRange(); } input.ReadMessage(dateRange_); break; } case 34: { if (roomType_ == null) { roomType_ = new global::HOLMS.Types.Supply.RoomTypes.RoomType(); } input.ReadMessage(roomType_); break; } case 40: { NumberAdults = input.ReadUInt32(); break; } case 48: { NumberChildren = input.ReadUInt32(); break; } case 66: { if (priceEstimate_ == null) { priceEstimate_ = new global::HOLMS.Types.Booking.Pricing.ReservationPriceEstimate(); } input.ReadMessage(priceEstimate_); break; } case 74: { tags_.AddEntriesFrom(input, _repeated_tags_codec); break; } } } } } #endregion } #endregion Designer generated code
/* MIT License Copyright (c) 2017 Saied Zarrinmehr 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; using System.Windows; using System.Windows.Media; using System.Windows.Shapes; using System.Windows.Controls; using System.Windows.Input; using SpatialAnalysis.FieldUtility; using SpatialAnalysis.Visualization; using SpatialAnalysis.CellularEnvironment; using SpatialAnalysis.Geometry; namespace SpatialAnalysis.FieldUtility.Visualization { /// <summary> /// The control that hosts the gradients /// </summary> public class GradientActivityVisualHost : FrameworkElement { private OSMDocument _host { get; set; } /// <summary> /// Gets or sets the scaling factor of the gradient lines. /// </summary> /// <value>The scaling factor.</value> public static double ScalingFactor { get; set; } /// <summary> /// Gets or sets the thickness of the gradient lines. /// </summary> /// <value>The thickness.</value> public static double Thickness { get; set; } private Brush _brush { get; set; } private MenuItem Visualization_Menu { get; set; } private MenuItem brush_Menu { get; set; } private MenuItem thickness_Menu { get; set; } private MenuItem draw_Menu { get; set; } private MenuItem scale_Menu { get; set; } private MenuItem clear_Menu { get; set; } // Create a collection of child visual objects. private VisualCollection _children; /// <summary> /// Initializes a new instance of the <see cref="GradientActivityVisualHost"/> class. /// </summary> public GradientActivityVisualHost() { _children = new VisualCollection(this); this.Visualization_Menu = new MenuItem() { Header = "Gradient Field Visualization" }; this.draw_Menu = new MenuItem() { Header = "Draw Active Gradient Field" }; this.draw_Menu.Click += new RoutedEventHandler(draw_Menu_Click); this.Visualization_Menu.Items.Add(this.draw_Menu); this.clear_Menu = new MenuItem() { Header = "Clear Gradient Field" }; this.clear_Menu.Click += new RoutedEventHandler(clear_Menu_Click); this._brush = Brushes.MidnightBlue; this.brush_Menu = new MenuItem() { Header = "Set Brush" }; this.brush_Menu.Click += new RoutedEventHandler(brush_Menu_Click); this.Visualization_Menu.Items.Add(this.brush_Menu); GradientActivityVisualHost.Thickness = .5; this.thickness_Menu = new MenuItem() { Header = "Set Thickness" }; this.thickness_Menu.Click += new RoutedEventHandler(thickness_Menu_Click); this.Visualization_Menu.Items.Add(this.thickness_Menu); GradientActivityVisualHost.ScalingFactor = 0.025; this.scale_Menu = new MenuItem() { Header = "Magnitude Scale for Visualization" }; this.scale_Menu.Click += new RoutedEventHandler(scale_Menu_Click); this.Visualization_Menu.Items.Add(this.scale_Menu); } private void clear_Menu_Click(object sender, RoutedEventArgs e) { this._children.Clear(); this.Visualization_Menu.Items.RemoveAt(0); this.Visualization_Menu.Items.Insert(0, this.draw_Menu); } /// <summary> /// Clears this instance. /// </summary> public void Clear() { this._host = null; this._children.Clear(); this._children = null; this.draw_Menu.Click -= draw_Menu_Click; this.clear_Menu.Click -= clear_Menu_Click; this.brush_Menu.Click -= brush_Menu_Click; this.thickness_Menu.Click -= thickness_Menu_Click; this.scale_Menu.Click -= scale_Menu_Click; this._brush = null; this.Visualization_Menu = null; this.brush_Menu = null; this.thickness_Menu = null; this.draw_Menu = null; this.scale_Menu = null; this.clear_Menu = null; } private void scale_Menu_Click(object sender, RoutedEventArgs e) { GetNumber gn = new GetNumber("Enter New Thickness Value", "New scaling factor will be applied to the size of visualized gradient field", GradientActivityVisualHost.ScalingFactor); gn.Owner = this._host; gn.ShowDialog(); GradientActivityVisualHost.ScalingFactor = gn.NumberValue; gn = null; if (this._children.Count != 0) { this.draw(); } } private void thickness_Menu_Click(object sender, RoutedEventArgs e) { GetNumber gn = new GetNumber("Enter New Thickness Value", "New thickness value will be applied to the gradients", GradientActivityVisualHost.Thickness); gn.Owner = this._host; gn.ShowDialog(); GradientActivityVisualHost.Thickness = gn.NumberValue; gn = null; if (this._children.Count != 0) { this.draw(); } } private void draw_Menu_Click(object sender, RoutedEventArgs e) { this.draw(); this.Visualization_Menu.Items.RemoveAt(0); this.Visualization_Menu.Items.Insert(0, this.clear_Menu); } private void brush_Menu_Click(object sender, RoutedEventArgs e) { BrushPicker colorPicker = new BrushPicker(this._brush); colorPicker.Owner = this._host; colorPicker.ShowDialog(); this._brush = colorPicker._Brush; colorPicker = null; if (this._children.Count != 0) { this.draw(); } } // Provide a required override for the VisualChildrenCount property. protected override int VisualChildrenCount { get { return _children.Count; } } // Provide a required override for the GetVisualChild method. protected override Visual GetVisualChild(int index) { if (index < 0 || index >= _children.Count) { throw new ArgumentOutOfRangeException(); } return _children[index]; } /// <summary> /// Sets the host. /// </summary> /// <param name="host">The main document to which this control belongs.</param> public void SetHost(OSMDocument host) { this._host = host; this.RenderTransform = this._host.RenderTransformation; this._host._activities.Items.Add(this.Visualization_Menu); //Thickness = this._host.UnitConvertor.Convert(Thickness, 4); //this._host._activities.Items.Insert(this._host._activities.Items.Count - 1, this.Visualization_Menu); } private void draw() { this._children.Clear(); if (this._host.ActiveFieldName.Items == null || this._host.ActiveFieldName.Items.Count == 0) { MessageBox.Show("Field was not assigned!"); return; } Activity activeField = null; foreach (MenuItem item in this._host.ActiveFieldName.Items) { if (item.IsChecked) { if (this._host.AllActivities.TryGetValue((string)item.Header, out activeField)) { break; } } } if (activeField == null) { MessageBox.Show("Active was not found!"); return; } Dictionary<Cell, UV> gradients = new Dictionary<Cell, UV>(); foreach (Cell item in activeField.Potentials.Keys) { UV gradient = activeField.Differentiate(item); if (gradient != null) { gradients.Add(item, gradient); } } double scale = this.getScaleFactor(); DrawingVisual drawingVisual = new DrawingVisual(); using (var dvc = drawingVisual.RenderOpen()) { StreamGeometry sg = new StreamGeometry(); using (var sgc = sg.Open()) { Point start = this.toPoint(gradients.First().Key); sgc.BeginFigure(start, false, false); foreach (KeyValuePair<Cell, UV> item in gradients) { sgc.LineTo(this.toPoint(item.Key), false, false); sgc.LineTo(this.toPoint(item.Key + item.Value * GradientActivityVisualHost.ScalingFactor), true, false); } } sg.Freeze(); Pen pen = new Pen(this._brush, GradientActivityVisualHost.Thickness / scale); dvc.DrawGeometry(null, pen, sg); } drawingVisual.Drawing.Freeze(); this._children.Add(drawingVisual); } private Point toPoint(UV p) { return new Point(p.U, p.V); } private double getScaleFactor() { double scale = this.RenderTransform.Value.M11 * this.RenderTransform.Value.M11 + this.RenderTransform.Value.M12 * this.RenderTransform.Value.M12; return Math.Sqrt(scale); } } }
using System; using System.Collections.Generic; using System.Text; namespace PlayFab { /// <summary> /// Error codes returned by PlayFabAPIs /// </summary> public enum PlayFabErrorCode { Unknown = 1, Success = 0, InvalidParams = 1000, AccountNotFound = 1001, AccountBanned = 1002, InvalidUsernameOrPassword = 1003, InvalidTitleId = 1004, InvalidEmailAddress = 1005, EmailAddressNotAvailable = 1006, InvalidUsername = 1007, InvalidPassword = 1008, UsernameNotAvailable = 1009, InvalidSteamTicket = 1010, AccountAlreadyLinked = 1011, LinkedAccountAlreadyClaimed = 1012, InvalidFacebookToken = 1013, AccountNotLinked = 1014, FailedByPaymentProvider = 1015, CouponCodeNotFound = 1016, InvalidContainerItem = 1017, ContainerNotOwned = 1018, KeyNotOwned = 1019, InvalidItemIdInTable = 1020, InvalidReceipt = 1021, ReceiptAlreadyUsed = 1022, ReceiptCancelled = 1023, GameNotFound = 1024, GameModeNotFound = 1025, InvalidGoogleToken = 1026, UserIsNotPartOfDeveloper = 1027, InvalidTitleForDeveloper = 1028, TitleNameConflicts = 1029, UserisNotValid = 1030, ValueAlreadyExists = 1031, BuildNotFound = 1032, PlayerNotInGame = 1033, InvalidTicket = 1034, InvalidDeveloper = 1035, InvalidOrderInfo = 1036, RegistrationIncomplete = 1037, InvalidPlatform = 1038, UnknownError = 1039, SteamApplicationNotOwned = 1040, WrongSteamAccount = 1041, TitleNotActivated = 1042, RegistrationSessionNotFound = 1043, NoSuchMod = 1044, FileNotFound = 1045, DuplicateEmail = 1046, ItemNotFound = 1047, ItemNotOwned = 1048, ItemNotRecycleable = 1049, ItemNotAffordable = 1050, InvalidVirtualCurrency = 1051, WrongVirtualCurrency = 1052, WrongPrice = 1053, NonPositiveValue = 1054, InvalidRegion = 1055, RegionAtCapacity = 1056, ServerFailedToStart = 1057, NameNotAvailable = 1058, InsufficientFunds = 1059, InvalidDeviceID = 1060, InvalidPushNotificationToken = 1061, NoRemainingUses = 1062, InvalidPaymentProvider = 1063, PurchaseInitializationFailure = 1064, DuplicateUsername = 1065, InvalidBuyerInfo = 1066, NoGameModeParamsSet = 1067, BodyTooLarge = 1068, ReservedWordInBody = 1069, InvalidTypeInBody = 1070, InvalidRequest = 1071, ReservedEventName = 1072, InvalidUserStatistics = 1073, NotAuthenticated = 1074, StreamAlreadyExists = 1075, ErrorCreatingStream = 1076, StreamNotFound = 1077, InvalidAccount = 1078, PurchaseDoesNotExist = 1080, InvalidPurchaseTransactionStatus = 1081, APINotEnabledForGameClientAccess = 1082, NoPushNotificationARNForTitle = 1083, BuildAlreadyExists = 1084, BuildPackageDoesNotExist = 1085, CustomAnalyticsEventsNotEnabledForTitle = 1087, InvalidSharedGroupId = 1088, NotAuthorized = 1089, MissingTitleGoogleProperties = 1090, InvalidItemProperties = 1091, InvalidPSNAuthCode = 1092, InvalidItemId = 1093, PushNotEnabledForAccount = 1094, PushServiceError = 1095, ReceiptDoesNotContainInAppItems = 1096, ReceiptContainsMultipleInAppItems = 1097, InvalidBundleID = 1098, JavascriptException = 1099, InvalidSessionTicket = 1100, UnableToConnectToDatabase = 1101, InternalServerError = 1110, InvalidReportDate = 1111, ReportNotAvailable = 1112, DatabaseThroughputExceeded = 1113, InvalidGameTicket = 1115, ExpiredGameTicket = 1116, GameTicketDoesNotMatchLobby = 1117, LinkedDeviceAlreadyClaimed = 1118, DeviceAlreadyLinked = 1119, DeviceNotLinked = 1120, PartialFailure = 1121, PublisherNotSet = 1122, ServiceUnavailable = 1123, VersionNotFound = 1124, RevisionNotFound = 1125, InvalidPublisherId = 1126, DownstreamServiceUnavailable = 1127, APINotIncludedInTitleUsageTier = 1128, DAULimitExceeded = 1129, APIRequestLimitExceeded = 1130, InvalidAPIEndpoint = 1131, BuildNotAvailable = 1132, ConcurrentEditError = 1133, ContentNotFound = 1134, CharacterNotFound = 1135, CloudScriptNotFound = 1136, ContentQuotaExceeded = 1137, InvalidCharacterStatistics = 1138, PhotonNotEnabledForTitle = 1139, PhotonApplicationNotFound = 1140, PhotonApplicationNotAssociatedWithTitle = 1141, InvalidEmailOrPassword = 1142, FacebookAPIError = 1143, InvalidContentType = 1144, KeyLengthExceeded = 1145, DataLengthExceeded = 1146, TooManyKeys = 1147, FreeTierCannotHaveVirtualCurrency = 1148, MissingAmazonSharedKey = 1149, AmazonValidationError = 1150, InvalidPSNIssuerId = 1151, PSNInaccessible = 1152, ExpiredAuthToken = 1153, FailedToGetEntitlements = 1154, FailedToConsumeEntitlement = 1155, TradeAcceptingUserNotAllowed = 1156, TradeInventoryItemIsAssignedToCharacter = 1157, TradeInventoryItemIsBundle = 1158, TradeStatusNotValidForCancelling = 1159, TradeStatusNotValidForAccepting = 1160, TradeDoesNotExist = 1161, TradeCancelled = 1162, TradeAlreadyFilled = 1163, TradeWaitForStatusTimeout = 1164, TradeInventoryItemExpired = 1165, TradeMissingOfferedAndAcceptedItems = 1166, TradeAcceptedItemIsBundle = 1167, TradeAcceptedItemIsStackable = 1168, TradeInventoryItemInvalidStatus = 1169, TradeAcceptedCatalogItemInvalid = 1170, TradeAllowedUsersInvalid = 1171, TradeInventoryItemDoesNotExist = 1172, TradeInventoryItemIsConsumed = 1173, TradeInventoryItemIsStackable = 1174, TradeAcceptedItemsMismatch = 1175, InvalidKongregateToken = 1176, FeatureNotConfiguredForTitle = 1177, NoMatchingCatalogItemForReceipt = 1178, InvalidCurrencyCode = 1179, NoRealMoneyPriceForCatalogItem = 1180, TradeInventoryItemIsNotTradable = 1181, TradeAcceptedCatalogItemIsNotTradable = 1182, UsersAlreadyFriends = 1183, LinkedIdentifierAlreadyClaimed = 1184, CustomIdNotLinked = 1185, TotalDataSizeExceeded = 1186, DeleteKeyConflict = 1187, InvalidXboxLiveToken = 1188, ExpiredXboxLiveToken = 1189, ResettableStatisticVersionRequired = 1190, NotAuthorizedByTitle = 1191, NoPartnerEnabled = 1192, InvalidPartnerResponse = 1193, APINotEnabledForGameServerAccess = 1194, StatisticNotFound = 1195, StatisticNameConflict = 1196, StatisticVersionClosedForWrites = 1197, StatisticVersionInvalid = 1198, APIClientRequestRateLimitExceeded = 1199, InvalidJSONContent = 1200, InvalidDropTable = 1201, StatisticVersionAlreadyIncrementedForScheduledInterval = 1202, StatisticCountLimitExceeded = 1203, StatisticVersionIncrementRateExceeded = 1204, ContainerKeyInvalid = 1205, CloudScriptExecutionTimeLimitExceeded = 1206, NoWritePermissionsForEvent = 1207, CloudScriptFunctionArgumentSizeExceeded = 1208, CloudScriptAPIRequestCountExceeded = 1209, CloudScriptAPIRequestError = 1210, CloudScriptHTTPRequestError = 1211, InsufficientGuildRole = 1212, GuildNotFound = 1213, OverLimit = 1214, EventNotFound = 1215, InvalidEventField = 1216, InvalidEventName = 1217, CatalogNotConfigured = 1218, OperationNotSupportedForPlatform = 1219, SegmentNotFound = 1220, StoreNotFound = 1221, InvalidStatisticName = 1222, TitleNotQualifiedForLimit = 1223, InvalidServiceLimitLevel = 1224, ServiceLimitLevelInTransition = 1225, CouponAlreadyRedeemed = 1226, GameServerBuildSizeLimitExceeded = 1227, GameServerBuildCountLimitExceeded = 1228, VirtualCurrencyCountLimitExceeded = 1229, VirtualCurrencyCodeExists = 1230, TitleNewsItemCountLimitExceeded = 1231, InvalidTwitchToken = 1232, TwitchResponseError = 1233, ProfaneDisplayName = 1234, UserAlreadyAdded = 1235, InvalidVirtualCurrencyCode = 1236, VirtualCurrencyCannotBeDeleted = 1237, IdentifierAlreadyClaimed = 1238, IdentifierNotLinked = 1239, InvalidContinuationToken = 1240, ExpiredContinuationToken = 1241, InvalidSegment = 1242, InvalidSessionId = 1243, SessionLogNotFound = 1244, InvalidSearchTerm = 1245, TwoFactorAuthenticationTokenRequired = 1246, GameServerHostCountLimitExceeded = 1247, PlayerTagCountLimitExceeded = 1248, RequestAlreadyRunning = 1249, ActionGroupNotFound = 1250, MaximumSegmentBulkActionJobsRunning = 1251, NoActionsOnPlayersInSegmentJob = 1252, DuplicateStatisticName = 1253, ScheduledTaskNameConflict = 1254, ScheduledTaskCreateConflict = 1255, InvalidScheduledTaskName = 1256, InvalidTaskSchedule = 1257 } public delegate void ErrorCallback(PlayFabError error); public class PlayFabError { public int HttpCode; public string HttpStatus; public PlayFabErrorCode Error; public string ErrorMessage; public Dictionary<string, List<string> > ErrorDetails; public object CustomData; public override string ToString() { var sb = new System.Text.StringBuilder(); if (ErrorDetails != null) { foreach (var kv in ErrorDetails) { sb.Append(kv.Key); sb.Append(": "); sb.Append(string.Join(", ", kv.Value.ToArray())); sb.Append(" | "); } } return string.Format("PlayFabError({0}, {1}, {2} {3}", Error, ErrorMessage, HttpCode, HttpStatus) + (sb.Length > 0 ? " - Details: " + sb.ToString() + ")" : ")"); } [ThreadStatic] private static StringBuilder _tempSb; public string GenerateErrorReport() { if (_tempSb == null) _tempSb = new StringBuilder(); _tempSb.Length = 0; _tempSb.Append(ErrorMessage); if (ErrorDetails != null) foreach (var pair in ErrorDetails) foreach (var msg in pair.Value) _tempSb.Append("\n").Append(pair.Key).Append(": ").Append(msg); return _tempSb.ToString(); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Diagnostics; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Xunit; namespace System.Net.Sockets.Tests { public class ArgumentValidation { // This type is used to test Socket.Select's argument validation. private sealed class LargeList : IList { private const int MaxSelect = 65536; public int Count { get { return MaxSelect + 1; } } public bool IsFixedSize { get { return true; } } public bool IsReadOnly { get { return true; } } public bool IsSynchronized { get { return false; } } public object SyncRoot { get { return null; } } public object this[int index] { get { return null; } set { } } public int Add(object value) { return -1; } public void Clear() { } public bool Contains(object value) { return false; } public void CopyTo(Array array, int index) { } public IEnumerator GetEnumerator() { return null; } public int IndexOf(object value) { return -1; } public void Insert(int index, object value) { } public void Remove(object value) { } public void RemoveAt(int index) { } } private static readonly byte[] s_buffer = new byte[1]; private static readonly IList<ArraySegment<byte>> s_buffers = new List<ArraySegment<byte>> { new ArraySegment<byte>(s_buffer) }; private static readonly SocketAsyncEventArgs s_eventArgs = new SocketAsyncEventArgs(); private static readonly Socket s_ipv4Socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); private static readonly Socket s_ipv6Socket = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp); private static void TheAsyncCallback(IAsyncResult ar) { } private static Socket GetSocket(AddressFamily addressFamily = AddressFamily.InterNetwork) { Debug.Assert(addressFamily == AddressFamily.InterNetwork || addressFamily == AddressFamily.InterNetworkV6); return addressFamily == AddressFamily.InterNetwork ? s_ipv4Socket : s_ipv6Socket; } [Fact] public void SetExclusiveAddressUse_BoundSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => { socket.ExclusiveAddressUse = true; }); } } [Fact] public void SetReceiveBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveBufferSize = -1; }); } [Fact] public void SetSendBufferSize_Negative_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendBufferSize = -1; }); } [Fact] public void SetReceiveTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveTimeout = int.MinValue; }); } [Fact] public void SetSendTimeout_LessThanNegativeOne_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendTimeout = int.MinValue; }); } [Fact] public void SetTtl_OutOfRange_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = -1; }); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().Ttl = 256; }); } [Fact] public void DontFragment_IPv6_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).DontFragment); } [Fact] public void SetDontFragment_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetworkV6).DontFragment = true; }); } [Fact] public void Bind_Throws_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Bind(null)); } [Fact] public void Connect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect(null)); } [Fact] public void Connect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.Connect(new IPEndPoint(IPAddress.Loopback, 1))); } } [Fact] public void Connect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress)null, 1)); } [Fact] public void Connect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(IPAddress.Loopback, 65536)); } [Fact] public void Connect_IPAddress_InvalidAddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).Connect(IPAddress.IPv6Loopback, 1)); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetworkV6).Connect(IPAddress.Loopback, 1)); } [Fact] public void Connect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((string)null, 1)); } [Fact] public void Connect_Host_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect("localhost", 65536)); } [Fact] public void Connect_IPAddresses_NullArray_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().Connect((IPAddress[])null, 1)); } [Fact] public void Connect_IPAddresses_EmptyArray_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().Connect(new IPAddress[0], 1)); } [Fact] public void Connect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Connect(new[] { IPAddress.Loopback }, 65536)); } [Fact] public void Accept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().Accept()); } [Fact] public void Accept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.Accept()); } } [Fact] public void Send_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Send(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Send(null, SocketFlags.None, out errorCode)); } [Fact] public void Send_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; Assert.Throws<ArgumentException>(() => GetSocket().Send(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void SendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1))); } [Fact] public void SendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendTo(s_buffer, 0, 0, SocketFlags.None, null)); } [Fact] public void SendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint)); } [Fact] public void SendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, -1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().SendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint)); } [Fact] public void Receive_Buffer_NullBuffer_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, 0, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, -1, 0, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { SocketError errorCode; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, -1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, out errorCode)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().Receive(s_buffer, s_buffer.Length, 1, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_NullBuffers_Throws_ArgumentNull() { SocketError errorCode; Assert.Throws<ArgumentNullException>(() => GetSocket().Receive(null, SocketFlags.None, out errorCode)); } [Fact] public void Receive_Buffers_EmptyBuffers_Throws_Argument() { SocketError errorCode; Assert.Throws<ArgumentException>(() => GetSocket().Receive(new List<ArraySegment<byte>>(), SocketFlags.None, out errorCode)); } [Fact] public void ReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint)); } [Fact] public void ReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(null, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, -1, s_buffer.Length, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, -1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, ref flags, ref remote, out packetInfo)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().ReceiveMessageFrom(s_buffer, s_buffer.Length, 1, ref flags, ref remote, out packetInfo)); } [Fact] public void ReceiveMessageFrom_NotBound_Throws_InvalidOperation() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<InvalidOperationException>(() => GetSocket().ReceiveMessageFrom(s_buffer, 0, 0, ref flags, ref remote, out packetInfo)); } [Fact] public void SetSocketOption_Object_ObjectNull_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, (object)null)); } [Fact] public void SetSocketOption_Linger_NotLingerOption_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new object())); } [Fact] public void SetSocketOption_Linger_InvalidLingerTime_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, -1))); Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.Linger, new LingerOption(true, (int)ushort.MaxValue + 1))); } [Fact] public void SetSocketOption_IPMulticast_NotIPMulticastOption_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.AddMembership, new object())); Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IP, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_IPv6Multicast_NotIPMulticastOption_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.AddMembership, new object())); Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.IPv6, SocketOptionName.DropMembership, new object())); } [Fact] public void SetSocketOption_Object_InvalidOptionName_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().SetSocketOption(SocketOptionLevel.Socket, SocketOptionName.NoDelay, new object())); } [Fact] public void Select_NullOrEmptyLists_Throws_ArgumentNull() { var emptyList = new List<Socket>(); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, null, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, null, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(null, emptyList, emptyList, -1)); Assert.Throws<ArgumentNullException>(() => Socket.Select(emptyList, emptyList, emptyList, -1)); } [Fact] public void Select_LargeList_Throws_ArgumentOutOfRange() { var largeList = new LargeList(); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(largeList, null, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, largeList, null, -1)); Assert.Throws<ArgumentOutOfRangeException>(() => Socket.Select(null, null, largeList, -1)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in AcceptAsync that dereferences null SAEA argument")] [Fact] public void AcceptAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().AcceptAsync(null)); } [Fact] public void AcceptAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; Assert.Throws<ArgumentException>(() => GetSocket().AcceptAsync(eventArgs)); } [Fact] public void AcceptAsync_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().AcceptAsync(s_eventArgs)); } [Fact] public void AcceptAsync_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.AcceptAsync(s_eventArgs)); } } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveAsync that dereferences null SAEA argument")] [Fact] public void ConnectAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(null)); } [Fact] public void ConnectAsync_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; Assert.Throws<ArgumentException>(() => GetSocket().ConnectAsync(eventArgs)); } [Fact] public void ConnectAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ConnectAsync(s_eventArgs)); } [Fact] public void ConnectAsync_ListeningSocket_Throws_InvalidOperation() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.Loopback, 1) }; using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.ConnectAsync(eventArgs)); } } [Fact] public void ConnectAsync_AddressFamily_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6) }; Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); eventArgs.RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).ConnectAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ConnectAsync that dereferences null SAEA argument")] [Fact] public void ConnectAsync_Static_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, null)); } [Fact] public void ConnectAsync_Static_BufferList_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { BufferList = s_buffers }; Assert.Throws<ArgumentException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, eventArgs)); } [Fact] public void ConnectAsync_Static_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.ConnectAsync(SocketType.Stream, ProtocolType.Tcp, s_eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveAsync that dereferences null SAEA argument")] [Fact] public void ReceiveAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveAsync(null)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveFromAsync that dereferences null SAEA argument")] [Fact] public void ReceiveFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(null)); } [Fact] public void ReceiveFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveFromAsync(s_eventArgs)); } [Fact] public void ReceiveFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in ReceiveMessageFromAsync that dereferences null SAEA argument")] [Fact] public void ReceiveMessageFromAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(null)); } [Fact] public void ReceiveMessageFromAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().ReceiveMessageFromAsync(s_eventArgs)); } [Fact] public void ReceiveMessageFromAsync_AddressFamily_Throws_Argument() { var eventArgs = new SocketAsyncEventArgs { RemoteEndPoint = new IPEndPoint(IPAddress.IPv6Loopback, 1) }; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendAsync that dereferences null SAEA argument")] [Fact] public void SendAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendAsync(null)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA argument")] [Fact] public void SendPacketsAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(null)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendPacketsAsync that dereferences null SAEA.SendPacketsElements")] [Fact] public void SendPacketsAsync_NullSendPacketsElements_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendPacketsAsync(s_eventArgs)); } [Fact] public void SendPacketsAsync_NotConnected_Throws_NotSupported() { var eventArgs = new SocketAsyncEventArgs { SendPacketsElements = new SendPacketsElement[0] }; Assert.Throws<NotSupportedException>(() => GetSocket().SendPacketsAsync(eventArgs)); } [SkipOnTargetFramework(TargetFrameworkMonikers.NetFramework, "Bug in SendToAsync that dereferences null SAEA argument")] [Fact] public void SendToAsync_NullAsyncEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(null)); } [Fact] public void SendToAsync_NullRemoteEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().SendToAsync(s_eventArgs)); } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_DnsEndPoint_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new DnsEndPoint("localhost", 12345))); } } [Fact] public async Task Socket_Connect_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } await accept; } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_StringHost_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect("localhost", 12345)); } } [Fact] public async Task Socket_Connect_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] public async Task Socket_Connect_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); Task accept = host.AcceptAsync(); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { s.Connect(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port); } await accept; } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_Connect_MultipleAddresses_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => s.Connect(new[] { IPAddress.Loopback }, 12345)); } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_ConnectAsync_DnsEndPoint_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync(new DnsEndPoint("localhost", 12345)); }); } } [Fact] public async Task Socket_ConnectAsync_DnsEndPointWithIPAddressString_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(new DnsEndPoint(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port))); } } } [Fact] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix public void Socket_ConnectAsync_StringHost_ExposedHandle_NotSupported() { using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { IntPtr ignored = s.Handle; Assert.Throws<PlatformNotSupportedException>(() => { s.ConnectAsync("localhost", 12345); }); } } [Fact] public async Task Socket_ConnectAsync_IPv4AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Fact] public async Task Socket_ConnectAsync_IPv6AddressAsStringHost_Supported() { using (Socket host = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { host.Bind(new IPEndPoint(IPAddress.IPv6Loopback, 0)); host.Listen(1); using (Socket s = new Socket(AddressFamily.InterNetworkV6, SocketType.Stream, ProtocolType.Tcp)) { await Task.WhenAll( host.AcceptAsync(), s.ConnectAsync(IPAddress.IPv6Loopback.ToString(), ((IPEndPoint)host.LocalEndPoint).Port)); } } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix [InlineData(0)] [InlineData(1)] public void Connect_ConnectTwice_NotSupported(int invalidatingAction) { using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { switch (invalidatingAction) { case 0: IntPtr handle = client.Handle; // exposing the underlying handle break; case 1: client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option break; } // // Connect once, to an invalid address, expecting failure // EndPoint ep = new IPEndPoint(IPAddress.Broadcast, 1234); Assert.ThrowsAny<SocketException>(() => client.Connect(ep)); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.Connect(ep)); } } [Theory] [PlatformSpecific(TestPlatforms.AnyUnix)] // API throws PNSE on Unix [InlineData(0)] [InlineData(1)] public void ConnectAsync_ConnectTwice_NotSupported(int invalidatingAction) { AutoResetEvent completed = new AutoResetEvent(false); using (Socket client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { switch (invalidatingAction) { case 0: IntPtr handle = client.Handle; // exposing the underlying handle break; case 1: client.SetSocketOption(SocketOptionLevel.IP, SocketOptionName.Debug, 1); // untracked socket option break; } // // Connect once, to an invalid address, expecting failure // SocketAsyncEventArgs args = new SocketAsyncEventArgs(); args.RemoteEndPoint = new IPEndPoint(IPAddress.Broadcast, 1234); args.Completed += delegate { completed.Set(); }; if (client.ConnectAsync(args)) { Assert.True(completed.WaitOne(5000), "IPv4: Timed out while waiting for connection"); } Assert.NotEqual(SocketError.Success, args.SocketError); // // Connect again, expecting PlatformNotSupportedException // Assert.Throws<PlatformNotSupportedException>(() => client.ConnectAsync(args)); } } [Fact] public void BeginAccept_NotBound_Throws_InvalidOperation() { Assert.Throws<InvalidOperationException>(() => GetSocket().BeginAccept(TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().AcceptAsync(); }); } [Fact] public void BeginAccept_NotListening_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); Assert.Throws<InvalidOperationException>(() => socket.BeginAccept(TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.AcceptAsync(); }); } } [Fact] public void EndAccept_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndAccept(null)); } [Fact] public void BeginConnect_EndPoint_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((EndPoint)null, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((EndPoint)null); }); } [Fact] public void BeginConnect_EndPoint_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new IPEndPoint(IPAddress.Loopback, 1)); }); } } [Fact] public void BeginConnect_EndPoint_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect( new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6), TheAsyncCallback, null)); Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetwork).ConnectAsync( new DnsEndPoint("localhost", 1, AddressFamily.InterNetworkV6)); }); } [Fact] public void BeginConnect_Host_NullHost_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((string)null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((string)null, 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_Host_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect("localhost", port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync("localhost", port); }); } [Fact] public void BeginConnect_Host_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect("localhost", 1, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync("localhost", 1); }); } } [Fact] public void BeginConnect_IPAddress_NullIPAddress_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress)null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress)null, 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_IPAddress_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(IPAddress.Loopback, port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(IPAddress.Loopback, 65536); }); } [Fact] public void BeginConnect_IPAddress_AddressFamily_Throws_NotSupported() { Assert.Throws<NotSupportedException>(() => GetSocket(AddressFamily.InterNetwork).BeginConnect(IPAddress.IPv6Loopback, 1, TheAsyncCallback, null)); Assert.Throws<NotSupportedException>(() => { GetSocket(AddressFamily.InterNetwork).ConnectAsync(IPAddress.IPv6Loopback, 1); }); } [Fact] public void BeginConnect_IPAddresses_NullIPAddresses_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginConnect((IPAddress[])null, 1, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ConnectAsync((IPAddress[])null, 1); }); } [Fact] public void BeginConnect_IPAddresses_EmptyIPAddresses_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginConnect(new IPAddress[0], 1, TheAsyncCallback, null)); Assert.Throws<ArgumentException>(() => { GetSocket().ConnectAsync(new IPAddress[0], 1); }); } [Theory] [InlineData(-1)] [InlineData(65536)] public void BeginConnect_IPAddresses_InvalidPort_Throws_ArgumentOutOfRange(int port) { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginConnect(new[] { IPAddress.Loopback }, port, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ConnectAsync(new[] { IPAddress.Loopback }, port); }); } [Fact] public void BeginConnect_IPAddresses_ListeningSocket_Throws_InvalidOperation() { using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => socket.BeginConnect(new[] { IPAddress.Loopback }, 1, TheAsyncCallback, null)); } using (var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)) { socket.Bind(new IPEndPoint(IPAddress.Loopback, 0)); socket.Listen(1); Assert.Throws<InvalidOperationException>(() => { socket.ConnectAsync(new[] { IPAddress.Loopback }, 1); }); } } [Fact] public void EndConnect_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndConnect(null)); } [Fact] public void EndConnect_UnrelatedAsyncResult_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().EndConnect(Task.CompletedTask)); } [Fact] public void BeginSend_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); }); } [Fact] public void BeginSend_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); }); } [Fact] public void BeginSend_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSend(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); }); } [Fact] public void BeginSend_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSend(null, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendAsync(null, SocketFlags.None); }); } [Fact] public void BeginSend_Buffers_EmptyBuffers_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginSend(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentException>(() => { GetSocket().SendAsync(new List<ArraySegment<byte>>(), SocketFlags.None); }); } [Fact] public void EndSend_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSend(null)); } [Fact] public void EndSend_UnrelatedAsyncResult_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().EndSend(Task.CompletedTask)); } [Fact] public void BeginSendTo_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(null, 0, 0, SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1), TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, new IPEndPoint(IPAddress.Loopback, 1)); }); } [Fact] public void BeginSendTo_NullEndPoint_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginSendTo(s_buffer, 0, 0, SocketFlags.None, null, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, null); }); } [Fact] public void BeginSendTo_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, -1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); }); } [Fact] public void BeginSendTo_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, -1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginSendTo(s_buffer, s_buffer.Length, 1, SocketFlags.None, endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().SendToAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); }); } [Fact] public void EndSendTo_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndSendTo(null)); } [Fact] public void EndSendto_UnrelatedAsyncResult_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().EndSendTo(Task.CompletedTask)); } [Fact] public void BeginReceive_Buffer_NullBuffer_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, 0, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffer_InvalidOffset_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, -1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length + 1, 0, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, -1, 0), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, 0), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffer_InvalidCount_Throws_ArgumentOutOfRange() { Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, -1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceive(s_buffer, s_buffer.Length, 1, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None); }); } [Fact] public void BeginReceive_Buffers_NullBuffers_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceive(null, SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveAsync(null, SocketFlags.None); }); } [Fact] public void BeginReceive_Buffers_EmptyBuffers_Throws_Argument() { Assert.Throws<ArgumentException>(() => GetSocket().BeginReceive(new List<ArraySegment<byte>>(), SocketFlags.None, TheAsyncCallback, null)); Assert.Throws<ArgumentException>(() => { GetSocket().ReceiveAsync(new List<ArraySegment<byte>>(), SocketFlags.None); }); } [Fact] public void EndReceive_NullAsyncResult_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceive(null)); } [Fact] public void BeginReceiveFrom_NullBuffer_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(null, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint endpoint = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_AddressFamily_Throws_Argument() { EndPoint endpoint = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentException>(() => { GetSocket(AddressFamily.InterNetwork).ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, -1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, endpoint); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, endpoint); }); } [Fact] public void BeginReceiveFrom_NotBound_Throws_InvalidOperation() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveFrom(s_buffer, 0, 0, SocketFlags.None, ref endpoint, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, endpoint); }); } [Fact] public void EndReceiveFrom_NullAsyncResult_Throws_ArgumentNull() { EndPoint endpoint = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveFrom(null, ref endpoint)); } [Fact] public void BeginReceiveMessageFrom_NullBuffer_Throws_ArgumentNull() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(null, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(null, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { EndPoint remote = null; Assert.Throws<ArgumentNullException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentNullException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_AddressFamily_Throws_Argument() { EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentException>(() => { GetSocket(AddressFamily.InterNetwork).ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_InvalidOffset_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, -1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length + 1, s_buffer.Length, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, -1, s_buffer.Length), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length + 1, s_buffer.Length), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_InvalidSize_Throws_ArgumentOutOfRange() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, -1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, s_buffer.Length + 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, s_buffer.Length, 1, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<ArgumentOutOfRangeException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, -1), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, s_buffer.Length + 1), SocketFlags.None, remote); }); Assert.ThrowsAny<ArgumentException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, s_buffer.Length, 1), SocketFlags.None, remote); }); } [Fact] public void BeginReceiveMessageFrom_NotBound_Throws_InvalidOperation() { EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); Assert.Throws<InvalidOperationException>(() => GetSocket().BeginReceiveMessageFrom(s_buffer, 0, 0, SocketFlags.None, ref remote, TheAsyncCallback, null)); Assert.Throws<InvalidOperationException>(() => { GetSocket().ReceiveMessageFromAsync(new ArraySegment<byte>(s_buffer, 0, 0), SocketFlags.None, remote); }); } [Fact] public void EndReceiveMessageFrom_NullEndPoint_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = null; IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_AddressFamily_Throws_Argument() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.IPv6Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentException>(() => GetSocket(AddressFamily.InterNetwork).EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void EndReceiveMessageFrom_NullAsyncResult_Throws_ArgumentNull() { SocketFlags flags = SocketFlags.None; EndPoint remote = new IPEndPoint(IPAddress.Loopback, 1); IPPacketInformation packetInfo; Assert.Throws<ArgumentNullException>(() => GetSocket().EndReceiveMessageFrom(null, ref flags, ref remote, out packetInfo)); } [Fact] public void CancelConnectAsync_NullEventArgs_Throws_ArgumentNull() { Assert.Throws<ArgumentNullException>(() => Socket.CancelConnectAsync(null)); } } }
//------------------------------------------------------------------------------ // <copyright file="IImplicitResourceProvider.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace System.Web.Compilation { using System; using System.Collections; using System.Collections.Specialized; using System.Reflection; using System.IO; using System.CodeDom; using System.Globalization; using System.Resources; using System.Web.Compilation; using System.Web.Util; using System.Web.UI; using System.Security.Permissions; /* * Interface to access implicit (automatic) page resources */ public interface IImplicitResourceProvider { /* * Retrieve a resource object for the passed in key and culture */ object GetObject(ImplicitResourceKey key, CultureInfo culture); /* * Return a collection of ImplicitResourceKey's for the given prefix */ ICollection GetImplicitResourceKeys(string keyPrefix); } /* * Contains fields which identify a specific implicit resource key */ public sealed class ImplicitResourceKey { private string _filter; private string _keyPrefix; private string _property; public ImplicitResourceKey() { } public ImplicitResourceKey(string filter, string keyPrefix, string property) { _filter = filter; _keyPrefix = keyPrefix; _property = property; } /* * The filter, if any */ public string Filter { get { return _filter; } set { _filter = value; } } /* * The prefix, as appears on tag's meta:resourcekey attributes */ public string KeyPrefix { get { return _keyPrefix; } set { _keyPrefix = value; } } /* * The property, possibly including sub-properties (e.g. MyProp.MySubProp) */ public string Property { get { return _property; } set { _property = value; } } } /* * IImplicitResourceProvider implementation on top of an arbitrary IResourceProvider */ internal class DefaultImplicitResourceProvider: IImplicitResourceProvider { private IResourceProvider _resourceProvider; private IDictionary _implicitResources; private bool _attemptedGetPageResources; internal DefaultImplicitResourceProvider(IResourceProvider resourceProvider) { _resourceProvider = resourceProvider; } public virtual object GetObject(ImplicitResourceKey entry, CultureInfo culture) { // Put together the full resource key based on the ImplicitResourceKey string fullResourceKey = ConstructFullKey(entry); // Look it up in the resource provider return _resourceProvider.GetObject(fullResourceKey, culture); } public virtual ICollection GetImplicitResourceKeys(string keyPrefix) { // Try to get the page resources EnsureGetPageResources(); // If there aren't any, return null if (_implicitResources == null) return null; // Return the collection of resources for this key prefix return (ICollection) _implicitResources[keyPrefix]; } /* * Create a dictionary, in which the key is a resource key (as found on meta:resourcekey * attributes), and the value is an ArrayList containing all the resources for that * resource key. Each element of the ArrayList is an ImplicitResourceKey */ internal void EnsureGetPageResources() { // If we already attempted to get them, don't do it again if (_attemptedGetPageResources) return; _attemptedGetPageResources = true; IResourceReader resourceReader = _resourceProvider.ResourceReader; if (resourceReader == null) return; _implicitResources = new Hashtable(StringComparer.OrdinalIgnoreCase); // Enumerate through all the page resources foreach (DictionaryEntry entry in resourceReader) { // Attempt to parse the key into a ImplicitResourceKey ImplicitResourceKey implicitResKey = ParseFullKey((string) entry.Key); // If we couldn't parse it as such, skip it if (implicitResKey == null) continue; // Check if we already have an entry for this resource key prefix ArrayList controlResources = (ArrayList) _implicitResources[implicitResKey.KeyPrefix]; // If not, create one if (controlResources == null) { controlResources = new ArrayList(); _implicitResources[implicitResKey.KeyPrefix] = controlResources; } // Add an entry in the ArrayList for this property controlResources.Add(implicitResKey); } } /* * Parse a complete page resource key into a ImplicitResourceKey. * Return null if the key does not appear to be meant for implict resources. */ private static ImplicitResourceKey ParseFullKey(string key) { string filter = String.Empty; // A page resource key looks like [myfilter:]MyResKey.MyProp[.MySubProp] // Check if there is a filter if (key.IndexOf(':') > 0) { string[] parts = key.Split(':'); // Shouldn't be multiple ':'. If there is, ignore it if (parts.Length > 2) return null; filter = parts[0]; key = parts[1]; } int periodIndex = key.IndexOf('.'); // There should be at least one period, for the meta:resourcekey part. If not, ignore. if (periodIndex <= 0) return null; string keyPrefix = key.Substring(0, periodIndex); // The rest of the string is the property (e.g. MyProp.MySubProp) string property = key.Substring(periodIndex+1); // Create a ImplicitResourceKey with the parsed data ImplicitResourceKey implicitResKey = new ImplicitResourceKey(); implicitResKey.Filter = filter; implicitResKey.KeyPrefix = keyPrefix; implicitResKey.Property = property; return implicitResKey; } private static string ConstructFullKey(ImplicitResourceKey entry) { string key = entry.KeyPrefix + "." + entry.Property; if (entry.Filter.Length > 0) key = entry.Filter + ":" + key; return key; } } }
//! \file ImageAinos.cs //! \date Sun Apr 05 04:16:27 2015 //! \brief Ainos 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 System; using System.ComponentModel.Composition; using System.IO; using System.Windows.Media; using GameRes.Utility; namespace GameRes.Formats.Ags { public class CgMetaData : ImageMetaData { public int Type; public int Right, Bottom; } [Export(typeof(ImageFormat))] [ExportMetadata("Priority", -1)] public class CgFormat : ImageFormat { public override string Tag { get { return "CG"; } } public override string Description { get { return "Anime Game System image format"; } } public override uint Signature { get { return 0; } } public override void Write (Stream file, ImageData image) { throw new System.NotImplementedException ("CgFormat.Write not implemented"); } public override ImageMetaData ReadMetaData (IBinaryStream file) { int sig = file.ReadByte(); if (sig >= 0x20) return null; int width = file.ReadInt16(); int height = file.ReadInt16(); if (width <= 0 || height <= 0 || width > 4096 || height > 4096) return null; var meta = new CgMetaData { Width = (uint)width, Height = (uint)height, BPP = 24, Type = sig, }; if (0 != (sig & 7)) { meta.OffsetX = file.ReadInt16(); meta.OffsetY = file.ReadInt16(); meta.Right = file.ReadInt16(); meta.Bottom = file.ReadInt16(); if (meta.OffsetX > meta.Right || meta.OffsetY > meta.Bottom || meta.Right > width || meta.Bottom > height || meta.OffsetX < 0 || meta.OffsetY < 0) return null; } return meta; } public override ImageData Read (IBinaryStream stream, ImageMetaData info) { using (var reader = new Reader (stream, (CgMetaData)info)) return reader.Image; } internal sealed class Reader : IImageDecoder { IBinaryStream m_input; ImageData m_image; byte[] m_output; int m_type; int m_width; int m_height; int m_left; int m_top; int m_right; int m_bottom; bool m_should_dispose; public Stream Source { get { m_input.Position = 0; return m_input.AsStream; } } public ImageFormat SourceFormat { get { return null; } } public ImageMetaData Info { get; private set; } public ImageData Image { get { if (null == m_image) { Unpack(); m_image = ImageData.Create (Info, PixelFormats.Bgr24, null, m_output, m_width*3); } return m_image; } } public byte[] Data { get { return m_output; } } public Reader (IBinaryStream file, CgMetaData info) : this (file, info, null, true) { } public Reader (IBinaryStream file, CgMetaData info, byte[] base_image, bool leave_open = false) { m_type = info.Type; m_width = (int)info.Width; m_height = (int)info.Height; m_left = info.OffsetX; m_top = info.OffsetY; m_right = info.Right == 0 ? m_width : info.Right; m_bottom = info.Bottom == 0 ? m_height : info.Bottom; m_output = base_image ?? CreateBackground(); m_input = file; Info = info; ShiftTable = InitShiftTable(); if (0 != (info.Type & 7)) m_input.Position = 13; else m_input.Position = 5; m_should_dispose = !leave_open; } static readonly short[] ShiftX = new short[] { // 409b6c 0, -1, -3, -2, -1, 0, 1, 2 }; static readonly short[] ShiftY = new short[] { // 409b7c 0, 0, -1, -1, -1, -1, -1, -1 }; readonly int[] ShiftTable; private int[] InitShiftTable () { var table = new int[8]; for (int i = 0; i < 8; ++i) { table[i] = 3 * (ShiftX[i] + ShiftY[i] * m_width); } return table; } private byte[] CreateBackground () { var bg = new byte[3*m_width*m_height]; for (int i = 1; i < bg.Length; i += 3) bg[i] = 0xFF; return bg; } public void Unpack () { if (0 != (m_type & 0x10)) UnpackRGB(); else UnpackIndexed(); } public void UnpackRGB () { int right = 3 * (m_width * m_top + m_right); int left = 3 * (m_width * m_top + m_left); for (int i = m_top; i != m_bottom; ++i) { int dst = left; while (dst != right) { byte v9 = m_input.ReadUInt8(); if (0 != (v9 & 0x80)) { if (0 != (v9 & 0x40)) { m_output[dst] = (byte)(m_output[dst - 3] + ((v9 >> 3) & 6) - 2); m_output[dst + 1] = (byte)(m_output[dst - 2] + ((v9 >> 1) & 6) - 2); m_output[dst + 2] = (byte)(m_output[dst - 1] + ((v9 & 3) + 127) * 2); } else { byte v15 = m_input.ReadUInt8(); m_output[dst] = (byte)(((v9 << 1) + (v15 & 1)) << 1); m_output[dst + 1] = (byte)(v15 & 0xfe); m_output[dst + 2] = m_input.ReadUInt8(); } dst += 3; continue; } uint shift = (uint)v9 >> 4; int count = v9 & 0xF; if (0 == count) { count = (int)m_input.ReadUInt8() + 15; if (270 == count) { int v12; do { v12 = m_input.ReadUInt8(); count += v12; } while (v12 == 0xff); } } if (0 != shift) { int src = dst + ShiftTable[shift]; Binary.CopyOverlapped (m_output, src, dst, count * 3); } dst += 3 * count; } left += m_width*3; //640*3; right += m_width*3; //640*3; } } public void UnpackIndexed () { byte[] palette = m_input.ReadBytes (0x180); int right = 3 * (m_width * m_top + m_right); int left = 3 * (m_width * m_top + m_left); // 3 * (Rect.left + 640 * Rect.top); for (int i = m_top; i != m_bottom; ++i) { int dst = left; while (dst != right) { byte v13 = m_input.ReadUInt8(); if (0 != (v13 & 0x80)) { int color = 3 * (v13 & 0x7F); m_output[dst] = palette[color]; m_output[dst+1] = palette[color+1]; m_output[dst+2] = palette[color+2]; dst += 3; continue; } uint shift = (uint)v13 >> 4; int count = v13 & 0xF; if (0 == count) { count = m_input.ReadUInt8() + 15; if (270 == count) { int v16; do { v16 = m_input.ReadUInt8(); count += v16; } while (v16 == 0xff); } } if (0 != shift) { int src = dst + ShiftTable[shift]; Binary.CopyOverlapped (m_output, src, dst, count * 3); } dst += 3 * count; } right += m_width*3; left += m_width*3; } } #region IDisposable Members bool m_disposed = false; public void Dispose () { if (!m_disposed) { if (m_should_dispose) { m_input.Dispose(); } m_disposed = true; } GC.SuppressFinalize (this); } #endregion } } }
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the rds-2014-10-31.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.RDS.Model { /// <summary> /// Contains the results of a successful invocation of the <a>DescribeEventSubscriptions</a> /// action. /// </summary> public partial class EventSubscription { private string _customerAwsId; private string _custSubscriptionId; private bool? _enabled; private List<string> _eventCategoriesList = new List<string>(); private string _snsTopicArn; private List<string> _sourceIdsList = new List<string>(); private string _sourceType; private string _status; private string _subscriptionCreationTime; /// <summary> /// Gets and sets the property CustomerAwsId. /// <para> /// The AWS customer account associated with the RDS event notification subscription. /// </para> /// </summary> public string CustomerAwsId { get { return this._customerAwsId; } set { this._customerAwsId = value; } } // Check to see if CustomerAwsId property is set internal bool IsSetCustomerAwsId() { return this._customerAwsId != null; } /// <summary> /// Gets and sets the property CustSubscriptionId. /// <para> /// The RDS event notification subscription Id. /// </para> /// </summary> public string CustSubscriptionId { get { return this._custSubscriptionId; } set { this._custSubscriptionId = value; } } // Check to see if CustSubscriptionId property is set internal bool IsSetCustSubscriptionId() { return this._custSubscriptionId != null; } /// <summary> /// Gets and sets the property Enabled. /// <para> /// A Boolean value indicating if the subscription is enabled. True indicates the subscription /// is enabled. /// </para> /// </summary> public bool Enabled { get { return this._enabled.GetValueOrDefault(); } set { this._enabled = value; } } // Check to see if Enabled property is set internal bool IsSetEnabled() { return this._enabled.HasValue; } /// <summary> /// Gets and sets the property EventCategoriesList. /// <para> /// A list of event categories for the RDS event notification subscription. /// </para> /// </summary> public List<string> EventCategoriesList { get { return this._eventCategoriesList; } set { this._eventCategoriesList = value; } } // Check to see if EventCategoriesList property is set internal bool IsSetEventCategoriesList() { return this._eventCategoriesList != null && this._eventCategoriesList.Count > 0; } /// <summary> /// Gets and sets the property SnsTopicArn. /// <para> /// The topic ARN of the RDS event notification subscription. /// </para> /// </summary> public string SnsTopicArn { get { return this._snsTopicArn; } set { this._snsTopicArn = value; } } // Check to see if SnsTopicArn property is set internal bool IsSetSnsTopicArn() { return this._snsTopicArn != null; } /// <summary> /// Gets and sets the property SourceIdsList. /// <para> /// A list of source IDs for the RDS event notification subscription. /// </para> /// </summary> public List<string> SourceIdsList { get { return this._sourceIdsList; } set { this._sourceIdsList = value; } } // Check to see if SourceIdsList property is set internal bool IsSetSourceIdsList() { return this._sourceIdsList != null && this._sourceIdsList.Count > 0; } /// <summary> /// Gets and sets the property SourceType. /// <para> /// The source type for the RDS event notification subscription. /// </para> /// </summary> public string SourceType { get { return this._sourceType; } set { this._sourceType = value; } } // Check to see if SourceType property is set internal bool IsSetSourceType() { return this._sourceType != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// The status of the RDS event notification subscription. /// </para> /// /// <para> /// Constraints: /// </para> /// /// <para> /// Can be one of the following: creating | modifying | deleting | active | no-permission /// | topic-not-exist /// </para> /// /// <para> /// The status "no-permission" indicates that RDS no longer has permission to post to /// the SNS topic. The status "topic-not-exist" indicates that the topic was deleted after /// the subscription was created. /// </para> /// </summary> public string Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } /// <summary> /// Gets and sets the property SubscriptionCreationTime. /// <para> /// The time the RDS event notification subscription was created. /// </para> /// </summary> public string SubscriptionCreationTime { get { return this._subscriptionCreationTime; } set { this._subscriptionCreationTime = value; } } // Check to see if SubscriptionCreationTime property is set internal bool IsSetSubscriptionCreationTime() { return this._subscriptionCreationTime != null; } } }
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace System.ServiceModel { using System.ComponentModel; using System.Configuration; using System.Runtime; using System.ServiceModel.Channels; using System.Xml; using Config = System.ServiceModel.Configuration; public class NetMsmqBinding : MsmqBindingBase { // private BindingElements BinaryMessageEncodingBindingElement encoding; NetMsmqSecurity security; public NetMsmqBinding() { Initialize(); this.security = new NetMsmqSecurity(); } public NetMsmqBinding(string configurationName) { Initialize(); this.security = new NetMsmqSecurity(); ApplyConfiguration(configurationName); } public NetMsmqBinding(NetMsmqSecurityMode securityMode) { if (!NetMsmqSecurityModeHelper.IsDefined(securityMode)) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new InvalidEnumArgumentException("mode", (int)securityMode, typeof(NetMsmqSecurityMode))); Initialize(); this.security = new NetMsmqSecurity(securityMode); } NetMsmqBinding(NetMsmqSecurity security) { Initialize(); Fx.Assert(security != null, "Invalid (null) NetMsmqSecurity value"); this.security = security; } [DefaultValue(MsmqDefaults.QueueTransferProtocol)] public QueueTransferProtocol QueueTransferProtocol { get { return (this.transport as MsmqTransportBindingElement).QueueTransferProtocol; } set { (this.transport as MsmqTransportBindingElement).QueueTransferProtocol = value; } } public XmlDictionaryReaderQuotas ReaderQuotas { get { return encoding.ReaderQuotas; } set { if (value == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperArgumentNull("value"); value.CopyTo(encoding.ReaderQuotas); } } public NetMsmqSecurity Security { get { return this.security; } set { this.security = value; } } public EnvelopeVersion EnvelopeVersion { get { return EnvelopeVersion.Soap12; } } [DefaultValue(TransportDefaults.MaxBufferPoolSize)] public long MaxBufferPoolSize { get { return transport.MaxBufferPoolSize; } set { transport.MaxBufferPoolSize = value; } } internal int MaxPoolSize { get { return (transport as MsmqTransportBindingElement).MaxPoolSize; } set { (transport as MsmqTransportBindingElement).MaxPoolSize = value; } } [DefaultValue(MsmqDefaults.UseActiveDirectory)] public bool UseActiveDirectory { get { return (transport as MsmqTransportBindingElement).UseActiveDirectory; } set { (transport as MsmqTransportBindingElement).UseActiveDirectory = value; } } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeReaderQuotas() { if (this.ReaderQuotas.MaxArrayLength != EncoderDefaults.MaxArrayLength) { return true; } if (this.ReaderQuotas.MaxBytesPerRead != EncoderDefaults.MaxBytesPerRead) { return true; } if (this.ReaderQuotas.MaxDepth != EncoderDefaults.MaxDepth) { return true; } if (this.ReaderQuotas.MaxNameTableCharCount != EncoderDefaults.MaxNameTableCharCount) { return true; } if (this.ReaderQuotas.MaxStringContentLength != EncoderDefaults.MaxStringContentLength) { return true; } return false; } [EditorBrowsable(EditorBrowsableState.Never)] public bool ShouldSerializeSecurity() { if (this.security.Mode != NetMsmqSecurity.DefaultMode) { return true; } if (this.security.Transport.MsmqAuthenticationMode != MsmqDefaults.MsmqAuthenticationMode || this.security.Transport.MsmqEncryptionAlgorithm != MsmqDefaults.MsmqEncryptionAlgorithm || this.security.Transport.MsmqSecureHashAlgorithm != MsmqDefaults.MsmqSecureHashAlgorithm || this.security.Transport.MsmqProtectionLevel != MsmqDefaults.MsmqProtectionLevel) { return true; } if (this.security.Message.AlgorithmSuite != MsmqDefaults.MessageSecurityAlgorithmSuite || this.security.Message.ClientCredentialType != MsmqDefaults.DefaultClientCredentialType) { return true; } return false; } void Initialize() { transport = new MsmqTransportBindingElement(); encoding = new BinaryMessageEncodingBindingElement(); } void InitializeFrom(MsmqTransportBindingElement transport, BinaryMessageEncodingBindingElement encoding) { // only set properties that have standard binding manifestations: MaxPoolSize *is not* one of them this.CustomDeadLetterQueue = transport.CustomDeadLetterQueue; this.DeadLetterQueue = transport.DeadLetterQueue; this.Durable = transport.Durable; this.ExactlyOnce = transport.ExactlyOnce; this.MaxReceivedMessageSize = transport.MaxReceivedMessageSize; this.ReceiveRetryCount = transport.ReceiveRetryCount; this.MaxRetryCycles = transport.MaxRetryCycles; this.ReceiveErrorHandling = transport.ReceiveErrorHandling; this.RetryCycleDelay = transport.RetryCycleDelay; this.TimeToLive = transport.TimeToLive; this.UseSourceJournal = transport.UseSourceJournal; this.UseMsmqTracing = transport.UseMsmqTracing; this.ReceiveContextEnabled = transport.ReceiveContextEnabled; this.QueueTransferProtocol = transport.QueueTransferProtocol; this.MaxBufferPoolSize = transport.MaxBufferPoolSize; this.UseActiveDirectory = transport.UseActiveDirectory; this.ValidityDuration = transport.ValidityDuration; this.ReaderQuotas = encoding.ReaderQuotas; } // check that properties of the HttpTransportBindingElement and // MessageEncodingBindingElement not exposed as properties on NetMsmqBinding // match default values of the binding elements bool IsBindingElementsMatch(MsmqTransportBindingElement transport, MessageEncodingBindingElement encoding) { // we do not have to check the transport match here: they always match if (!this.GetTransport().IsMatch(transport)) return false; if (!this.encoding.IsMatch(encoding)) return false; return true; } void ApplyConfiguration(string configurationName) { Config.NetMsmqBindingCollectionElement section = Config.NetMsmqBindingCollectionElement.GetBindingCollectionElement(); Config.NetMsmqBindingElement element = section.Bindings[configurationName]; if (element == null) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ConfigurationErrorsException( SR.GetString(SR.ConfigInvalidBindingConfigurationName, configurationName, Config.ConfigurationStrings.NetMsmqBindingCollectionElementName))); } else { element.ApplyConfiguration(this); } } public override BindingElementCollection CreateBindingElements() { // return collection of BindingElements BindingElementCollection bindingElements = new BindingElementCollection(); // order of BindingElements is important // add security SecurityBindingElement wsSecurity = CreateMessageSecurity(); if (wsSecurity != null) { bindingElements.Add(wsSecurity); } // add encoding (text or mtom) bindingElements.Add(encoding); // add transport bindingElements.Add(GetTransport()); return bindingElements.Clone(); } internal static bool TryCreate(BindingElementCollection elements, out Binding binding) { binding = null; if (elements.Count > 3) return false; SecurityBindingElement security = null; BinaryMessageEncodingBindingElement encoding = null; MsmqTransportBindingElement transport = null; foreach (BindingElement element in elements) { if (element is SecurityBindingElement) security = element as SecurityBindingElement; else if (element is TransportBindingElement) transport = element as MsmqTransportBindingElement; else if (element is MessageEncodingBindingElement) encoding = element as BinaryMessageEncodingBindingElement; else return false; } UnifiedSecurityMode mode; if (!IsValidTransport(transport, out mode)) return false; if (encoding == null) return false; NetMsmqSecurity netMsmqSecurity; if (!TryCreateSecurity(security, mode, out netMsmqSecurity)) return false; NetMsmqBinding netMsmqBinding = new NetMsmqBinding(netMsmqSecurity); netMsmqBinding.InitializeFrom(transport, encoding); if (!netMsmqBinding.IsBindingElementsMatch(transport, encoding)) return false; binding = netMsmqBinding; return true; } SecurityBindingElement CreateMessageSecurity() { if (this.security.Mode == NetMsmqSecurityMode.Message || this.security.Mode == NetMsmqSecurityMode.Both) { return this.security.CreateMessageSecurity(); } else { return null; } } static bool TryCreateSecurity(SecurityBindingElement sbe, UnifiedSecurityMode mode, out NetMsmqSecurity security) { if (sbe != null) mode &= UnifiedSecurityMode.Message | UnifiedSecurityMode.Both; else mode &= ~(UnifiedSecurityMode.Message | UnifiedSecurityMode.Both); NetMsmqSecurityMode netMsmqSecurityMode = NetMsmqSecurityModeHelper.ToSecurityMode(mode); Fx.Assert(NetMsmqSecurityModeHelper.IsDefined(netMsmqSecurityMode), string.Format("Invalid NetMsmqSecurityMode value: {0}.", netMsmqSecurityMode.ToString())); if (NetMsmqSecurity.TryCreate(sbe, netMsmqSecurityMode, out security)) { return true; } return false; } MsmqBindingElementBase GetTransport() { this.security.ConfigureTransportSecurity(transport); return transport; } static bool IsValidTransport(MsmqTransportBindingElement msmq, out UnifiedSecurityMode mode) { mode = (UnifiedSecurityMode)0; if (msmq == null) return false; return NetMsmqSecurity.IsConfiguredTransportSecurity(msmq, out mode); } } }
// Copyright (c) Umbraco. // See LICENSE for more details. using System; using System.Collections.Generic; using System.Linq; using System.Threading; using NPoco; using NUnit.Framework; using Umbraco.Cms.Core.Cache; using Umbraco.Cms.Core.DependencyInjection; using Umbraco.Cms.Core.Scoping; using Umbraco.Cms.Core.Services; using Umbraco.Cms.Core.Services.Implement; using Umbraco.Cms.Core.Sync; using Umbraco.Cms.Infrastructure.Persistence; using Umbraco.Cms.Infrastructure.Persistence.Dtos; using Umbraco.Cms.Tests.Common.Testing; using Umbraco.Cms.Tests.Integration.Testing; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.Integration.Umbraco.Infrastructure.Services { [TestFixture] [UmbracoTest(Database = UmbracoTestOptions.Database.NewSchemaPerTest)] public class CacheInstructionServiceTests : UmbracoIntegrationTest { private const string LocalIdentity = "localIdentity"; private const string AlternateIdentity = "alternateIdentity"; private CancellationToken CancellationToken => new CancellationToken(); private CacheRefresherCollection CacheRefreshers => GetRequiredService<CacheRefresherCollection>(); private IServerRoleAccessor ServerRoleAccessor => GetRequiredService<IServerRoleAccessor>(); protected override void CustomTestSetup(IUmbracoBuilder builder) { base.CustomTestSetup(builder); builder.AddNuCache(); } [Test] public void Confirms_Cold_Boot_Required_When_Instructions_Exist_And_None_Have_Been_Synced() { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); List<RefreshInstruction> instructions = CreateInstructions(); sut.DeliverInstructions(instructions, LocalIdentity); var result = sut.IsColdBootRequired(0); Assert.IsTrue(result); } [Test] public void Confirms_Cold_Boot_Required_When_Last_Synced_Instruction_Not_Found() { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); List<RefreshInstruction> instructions = CreateInstructions(); sut.DeliverInstructions(instructions, LocalIdentity); // will create with Id = 1 var result = sut.IsColdBootRequired(2); Assert.IsTrue(result); } [Test] public void Confirms_Cold_Boot_Not_Required_When_Last_Synced_Instruction_Found() { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); List<RefreshInstruction> instructions = CreateInstructions(); sut.DeliverInstructions(instructions, LocalIdentity); // will create with Id = 1 var result = sut.IsColdBootRequired(1); Assert.IsFalse(result); } [TestCase(1, 10, false, 4)] [TestCase(1, 3, true, 4)] public void Confirms_Instruction_Count_Over_Limit(int lastId, int limit, bool expectedResult, int expectedCount) { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); CreateAndDeliveryMultipleInstructions(sut); // 3 records, each with 2 instructions = 6. var result = sut.IsInstructionCountOverLimit(lastId, limit, out int count); Assert.AreEqual(expectedResult, result); Assert.AreEqual(expectedCount, count); } [Test] public void Can_Get_Max_Instruction_Id() { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); CreateAndDeliveryMultipleInstructions(sut); var result = sut.GetMaxInstructionId(); Assert.AreEqual(3, result); } [Test] public void Can_Deliver_Instructions() { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); List<RefreshInstruction> instructions = CreateInstructions(); sut.DeliverInstructions(instructions, LocalIdentity); AssertDeliveredInstructions(); } [Test] public void Can_Deliver_Instructions_In_Batches() { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); List<RefreshInstruction> instructions = CreateInstructions(); sut.DeliverInstructionsInBatches(instructions, LocalIdentity); AssertDeliveredInstructions(); } private List<RefreshInstruction> CreateInstructions() => new List<RefreshInstruction> { new RefreshInstruction(UserCacheRefresher.UniqueId, RefreshMethodType.RefreshByIds, Guid.Empty, 0, "[-1]", null), new RefreshInstruction(UserCacheRefresher.UniqueId, RefreshMethodType.RefreshByIds, Guid.Empty, 0, "[-1]", null), }; private void AssertDeliveredInstructions() { List<CacheInstructionDto> cacheInstructions; ISqlContext sqlContext = GetRequiredService<ISqlContext>(); Sql<ISqlContext> sql = sqlContext.Sql() .Select<CacheInstructionDto>() .From<CacheInstructionDto>(); using (IScope scope = ScopeProvider.CreateScope()) { cacheInstructions = scope.Database.Fetch<CacheInstructionDto>(sql); scope.Complete(); } Assert.Multiple(() => { Assert.AreEqual(1, cacheInstructions.Count); CacheInstructionDto firstInstruction = cacheInstructions.First(); Assert.AreEqual(2, firstInstruction.InstructionCount); Assert.AreEqual(LocalIdentity, firstInstruction.OriginIdentity); }); } [Test] public void Can_Process_Instructions() { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); // Create three instruction records, each with two instructions. First two records are for a different identity. CreateAndDeliveryMultipleInstructions(sut); ProcessInstructionsResult result = sut.ProcessInstructions(CacheRefreshers, ServerRoleAccessor.CurrentServerRole, CancellationToken, LocalIdentity, DateTime.UtcNow.AddSeconds(-1), -1); Assert.Multiple(() => { Assert.AreEqual(3, result.LastId); // 3 records found. Assert.AreEqual(2, result.NumberOfInstructionsProcessed); // 2 records processed (as one is for the same identity). Assert.IsFalse(result.InstructionsWerePruned); }); } [Test] public void Can_Process_And_Purge_Instructions() { // Purging of instructions only occurs on single or master servers, so we need to ensure this is set before running the test. EnsureServerRegistered(); var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); CreateAndDeliveryMultipleInstructions(sut); ProcessInstructionsResult result = sut.ProcessInstructions(CacheRefreshers, ServerRoleAccessor.CurrentServerRole, CancellationToken, LocalIdentity, DateTime.UtcNow.AddHours(-1), -1); Assert.IsTrue(result.InstructionsWerePruned); } [Test] public void Processes_No_Instructions_When_CancellationToken_is_Cancelled() { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); CreateAndDeliveryMultipleInstructions(sut); var cancellationTokenSource = new CancellationTokenSource(); cancellationTokenSource.Cancel(); ProcessInstructionsResult result = sut.ProcessInstructions(CacheRefreshers, ServerRoleAccessor.CurrentServerRole, cancellationTokenSource.Token, LocalIdentity, DateTime.UtcNow.AddSeconds(-1), -1); Assert.Multiple(() => { Assert.AreEqual(0, result.LastId); Assert.AreEqual(0, result.NumberOfInstructionsProcessed); Assert.IsFalse(result.InstructionsWerePruned); }); } [Test] public void Processes_Instructions_Only_Once() { // This test shows what's happening in issue #10112 // The DatabaseServerMessenger will run its sync operation every five seconds which calls CacheInstructionService.ProcessInstructions, // which is why the CacheRefresherNotification keeps dispatching, because the cache instructions gets constantly processed. var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); CreateAndDeliveryMultipleInstructions(sut); var lastId = -1; // Run once ProcessInstructionsResult result = sut.ProcessInstructions(CacheRefreshers, ServerRoleAccessor.CurrentServerRole, CancellationToken, LocalIdentity, DateTime.UtcNow.AddSeconds(-1), lastId); Assert.Multiple(() => { Assert.AreEqual(3, result.LastId); // 3 records found. Assert.AreEqual(2, result.NumberOfInstructionsProcessed); // 2 records processed (as one is for the same identity). Assert.IsFalse(result.InstructionsWerePruned); }); // DatabaseServerMessenger stores the LastID after ProcessInstructions has been run. lastId = result.LastId; // The instructions has now been processed and shouldn't be processed on the next call... // Run again. ProcessInstructionsResult secondResult = sut.ProcessInstructions(CacheRefreshers, ServerRoleAccessor.CurrentServerRole, CancellationToken, LocalIdentity, DateTime.UtcNow.AddSeconds(-1), lastId); Assert.Multiple(() => { Assert.AreEqual(0, secondResult.LastId); // No instructions was processed so LastId is 0, this is consistent with behavior from V8 Assert.AreEqual(0, secondResult.NumberOfInstructionsProcessed); // Nothing was processed. Assert.IsFalse(secondResult.InstructionsWerePruned); }); } [Test] public void Processes_New_Instructions() { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); CreateAndDeliveryMultipleInstructions(sut); var lastId = -1; ProcessInstructionsResult result = sut.ProcessInstructions(CacheRefreshers, ServerRoleAccessor.CurrentServerRole, CancellationToken, LocalIdentity, DateTime.UtcNow.AddSeconds(-1), lastId); Assert.AreEqual(3, result.LastId); // Make sure LastId is 3, the rest is tested in other test. lastId = result.LastId; // Add new instruction List<RefreshInstruction> instructions = CreateInstructions(); sut.DeliverInstructions(instructions, AlternateIdentity); ProcessInstructionsResult secondResult = sut.ProcessInstructions(CacheRefreshers, ServerRoleAccessor.CurrentServerRole, CancellationToken, LocalIdentity, DateTime.UtcNow.AddSeconds(-1), lastId); Assert.Multiple(() => { Assert.AreEqual(4, secondResult.LastId); Assert.AreEqual(1, secondResult.NumberOfInstructionsProcessed); Assert.IsFalse(secondResult.InstructionsWerePruned); }); } [Test] public void Correct_ID_For_Instruction_With_Same_Identity() { var sut = (CacheInstructionService)GetRequiredService<ICacheInstructionService>(); CreateAndDeliveryMultipleInstructions(sut); var lastId = -1; ProcessInstructionsResult result = sut.ProcessInstructions(CacheRefreshers, ServerRoleAccessor.CurrentServerRole, CancellationToken, LocalIdentity, DateTime.UtcNow.AddSeconds(-1), lastId); Assert.AreEqual(3, result.LastId); // Make sure LastId is 3, the rest is tested in other test. lastId = result.LastId; // Add new instruction List<RefreshInstruction> instructions = CreateInstructions(); sut.DeliverInstructions(instructions, LocalIdentity); ProcessInstructionsResult secondResult = sut.ProcessInstructions(CacheRefreshers, ServerRoleAccessor.CurrentServerRole, CancellationToken, LocalIdentity, DateTime.UtcNow.AddSeconds(-1), lastId); Assert.Multiple(() => { Assert.AreEqual(4, secondResult.LastId); Assert.AreEqual(0, secondResult.NumberOfInstructionsProcessed); Assert.IsFalse(secondResult.InstructionsWerePruned); }); } private void CreateAndDeliveryMultipleInstructions(CacheInstructionService sut) { for (int i = 0; i < 3; i++) { List<RefreshInstruction> instructions = CreateInstructions(); sut.DeliverInstructions(instructions, i == 2 ? LocalIdentity : AlternateIdentity); } } private void EnsureServerRegistered() { IServerRegistrationService serverRegistrationService = GetRequiredService<IServerRegistrationService>(); serverRegistrationService.TouchServer("http://localhost", TimeSpan.FromMinutes(10)); } } }
// Generated by SharpKit.QooxDoo.Generator using System; using System.Collections.Generic; using SharpKit.Html; using SharpKit.JavaScript; namespace qx.ui.mobile.list.renderer { /// <summary> /// <para>Base class for all list item renderer.</para> /// </summary> [JsType(JsMode.Prototype, Name = "qx.ui.mobile.list.renderer.Abstract", OmitOptionalParameters = true, Export = false)] public abstract partial class Abstract : qx.ui.mobile.container.Composite { #region Properties /// <summary> /// <para>Whether the widget can be activated or not. When the widget is activated /// a css class active is automatically added to the widget, which /// can indicate the acitvation status.</para> /// </summary> [JsProperty(Name = "activatable", NativeField = true)] public bool Activatable { get; set; } /// <summary> /// <para>The default CSS class used for this widget. The default CSS class /// should contain the common appearance of the widget. /// It is set to the container element of the widget. Use <see cref="AddCssClass"/> /// to enhance the default appearance of the widget.</para> /// </summary> /// <remarks> /// Allow nulls: true /// </remarks> [JsProperty(Name = "defaultCssClass", NativeField = true)] public string DefaultCssClass { get; set; } /// <summary> /// <para>Whether the row is selectable.</para> /// </summary> [JsProperty(Name = "selectable", NativeField = true)] public bool Selectable { get; set; } /// <summary> /// <para>Whether the row is selected.</para> /// </summary> [JsProperty(Name = "selected", NativeField = true)] public bool Selected { get; set; } /// <summary> /// <para>Whether to show an arrow in the row.</para> /// </summary> [JsProperty(Name = "showArrow", NativeField = true)] public bool ShowArrow { get; set; } #endregion Properties #region Methods public Abstract() { throw new NotImplementedException(); } public Abstract(object layout) { throw new NotImplementedException(); } /// <summary> /// <para>Returns the row index of a certain DOM element in the list.</para> /// </summary> /// <param name="element">DOM element to retrieve the index from.</param> /// <returns>the index of the row.</returns> [JsMethod(Name = "getRowIndex")] public double GetRowIndex(qx.html.Element element) { throw new NotImplementedException(); } /// <summary> /// <para>Returns the row index of a certain DOM element in the list from the given event.</para> /// </summary> /// <param name="evt">The causing event.</param> /// <returns>the index of the row.</returns> [JsMethod(Name = "getRowIndexFromEvent")] public double GetRowIndexFromEvent(qx.eventx.type.Event evt) { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property selectable.</para> /// </summary> [JsMethod(Name = "getSelectable")] public bool GetSelectable() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property selected.</para> /// </summary> [JsMethod(Name = "getSelected")] public bool GetSelected() { throw new NotImplementedException(); } /// <summary> /// <para>Returns the (computed) value of the property showArrow.</para> /// </summary> [JsMethod(Name = "getShowArrow")] public bool GetShowArrow() { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property selectable /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property selectable.</param> [JsMethod(Name = "initSelectable")] public void InitSelectable(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property selected /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property selected.</param> [JsMethod(Name = "initSelected")] public void InitSelected(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Calls the apply method and dispatches the change event of the property showArrow /// with the default value defined by the class developer. This function can /// only be called from the constructor of a class.</para> /// </summary> /// <param name="value">Initial value for property showArrow.</param> [JsMethod(Name = "initShowArrow")] public void InitShowArrow(object value) { throw new NotImplementedException(); } /// <summary> /// <para>Check whether the (computed) value of the boolean property selectable equals true.</para> /// </summary> [JsMethod(Name = "isSelectable")] public void IsSelectable() { throw new NotImplementedException(); } /// <summary> /// <para>Check whether the (computed) value of the boolean property selected equals true.</para> /// </summary> [JsMethod(Name = "isSelected")] public void IsSelected() { throw new NotImplementedException(); } /// <summary> /// <para>Check whether the (computed) value of the boolean property showArrow equals true.</para> /// </summary> [JsMethod(Name = "isShowArrow")] public void IsShowArrow() { throw new NotImplementedException(); } /// <summary> /// <para>Resets all defined child widgets. Override this method in your custom /// list item renderer and reset all widgets displaying data. Needed as the /// renderer is used for every row and otherwise data of a different row /// might be displayed, when not all data displaying widgets are used for the row. /// Gets called automatically by the <see cref="qx.ui.mobile.list.provider.Provider"/>.</para> /// </summary> [JsMethod(Name = "reset")] public void Reset() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property selectable.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetSelectable")] public void ResetSelectable() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property selected.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetSelected")] public void ResetSelected() { throw new NotImplementedException(); } /// <summary> /// <para>Resets the user value of the property showArrow.</para> /// <para>The computed value falls back to the next available value e.g. appearance, init or /// inheritance value depeneding on the property configuration and value availability.</para> /// </summary> [JsMethod(Name = "resetShowArrow")] public void ResetShowArrow() { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property selectable.</para> /// </summary> /// <param name="value">New value for property selectable.</param> [JsMethod(Name = "setSelectable")] public void SetSelectable(bool value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property selected.</para> /// </summary> /// <param name="value">New value for property selected.</param> [JsMethod(Name = "setSelected")] public void SetSelected(bool value) { throw new NotImplementedException(); } /// <summary> /// <para>Sets the user value of the property showArrow.</para> /// </summary> /// <param name="value">New value for property showArrow.</param> [JsMethod(Name = "setShowArrow")] public void SetShowArrow(bool value) { throw new NotImplementedException(); } /// <summary> /// <para>Toggles the (computed) value of the boolean property selectable.</para> /// </summary> [JsMethod(Name = "toggleSelectable")] public void ToggleSelectable() { throw new NotImplementedException(); } /// <summary> /// <para>Toggles the (computed) value of the boolean property selected.</para> /// </summary> [JsMethod(Name = "toggleSelected")] public void ToggleSelected() { throw new NotImplementedException(); } /// <summary> /// <para>Toggles the (computed) value of the boolean property showArrow.</para> /// </summary> [JsMethod(Name = "toggleShowArrow")] public void ToggleShowArrow() { throw new NotImplementedException(); } #endregion Methods } }
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Management.Automation; using Microsoft.Azure.Commands.RecoveryServices.SiteRecovery.Properties; using Microsoft.Azure.Management.RecoveryServices.SiteRecovery.Models; using Newtonsoft.Json; namespace Microsoft.Azure.Commands.RecoveryServices.SiteRecovery { /// <summary> /// Creates Azure Site Recovery Recovery Plan object. /// </summary> [Cmdlet( VerbsData.Update, "AzureRmRecoveryServicesAsrRecoveryPlan", DefaultParameterSetName = ASRParameterSets.ByRPObject, SupportsShouldProcess = true)] [Alias("Update-ASRRecoveryPlan")] [OutputType(typeof(ASRJob))] public class UpdateAzureRmRecoveryServicesAsrRecoveryPlan : SiteRecoveryCmdletBase { /// <summary> /// Gets or sets Name of the Recovery Plan. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPObject, Mandatory = true, ValueFromPipeline = true)] [Alias("RecoveryPlan")] public ASRRecoveryPlan InputObject { get; set; } /// <summary> /// Gets or sets RP JSON FilePath. /// </summary> [Parameter( ParameterSetName = ASRParameterSets.ByRPFile, Mandatory = true)] public string Path { get; set; } /// <summary> /// ProcessRecord of the command. /// </summary> public override void ExecuteSiteRecoveryCmdlet() { base.ExecuteSiteRecoveryCmdlet(); if (this.ShouldProcess( "Recovery plan", VerbsData.Update)) { switch (this.ParameterSetName) { case ASRParameterSets.ByRPObject: this.UpdateRecoveryPlan(this.InputObject); break; case ASRParameterSets.ByRPFile: if (!File.Exists(this.Path)) { throw new FileNotFoundException( string.Format( Resources.FileNotFound, this.Path)); ; } var filePath = this.Path; RecoveryPlan recoveryPlan = null; using (var file = new StreamReader(filePath)) { recoveryPlan = JsonConvert.DeserializeObject<RecoveryPlan>( file.ReadToEnd(), new RecoveryPlanActionDetailsConverter()); } this.UpdateRecoveryPlan(recoveryPlan); break; } } } /// <summary> /// Update Recovery Plan: By powerShell Recovery Plan object /// </summary> private void UpdateRecoveryPlan( ASRRecoveryPlan asrRecoveryPlan) { var updateRecoveryPlanInputProperties = new UpdateRecoveryPlanInputProperties { Groups = new List<RecoveryPlanGroup>() }; foreach (var asrRecoveryPlanGroup in asrRecoveryPlan.Groups) { var recoveryPlanGroup = new RecoveryPlanGroup { GroupType = (RecoveryPlanGroupType)Enum.Parse( typeof(RecoveryPlanGroupType), asrRecoveryPlanGroup.GroupType), // Initialize ReplicationProtectedItems with empty List if asrRecoveryPlanGroup.ReplicationProtectedItems is null // otherwise assign respective values ReplicationProtectedItems = asrRecoveryPlanGroup.ReplicationProtectedItems == null ? new List<RecoveryPlanProtectedItem>() : asrRecoveryPlanGroup .ReplicationProtectedItems.Select( item => { var newItem = new RecoveryPlanProtectedItem(item.Id); string VmId = null; if (item.Properties.ProviderSpecificDetails.GetType() == typeof(HyperVReplicaAzureReplicationDetails)) { VmId = ((HyperVReplicaAzureReplicationDetails)item .Properties.ProviderSpecificDetails).VmId; } else if (item.Properties.ProviderSpecificDetails .GetType() == typeof(HyperVReplicaReplicationDetails)) { VmId = ((HyperVReplicaReplicationDetails)item.Properties .ProviderSpecificDetails).VmId; } else if (item.Properties.ProviderSpecificDetails .GetType() == typeof(HyperVReplicaBlueReplicationDetails)) { VmId = ((HyperVReplicaBlueReplicationDetails)item .Properties.ProviderSpecificDetails).VmId; } newItem.VirtualMachineId = VmId; return newItem; }) .ToList(), StartGroupActions = asrRecoveryPlanGroup.StartGroupActions, EndGroupActions = asrRecoveryPlanGroup.EndGroupActions }; updateRecoveryPlanInputProperties.Groups.Add(recoveryPlanGroup); } var updateRecoveryPlanInput = new UpdateRecoveryPlanInput { Properties = updateRecoveryPlanInputProperties }; this.UpdateRecoveryPlan( asrRecoveryPlan.Name, updateRecoveryPlanInput); } /// <summary> /// Update Recovery Plan: By Service object /// </summary> private void UpdateRecoveryPlan( RecoveryPlan recoveryPlan) { var updateRecoveryPlanInputProperties = new UpdateRecoveryPlanInputProperties { Groups = recoveryPlan.Properties.Groups }; var updateRecoveryPlanInput = new UpdateRecoveryPlanInput { Properties = updateRecoveryPlanInputProperties }; this.UpdateRecoveryPlan( recoveryPlan.Name, updateRecoveryPlanInput); } /// <summary> /// Update Replication Plan: Utility call /// </summary> private void UpdateRecoveryPlan( string recoveryPlanName, UpdateRecoveryPlanInput updateRecoveryPlanInput) { var response = this.RecoveryServicesClient.UpdateAzureSiteRecoveryRecoveryPlan( recoveryPlanName, updateRecoveryPlanInput); var jobResponse = this.RecoveryServicesClient.GetAzureSiteRecoveryJobDetails( PSRecoveryServicesClient.GetJobIdFromReponseLocation(response.Location)); this.WriteObject(new ASRJob(jobResponse)); } } }
// // Copyright (c) 2004-2016 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.UnitTests.Internal.NetworkSenders { using System; using System.Collections.Generic; using System.IO; using System.Net; using System.Net.Sockets; using System.Text; using System.Threading; using NLog.Internal.NetworkSenders; using Xunit; public class TcpNetworkSenderTests : NLogTestBase { [Fact] public void TcpHappyPathTest() { foreach (bool async in new[] { false, true }) { var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified) { Async = async, }; sender.Initialize(); byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog"); var exceptions = new List<Exception>(); for (int i = 1; i < 8; i *= 2) { sender.Send( buffer, 0, i, ex => { lock (exceptions) exceptions.Add(ex); }); } var mre = new ManualResetEvent(false); sender.FlushAsync(ex => { lock (exceptions) { exceptions.Add(ex); } mre.Set(); }); mre.WaitOne(); var actual = sender.Log.ToString(); Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1); Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1); Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1); Assert.True(actual.IndexOf("send async 0 1 'q'") != -1); Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1); Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1); mre.Reset(); for (int i = 1; i < 8; i *= 2) { sender.Send( buffer, 0, i, ex => { lock (exceptions) exceptions.Add(ex); }); } sender.Close(ex => { lock (exceptions) { exceptions.Add(ex); } mre.Set(); }); mre.WaitOne(); actual = sender.Log.ToString(); Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1); Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1); Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1); Assert.True(actual.IndexOf("send async 0 1 'q'") != -1); Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1); Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1); Assert.True(actual.IndexOf("send async 0 1 'q'") != -1); Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1); Assert.True(actual.IndexOf("send async 0 4 'quic'") != -1); Assert.True(actual.IndexOf("close") != -1); foreach (var ex in exceptions) { Assert.Null(ex); } } } [Fact] public void TcpProxyTest() { var sender = new TcpNetworkSender("tcp://foo:1234", AddressFamily.Unspecified); var socket = sender.CreateSocket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); Assert.IsType(typeof(SocketProxy), socket); } [Fact] public void TcpConnectFailureTest() { var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified) { ConnectFailure = 1, Async = true, }; sender.Initialize(); byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog"); var exceptions = new List<Exception>(); var allSent = new ManualResetEvent(false); for (int i = 1; i < 8; i++) { sender.Send( buffer, 0, i, ex => { lock (exceptions) { exceptions.Add(ex); if (exceptions.Count == 7) { allSent.Set(); } } }); } #if SILVERLIGHT Assert.True(allSent.WaitOne(3000)); #else Assert.True(allSent.WaitOne(3000, false)); #endif var mre = new ManualResetEvent(false); sender.FlushAsync(ex => mre.Set()); #if SILVERLIGHT mre.WaitOne(3000); #else mre.WaitOne(3000, false); #endif var actual = sender.Log.ToString(); Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1); Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1); Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1); Assert.True(actual.IndexOf("failed") != -1); foreach (var ex in exceptions) { Assert.NotNull(ex); } } [Fact] public void TcpSendFailureTest() { var sender = new MyTcpNetworkSender("tcp://hostname:123", AddressFamily.Unspecified) { SendFailureIn = 3, // will cause failure on 3rd send Async = true, }; sender.Initialize(); byte[] buffer = Encoding.UTF8.GetBytes("quick brown fox jumps over the lazy dog"); var exceptions = new Exception[9]; var writeFinished = new ManualResetEvent(false); int remaining = exceptions.Length; for (int i = 1; i < 10; i++) { int pos = i - 1; sender.Send( buffer, 0, i, ex => { lock (exceptions) { exceptions[pos] = ex; if (--remaining == 0) { writeFinished.Set(); } } }); } var mre = new ManualResetEvent(false); writeFinished.WaitOne(); sender.Close(ex => mre.Set()); mre.WaitOne(); var actual = sender.Log.ToString(); Assert.True(actual.IndexOf("Parse endpoint address tcp://hostname:123/ Unspecified") != -1); Assert.True(actual.IndexOf("create socket 10000 Stream Tcp") != -1); Assert.True(actual.IndexOf("connect async to {mock end point: tcp://hostname:123/}") != -1); Assert.True(actual.IndexOf("send async 0 1 'q'") != -1); Assert.True(actual.IndexOf("send async 0 2 'qu'") != -1); Assert.True(actual.IndexOf("send async 0 3 'qui'") != -1); Assert.True(actual.IndexOf("failed") != -1); Assert.True(actual.IndexOf("close") != -1); for (int i = 0; i < exceptions.Length; ++i) { if (i < 2) { Assert.Null(exceptions[i]); } else { Assert.NotNull(exceptions[i]); } } } internal class MyTcpNetworkSender : TcpNetworkSender { public StringWriter Log { get; set; } public MyTcpNetworkSender(string url, AddressFamily addressFamily) : base(url, addressFamily) { this.Log = new StringWriter(); } protected internal override ISocket CreateSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType) { return new MockSocket(addressFamily, socketType, protocolType, this); } protected override EndPoint ParseEndpointAddress(Uri uri, AddressFamily addressFamily) { this.Log.WriteLine("Parse endpoint address {0} {1}", uri, addressFamily); return new MockEndPoint(uri); } public int ConnectFailure { get; set; } public bool Async { get; set; } public int SendFailureIn { get; set; } } internal class MockSocket : ISocket { private readonly MyTcpNetworkSender sender; private readonly StringWriter log; private bool faulted = false; public MockSocket(AddressFamily addressFamily, SocketType socketType, ProtocolType protocolType, MyTcpNetworkSender sender) { this.sender = sender; this.log = sender.Log; this.log.WriteLine("create socket {0} {1} {2}", addressFamily, socketType, protocolType); } public bool ConnectAsync(SocketAsyncEventArgs args) { this.log.WriteLine("connect async to {0}", args.RemoteEndPoint); lock (this) { if (this.sender.ConnectFailure > 0) { this.sender.ConnectFailure--; this.faulted = true; args.SocketError = SocketError.SocketError; this.log.WriteLine("failed"); } } return InvokeCallback(args); } private bool InvokeCallback(SocketAsyncEventArgs args) { lock (this) { var args2 = args as TcpNetworkSender.MySocketAsyncEventArgs; if (this.sender.Async) { ThreadPool.QueueUserWorkItem(s => { Thread.Sleep(10); args2.RaiseCompleted(); }); return true; } else { return false; } } } public void Close() { lock (this) { this.log.WriteLine("close"); } } public bool SendAsync(SocketAsyncEventArgs args) { lock (this) { this.log.WriteLine("send async {0} {1} '{2}'", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count)); if (this.sender.SendFailureIn > 0) { this.sender.SendFailureIn--; if (this.sender.SendFailureIn == 0) { this.faulted = true; } } if (this.faulted) { this.log.WriteLine("failed"); args.SocketError = SocketError.SocketError; } } return InvokeCallback(args); } public bool SendToAsync(SocketAsyncEventArgs args) { lock (this) { this.log.WriteLine("sendto async {0} {1} '{2}' {3}", args.Offset, args.Count, Encoding.UTF8.GetString(args.Buffer, args.Offset, args.Count), args.RemoteEndPoint); return InvokeCallback(args); } } } internal class MockEndPoint : EndPoint { private readonly Uri uri; public MockEndPoint(Uri uri) { this.uri = uri; } public override AddressFamily AddressFamily { get { return (System.Net.Sockets.AddressFamily)10000; } } public override string ToString() { return "{mock end point: " + this.uri + "}"; } } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Logging; namespace QuantConnect.Securities { /// <summary> /// Represents a holding of a currency in cash. /// </summary> public class Cash { private bool _isBaseCurrency; private bool _invertRealTimePrice; private readonly object _locker = new object(); /// <summary> /// Gets the symbol of the security required to provide conversion rates. /// </summary> public Symbol SecuritySymbol { get; private set; } /// <summary> /// Gets the symbol used to represent this cash /// </summary> public string Symbol { get; private set; } /// <summary> /// Gets or sets the amount of cash held /// </summary> public decimal Amount { get; private set; } /// <summary> /// Gets the conversion rate into account currency /// </summary> public decimal ConversionRate { get; internal set; } /// <summary> /// Gets the value of this cash in the accout currency /// </summary> public decimal ValueInAccountCurrency { get { return Amount*ConversionRate; } } /// <summary> /// Initializes a new instance of the <see cref="Cash"/> class /// </summary> /// <param name="symbol">The symbol used to represent this cash</param> /// <param name="amount">The amount of this currency held</param> /// <param name="conversionRate">The initial conversion rate of this currency into the <see cref="CashBook.AccountCurrency"/></param> public Cash(string symbol, decimal amount, decimal conversionRate) { if (symbol == null || symbol.Length != 3) { throw new ArgumentException("Cash symbols must be exactly 3 characters."); } Amount = amount; ConversionRate = conversionRate; Symbol = symbol.ToUpper(); } /// <summary> /// Updates this cash object with the specified data /// </summary> /// <param name="data">The new data for this cash object</param> public void Update(BaseData data) { if (_isBaseCurrency) return; var rate = data.Value; if (_invertRealTimePrice) { rate = 1/rate; } ConversionRate = rate; } /// <summary> /// Adds the specified amount of currency to this Cash instance and returns the new total. /// This operation is thread-safe /// </summary> /// <param name="amount">The amount of currency to be added</param> /// <returns>The amount of currency directly after the addition</returns> public decimal AddAmount(decimal amount) { lock (_locker) { Amount += amount; return Amount; } } /// <summary> /// Sets the Quantity to the specified amount /// </summary> /// <param name="amount">The amount to set the quantity to</param> public void SetAmount(decimal amount) { lock (_locker) { Amount = amount; } } /// <summary> /// Ensures that we have a data feed to convert this currency into the base currency. /// This will add a subscription at the lowest resolution if one is not found. /// </summary> /// <param name="securities">The security manager</param> /// <param name="subscriptions">The subscription manager used for searching and adding subscriptions</param> /// <param name="marketHoursDatabase">A security exchange hours provider instance used to resolve exchange hours for new subscriptions</param> /// <param name="symbolPropertiesDatabase">A symbol properties database instance</param> /// <param name="marketMap">The market map that decides which market the new security should be in</param> /// <param name="cashBook">The cash book - used for resolving quote currencies for created conversion securities</param> /// <returns>Returns the added currency security if needed, otherwise null</returns> public Security EnsureCurrencyDataFeed(SecurityManager securities, SubscriptionManager subscriptions, MarketHoursDatabase marketHoursDatabase, SymbolPropertiesDatabase symbolPropertiesDatabase, IReadOnlyDictionary<SecurityType, string> marketMap, CashBook cashBook) { if (Symbol == CashBook.AccountCurrency) { SecuritySymbol = QuantConnect.Symbol.Empty; _isBaseCurrency = true; ConversionRate = 1.0m; return null; } if (subscriptions.Count == 0) { throw new InvalidOperationException("Unable to add cash when no subscriptions are present. Please add subscriptions in the Initialize() method."); } // we require a subscription that converts this into the base currency string normal = Symbol + CashBook.AccountCurrency; string invert = CashBook.AccountCurrency + Symbol; foreach (var config in subscriptions.Subscriptions.Where(config => config.SecurityType == SecurityType.Forex || config.SecurityType == SecurityType.Cfd)) { if (config.Symbol.Value == normal) { SecuritySymbol = config.Symbol; return null; } if (config.Symbol.Value == invert) { SecuritySymbol = config.Symbol; _invertRealTimePrice = true; return null; } } // if we've made it here we didn't find a subscription, so we'll need to add one var currencyPairs = Currencies.CurrencyPairs.Select(x => { // allow XAU or XAG to be used as quote currencies, but pairs including them are CFDs var securityType = Symbol.StartsWith("X") ? SecurityType.Cfd : SecurityType.Forex; var market = marketMap[securityType]; return QuantConnect.Symbol.Create(x, securityType, market); }); var minimumResolution = subscriptions.Subscriptions.Select(x => x.Resolution).DefaultIfEmpty(Resolution.Minute).Min(); var objectType = minimumResolution == Resolution.Tick ? typeof (Tick) : typeof (TradeBar); foreach (var symbol in currencyPairs) { if (symbol.Value == normal || symbol.Value == invert) { _invertRealTimePrice = symbol.Value == invert; var securityType = symbol.ID.SecurityType; var symbolProperties = symbolPropertiesDatabase.GetSymbolProperties(symbol.ID.Market, symbol.Value, securityType, Symbol); Cash quoteCash; if (!cashBook.TryGetValue(symbolProperties.QuoteCurrency, out quoteCash)) { throw new Exception("Unable to resolve quote cash: " + symbolProperties.QuoteCurrency + ". This is required to add conversion feed: " + symbol.ToString()); } var marketHoursDbEntry = marketHoursDatabase.GetEntry(symbol.ID.Market, symbol.Value, symbol.ID.SecurityType); var exchangeHours = marketHoursDbEntry.ExchangeHours; // set this as an internal feed so that the data doesn't get sent into the algorithm's OnData events var config = subscriptions.Add(objectType, symbol, minimumResolution, marketHoursDbEntry.DataTimeZone, exchangeHours.TimeZone, false, true, false, true); SecuritySymbol = config.Symbol; Security security; if (securityType == SecurityType.Cfd) { security = new Cfd.Cfd(exchangeHours, quoteCash, config, symbolProperties); } else { security = new Forex.Forex(exchangeHours, this, config, symbolProperties); } securities.Add(config.Symbol, security); Log.Trace("Cash.EnsureCurrencyDataFeed(): Adding " + symbol.Value + " for cash " + Symbol + " currency feed"); return security; } } // if this still hasn't been set then it's an error condition throw new ArgumentException(string.Format("In order to maintain cash in {0} you are required to add a subscription for Forex pair {0}{1} or {1}{0}", Symbol, CashBook.AccountCurrency)); } /// <summary> /// Returns a <see cref="System.String"/> that represents the current <see cref="QuantConnect.Securities.Cash"/>. /// </summary> /// <returns>A <see cref="System.String"/> that represents the current <see cref="QuantConnect.Securities.Cash"/>.</returns> public override string ToString() { // round the conversion rate for output decimal rate = ConversionRate; rate = rate < 1000 ? rate.RoundToSignificantDigits(5) : Math.Round(rate, 2); return string.Format("{0}: {1,15} @ ${2,10} = {3}{4}", Symbol, Amount.ToString("0.00"), rate.ToString("0.00####"), Currencies.CurrencySymbols[Symbol], Math.Round(ValueInAccountCurrency, 2) ); } } }
#region Licence... /* The MIT License (MIT) Copyright (c) 2014 Oleg Shilo 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; using System.Text; namespace WixSharp { /// <summary> /// Defines WiX Managed CustomAction, which is to be run with elevated privileges (UAC). /// <para> /// Any CustomAction, which needs elevation must be run with <see cref="Action.Impersonate"/> set to /// <c>false</c> and <see cref="Action.Execute"/> set to <c>Execute.deferred</c>. Thus <see cref="ElevatedManagedAction"/> is /// a full equivalent of <see cref="T:WixSharp.ManagedAction"/> with appropriately adjusted <see cref="Action.Execute"/> and /// <see cref="Action.Impersonate"/> during the instantiation: /// </para> /// <code> /// public ElevatedManagedAction() : base() /// { /// Impersonate = false; /// Execute = Execute.deferred; /// } /// </code> /// </summary>summary> public partial class ElevatedManagedAction : ManagedAction { /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class. /// </summary> public ElevatedManagedAction() : base() { Impersonate = false; Execute = Execute.deferred; UsesProperties="INSTALLDIR"; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> public ElevatedManagedAction(string name) : base(name) { Impersonate = false; Execute = Execute.deferred; UsesProperties = "INSTALLDIR"; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ElevatedManagedAction"/> instance.</param> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> public ElevatedManagedAction(Id id, string name) : base(id, name) { Impersonate = false; Execute = Execute.deferred; UsesProperties = "INSTALLDIR"; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> /// <param name="actionAssembly">Path to the assembly containing the CustomAction implementation. Specify <c>"%this%"</c> if the assembly /// is in the Wix# script.</param> public ElevatedManagedAction(string name, string actionAssembly) : base(name, actionAssembly) { Impersonate = false; Execute = Execute.deferred; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ElevatedManagedAction"/> instance.</param> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> /// <param name="actionAssembly">Path to the assembly containing the CustomAction implementation. Specify <c>"%this%"</c> if the assembly /// is in the Wix# script.</param> public ElevatedManagedAction(Id id, string name, string actionAssembly) : base(id, name, actionAssembly) { Impersonate = false; Execute = Execute.deferred; UsesProperties = "INSTALLDIR"; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="ManagedAction"/>.</param> public ElevatedManagedAction(string name, Return returnType, When when, Step step, Condition condition) : base(name, returnType, when, step, condition) { Impersonate = false; Execute = Execute.deferred; UsesProperties = "INSTALLDIR"; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> /// <param name="actionAssembly">Path to the assembly containing the CustomAction implementation. Specify <c>"%this%"</c> if the assembly /// is in the Wix# script.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="ManagedAction"/>.</param> public ElevatedManagedAction(string name, string actionAssembly, Return returnType, When when, Step step, Condition condition) : base(name, actionAssembly, returnType, when, step, condition) { Impersonate = false; Execute = Execute.deferred; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ElevatedManagedAction"/> instance.</param> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="ManagedAction"/>.</param> public ElevatedManagedAction(Id id, string name, Return returnType, When when, Step step, Condition condition) : base(id, name, returnType, when, step, condition) { Impersonate = false; Execute = Execute.deferred; UsesProperties = "INSTALLDIR"; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ElevatedManagedAction"/> instance.</param> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> /// <param name="actionAssembly">Path to the assembly containing the CustomAction implementation. Specify <c>"%this%"</c> if the assembly /// is in the Wix# script.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="ManagedAction"/>.</param> public ElevatedManagedAction(Id id, string name, string actionAssembly, Return returnType, When when, Step step, Condition condition) : base(id, name, actionAssembly, returnType, when, step, condition) { Impersonate = false; Execute = Execute.deferred; UsesProperties = "INSTALLDIR"; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="ManagedAction"/>.</param> /// <param name="sequence">The MSI sequence the action belongs to.</param> public ElevatedManagedAction(string name, Return returnType, When when, Step step, Condition condition, Sequence sequence) : base(name, returnType, when, step, condition, sequence) { Impersonate = false; Execute = Execute.deferred; UsesProperties = "INSTALLDIR"; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> /// <param name="actionAssembly">Path to the assembly containing the CustomAction implementation. Specify <c>"%this%"</c> if the assembly /// is in the Wix# script.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="ManagedAction"/>.</param> /// <param name="sequence">The MSI sequence the action belongs to.</param> public ElevatedManagedAction(string name, string actionAssembly, Return returnType, When when, Step step, Condition condition, Sequence sequence) : base(name, actionAssembly, returnType, when, step, condition, sequence) { Impersonate = false; Execute = Execute.deferred; UsesProperties = "INSTALLDIR"; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ElevatedManagedAction"/> instance.</param> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="ManagedAction"/>.</param> /// <param name="sequence">The MSI sequence the action belongs to.</param> public ElevatedManagedAction(Id id, string name, Return returnType, When when, Step step, Condition condition, Sequence sequence) : base(id, name, returnType, when, step, condition, sequence) { Impersonate = false; Execute = Execute.deferred; UsesProperties = "INSTALLDIR"; } /// <summary> /// Initializes a new instance of the <see cref="ElevatedManagedAction"/> class with properties/fields initialized with specified parameters. /// </summary> /// <param name="id">The explicit <see cref="Id"></see> to be associated with <see cref="ElevatedManagedAction"/> instance.</param> /// <param name="name">Name of the CustomAction. The name should match the method implementing the custom action functionality.</param> /// <param name="actionAssembly">Path to the assembly containing the CustomAction implementation. Specify <c>"%this%"</c> if the assembly /// is in the Wix# script.</param> /// <param name="returnType">The return type of the action.</param> /// <param name="when"><see cref="T:WixSharp.When"/> the action should be executed with respect to the <paramref name="step"/> parameter.</param> /// <param name="step"><see cref="T:WixSharp.Step"/> the action should be executed before/after during the installation.</param> /// <param name="condition">The launch condition for the <see cref="ManagedAction"/>.</param> /// <param name="sequence">The MSI sequence the action belongs to.</param> public ElevatedManagedAction(Id id, string name, string actionAssembly, Return returnType, When when, Step step, Condition condition, Sequence sequence) : base(id, name, actionAssembly, returnType, when, step, condition, sequence) { Impersonate = false; Execute = Execute.deferred; UsesProperties = "INSTALLDIR"; } } }
// Document.cs // Script#/Libraries/Web // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Runtime.CompilerServices; using System.Html.StyleSheets; using System.Html.Editing; namespace System.Html { [ScriptIgnoreNamespace] [ScriptImport] [ScriptName("document")] public static class Document { [ScriptField] public static Element ActiveElement { get { return null; } } [ScriptField] public static Element Body { get { return null; } } [ScriptField] public static string Cookie { get { return null; } set { } } [ScriptField] public static string Doctype { get { return null; } } [ScriptField] public static Element DocumentElement { get { return null; } } [ScriptField] public static string DesignMode { get { return null; } set { } } [ScriptField] public static string Domain { get { return null; } set { } } [ScriptField] public static DocumentImplementation Implementation { get { return null; } } [ScriptField] public static WindowInstance ParentWindow { get { return null; } } [ScriptField] public static string ReadyState { get { return null; } } [ScriptField] public static string Referrer { get { return null; } } [ScriptField] public static Selection Selection { get { return null; } } [ScriptField] public static StyleSheetList StyleSheets { get { return null; } } [ScriptField] public static string Title { get { return null; } set { } } [ScriptField] public static string URL { get { return null; } } /// <summary> /// Adds a listener for the specified event. /// </summary> /// <param name="eventName">The name of the event such as 'load'.</param> /// <param name="listener">The listener to be invoked in response to the event.</param> public static void AddEventListener(string eventName, ElementEventListener listener) { } /// <summary> /// Adds a listener for the specified event. /// </summary> /// <param name="eventName">The name of the event such as 'load'.</param> /// <param name="listener">The listener to be invoked in response to the event.</param> /// <param name="useCapture">Whether the listener wants to initiate capturing the event.</param> public static void AddEventListener(string eventName, ElementEventListener listener, bool useCapture) { } public static void AttachEvent(string eventName, ElementEventHandler handler) { } /// <summary> /// Creates an Attr of the given name. Note that the Attr instance can then be set on an /// Element using the setAttributeNode method. To create an attribute with a qualified name /// and namespace URI, use the CreateAttributeNS method. /// </summary> /// <param name="name">The name of the attribute.</param> /// <returns>A new Attr object with the nodeName attribute set to name, and localName, prefix, /// and namespaceURI set to null. The value of the attribute is the empty string.</returns> public static ElementAttribute CreateAttribute(string name) { return null; } /// <summary> /// Creates an attribute of the given qualified name and namespace URI. /// </summary> /// <param name="namespaceURI">The namespace URI of the attribute to create.</param> /// <param name="qualifiedName">The qualified name of the attribute to instantiate.</param> /// <returns>A new Attr object with the given namespace and qualified name.</returns> public static ElementAttribute CreateAttributeNS(string namespaceURI, string qualifiedName) { return null; } public static DocumentFragment CreateDocumentFragment() { return null; } /// <summary> /// Creates an element of the type specified. /// To create an element with a qualified name and namespace URI, use the CreateElementNS method. /// </summary> /// <param name="tagName">The name of the element type to instantiate.</param> /// <returns>A new Element object with the nodeName attribute set to tagName, and localName, /// prefix, and namespaceURI set to null.</returns> public static Element CreateElement(string tagName) { return null; } /// <summary> /// Creates an element of the given qualified name and namespace URI. /// </summary> /// <param name="namespaceURI">The namespace URI of the element to create.</param> /// <param name="qualifiedName">The qualified name of the element type to instantiate.</param> /// <returns>A new Element object with the given namespace and qualified name.</returns> public static Element CreateElementNS(string namespaceURI, string qualifiedName) { return null; } public static MutableEvent CreateEvent(string eventType) { return null; } public static Element CreateTextNode(string data) { return null; } public static Element ImportNode(Element imporedNode, bool deep) { return null; } public static void DetachEvent(string eventName, ElementEventHandler handler) { } public static bool DispatchEvent(MutableEvent eventObject) { return false; } public static Element ElementFromPoint(int x, int y) { return null; } public static bool ExecCommand(string command, bool displayUserInterface, object value) { return false; } public static void Focus() { } public static Element GetElementById(string id) { return null; } public static TElement GetElementById<TElement>(string id) where TElement : Element { return null; } public static ElementCollection GetElementsByClassName(string className) { return null; } public static ElementCollection GetElementsByName(string name) { return null; } public static ElementCollection GetElementsByTagName(string tagName) { return null; } /// <summary> /// Returns a NodeList of all the Elements with a given local name and namespace URI in the order in which they are encountered in a preorder traversal of the Document tree. /// </summary> /// <param name="namespaceURI">The namespace URI of the elements to match on. The special value "*" matches all namespaces.</param> /// <param name="localName">The local name of the elements to match on. The special value "*" matches all local names.</param> /// <returns>A new NodeList object containing all the matched Elements.</returns> public static ElementCollection GetElementsByTagNameNS(string namespaceURI, string localName) { return null; } public static bool HasFocus() { return false; } public static bool QueryCommandEnabled(string command) { return false; } public static bool QueryCommandIndeterm(string command) { return false; } public static bool QueryCommandState(string command) { return false; } public static bool QueryCommandSupported(string command) { return false; } public static object QueryCommandValue(string command) { return null; } public static Element QuerySelector(string selector) { return null; } public static ElementCollection QuerySelectorAll(string selector) { return null; } /// <summary> /// Removes a listener for the specified event. /// </summary> /// <param name="eventName">The name of the event such as 'load'.</param> /// <param name="listener">The listener to be invoked in response to the event.</param> public static void RemoveEventListener(string eventName, ElementEventListener listener) { } /// <summary> /// Removes a listener for the specified event. /// </summary> /// <param name="eventName">The name of the event such as 'load'.</param> /// <param name="listener">The listener to be invoked in response to the event.</param> /// <param name="useCapture">Whether the listener wants to initiate capturing the event.</param> public static void RemoveEventListener(string eventName, ElementEventListener listener, bool useCapture) { } } }
using System; using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Security; using System.Threading.Tasks; using Newtonsoft.Json; namespace Meadow.Services.Geocoding.Geocodio { /// <summary> /// A geocoding service which uses Geocodio as its source. /// </summary> public partial class GeocodioGeoProvider : GeoProviderBase { /// <inheritdoc /> public override string ProviderName => "Geocodio"; /// <inheritdoc /> public override int MaximumBatchSize => 10000; private const float _AccuracyThreshold = 0.925f; /// <inheritdoc /> public GeocodioGeoProvider(Uri uri = null) : base(uri) { } /// <inheritdoc /> protected override Task<SecureString> GetApiKey(IGeoSecureCredentials credentials) { return Task.FromResult(credentials.ApiKey); } /// <inheritdoc /> /// <exception cref="ArgumentNullException">Thrown if <paramref name="credentials"/> is <see langword="null"/>.</exception> /// <exception cref="RuntimeException">Unknown provider service type.</exception> /// <exception cref="NotSupportedException">The current computer is not running Windows 2000 Service Pack 3 or later.</exception> /// <exception cref="OutOfMemoryException">There is insufficient memory available.</exception> public override string GetApiUriForService(EGeoProviderService service, IGeoSecureCredentials credentials, string format = "json") { MeadowAssert.ArgumentNotNull(nameof(credentials), credentials); if (_UriOverride != null) { return _UriOverride.ToString(); } switch (service) { case EGeoProviderService.AddressLookup: return $"https://api.geocod.io/v1/reverse?api_key={credentials.ApiKey?.FromSecureString()}"; case EGeoProviderService.CoordinateLookup: return $"https://api.geocod.io/v1/geocode?api_key={credentials.ApiKey?.FromSecureString()}"; //?street=&city=&state=&postal_code= default: return base.GetApiUriForService(service, credentials, format); } } /// <inheritdoc /> /// <exception cref="ArgumentNullException">Thrown if <paramref name="credentials"/> is <see langword="null"/>.</exception> /// <exception cref="Exception"></exception> public override Task<IEnumerable<IGeocodedAddress>> FetchCoordinatesBatch(IGeoSecureCredentials credentials, IEnumerable<IAddress> addressBatch, int concurrencySize) { return FetchInternal(credentials, addressBatch, DoFetchCoordinates, false, concurrencySize); } /// <inheritdoc /> /// <exception cref="ArgumentNullException">Thrown if <paramref name="credentials"/> is <see langword="null"/>.</exception> /// <exception cref="Exception"></exception> public override Task FetchCoordinatesBatch(IGeoSecureCredentials credentials, IEnumerable<IGeocodedAddress> addressBatch, int concurrencySize) { return FetchInternal(credentials, addressBatch.Cast<IAddress>(), DoFetchCoordinates, true, concurrencySize); } /// <inheritdoc /> /// <exception cref="ArgumentNullException">Thrown if <paramref name="credentials"/> is <see langword="null"/>.</exception> /// <exception cref="Exception"></exception> public override Task FetchCoordinatesBatch(IGeoSecureCredentials credentials, IEnumerable<IGeocodedAddress2> addressBatch, int concurrencySize) { return FetchInternal(credentials, addressBatch.Cast<IAddress>(), DoFetchCoordinates, true, concurrencySize); } /// <inheritdoc /> /// <exception cref="ArgumentNullException">Thrown if <paramref name="credentials"/> is <see langword="null"/>.</exception> /// <exception cref="Exception"></exception> public override Task FetchAddressBatch(IGeoSecureCredentials credentials, IEnumerable<IGeocodedAddress2> coordinateBatch, int concurrencySize) { return FetchInternal(credentials, coordinateBatch.Cast<ICoordinates>(), DoFetchAddress, true, concurrencySize); } /// <inheritdoc /> /// <exception cref="ArgumentNullException">Thrown if <paramref name="credentials"/> is <see langword="null"/>.</exception> /// <exception cref="Exception"></exception> public override Task<IEnumerable<IGeocodedAddress>> FetchAddressBatch(IGeoSecureCredentials credentials, IEnumerable<ICoordinates> coordinateBatch, int concurrencySize) { return FetchInternal(credentials, coordinateBatch, DoFetchAddress, false, concurrencySize); } /// <inheritdoc /> /// <exception cref="ArgumentNullException">Thrown if <paramref name="credentials"/> is <see langword="null"/>.</exception> /// <exception cref="Exception"></exception> public override Task<IEnumerable<IGeocodedAddress>> FetchAddressBatch(IGeoSecureCredentials credentials, IEnumerable<IHasCoordinates> coordinateBatch, int concurrencySize) { return FetchInternal(credentials, coordinateBatch.Select(p => p.Coordinates), DoFetchAddress, false, concurrencySize); } /// <inheritdoc /> /// <exception cref="ArgumentNullException">Thrown if <paramref name="credentials"/> is <see langword="null"/>.</exception> /// <exception cref="Exception"></exception> public override Task FetchAddressBatch(IGeoSecureCredentials credentials, IEnumerable<IGeocodedAddress> coordinateBatch, int concurrencySize) { return FetchInternal(credentials, coordinateBatch.Cast<IHasCoordinates>(), DoFetchAddress, true, concurrencySize); } private async Task<Dictionary<int, IGeocodedAddress>> DoFetchCoordinates(List<IAddress> addresses, IGeoSecureCredentials credentials) { var rawData = new Dictionary<string, GeocodioCoordinateRequest>(addresses.Count); for (int i = 0; i < addresses.Count; ++i) { IAddress address = addresses[i]; if (address == null) { continue; } rawData.Add(i.ToString(), new GeocodioCoordinateRequest { Street = address.StreetAddress, City = address.City, State = address.State, Zip = address.Zip, PostalCode = address.Zip }); } string jsonData = JsonConvert.SerializeObject(rawData); var encodedData = new StringContent(jsonData); encodedData.Headers.ContentType = new MediaTypeHeaderValue("application/json"); using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(Math.Max(rawData.Count * 2, 150)) }) { var response = await client.PostAsync(GetApiUriForService(EGeoProviderService.CoordinateLookup, credentials), encodedData).ConfigureAwait(false); var resultJson = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var resultData = JsonConvert.DeserializeObject<GeocodioCoordinateResults>(resultJson); if (resultData == null) { throw Exceptions.Runtime("Unable to create result data."); } if (!string.IsNullOrEmpty(resultData.Error)) { throw Exceptions.Runtime(resultData.Error); } var results = new Dictionary<int, IGeocodedAddress>(resultData.Results.Count); for (int i = 0; i < resultData.Results.Count; ++i) { var address = resultData.Results[i]; foreach (var result in address.Response.Results) { // If AccuracyScore <= 0.925 then fail it. This isn't accurate enough for a successful result. if (float.TryParse(result.Accuracy, out float accuracyScore) && accuracyScore >= _AccuracyThreshold) { IAddress originalAddress = addresses[i]; results.Add(i, new GeocodedAddress { StreetAddress = originalAddress.StreetAddress, City = originalAddress.City, State = originalAddress.State, Zip = originalAddress.Zip, Coordinates = new Coordinates(result.Location.Latitude, result.Location.Longitude) }); break; } } } return results; } } private async Task<Dictionary<int, IGeocodedAddress>> DoFetchAddress(List<ICoordinates> coordinates, IGeoSecureCredentials credentials) { var rawData = coordinates.Select(p => $"{p.Latitude},{p.Longitude}"); string jsonData = JsonConvert.SerializeObject(rawData); var encodedData = new StringContent(jsonData); encodedData.Headers.ContentType = new MediaTypeHeaderValue("application/json"); using (var client = new HttpClient { Timeout = TimeSpan.FromSeconds(Math.Max(rawData.Count() * 2, 150)) }) { var response = await client.PostAsync(GetApiUriForService(EGeoProviderService.AddressLookup, credentials), encodedData).ConfigureAwait(false); var resultJson = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var resultData = JsonConvert.DeserializeObject<GeocodioAddressResults>(resultJson); if (resultData == null) { throw Exceptions.Runtime("Unable to create result data."); } var results = new Dictionary<int, IGeocodedAddress>(resultData.Results.Count); for (int i = 0; i < resultData.Results.Count; ++i) { var address = resultData.Results[i]; foreach (var result in address.Response.Results) { // If AccuracyScore <= 0.925 then fail it. This isn't accurate enough for a successful result. if (float.TryParse(result.Accuracy, out float accuracyScore) && accuracyScore > _AccuracyThreshold) { ICoordinates originalCoordinates = coordinates[i]; results.Add(i, new GeocodedAddress { StreetAddress = result.AddressComponents.FormattedStreet, City = result.AddressComponents.City, State = result.AddressComponents.State, Zip = result.AddressComponents.Zip, Coordinates = new Coordinates(originalCoordinates) //result.Location }); break; } } } return results; } } private Task<Dictionary<int, IGeocodedAddress>> DoFetchAddress(List<IHasCoordinates> coordinates, IGeoSecureCredentials credentials) { return DoFetchAddress(coordinates.Select(p => p.Coordinates).ToList(), credentials); } } }
using System; using System.Linq; using System.Runtime.InteropServices; using Torque6.Engine.SimObjects; using Torque6.Engine.SimObjects.Scene; using Torque6.Engine.Namespaces; using Torque6.Utility; namespace Torque6.Engine.SimObjects { public unsafe class NameTags : SimSet { public NameTags() { ObjectPtr = Sim.WrapObject(InternalUnsafeMethods.NameTagsCreateInstance()); } public NameTags(uint pId) : base(pId) { } public NameTags(string pName) : base(pName) { } public NameTags(IntPtr pObjPtr) : base(pObjPtr) { } public NameTags(Sim.SimObjectPtr* pObjPtr) : base(pObjPtr) { } public NameTags(SimObject pObj) : base(pObj) { } #region UnsafeNativeMethods new internal struct InternalUnsafeMethods { [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _NameTagsCreateInstance(); private static _NameTagsCreateInstance _NameTagsCreateInstanceFunc; internal static IntPtr NameTagsCreateInstance() { if (_NameTagsCreateInstanceFunc == null) { _NameTagsCreateInstanceFunc = (_NameTagsCreateInstance)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsCreateInstance"), typeof(_NameTagsCreateInstance)); } return _NameTagsCreateInstanceFunc(); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _NameTagsCreateTag(IntPtr nameTags, string newTagName); private static _NameTagsCreateTag _NameTagsCreateTagFunc; internal static int NameTagsCreateTag(IntPtr nameTags, string newTagName) { if (_NameTagsCreateTagFunc == null) { _NameTagsCreateTagFunc = (_NameTagsCreateTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsCreateTag"), typeof(_NameTagsCreateTag)); } return _NameTagsCreateTagFunc(nameTags, newTagName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _NameTagsRenameTag(IntPtr nameTags, int tagId, string newTagName); private static _NameTagsRenameTag _NameTagsRenameTagFunc; internal static int NameTagsRenameTag(IntPtr nameTags, int tagId, string newTagName) { if (_NameTagsRenameTagFunc == null) { _NameTagsRenameTagFunc = (_NameTagsRenameTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsRenameTag"), typeof(_NameTagsRenameTag)); } return _NameTagsRenameTagFunc(nameTags, tagId, newTagName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _NameTagsDeleteTag(IntPtr nameTags, int tagId); private static _NameTagsDeleteTag _NameTagsDeleteTagFunc; internal static int NameTagsDeleteTag(IntPtr nameTags, int tagId) { if (_NameTagsDeleteTagFunc == null) { _NameTagsDeleteTagFunc = (_NameTagsDeleteTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsDeleteTag"), typeof(_NameTagsDeleteTag)); } return _NameTagsDeleteTagFunc(nameTags, tagId); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _NameTagsGetTagCount(IntPtr nameTags); private static _NameTagsGetTagCount _NameTagsGetTagCountFunc; internal static int NameTagsGetTagCount(IntPtr nameTags) { if (_NameTagsGetTagCountFunc == null) { _NameTagsGetTagCountFunc = (_NameTagsGetTagCount)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsGetTagCount"), typeof(_NameTagsGetTagCount)); } return _NameTagsGetTagCountFunc(nameTags); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _NameTagsGetTagName(IntPtr nameTags, int tagId); private static _NameTagsGetTagName _NameTagsGetTagNameFunc; internal static IntPtr NameTagsGetTagName(IntPtr nameTags, int tagId) { if (_NameTagsGetTagNameFunc == null) { _NameTagsGetTagNameFunc = (_NameTagsGetTagName)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsGetTagName"), typeof(_NameTagsGetTagName)); } return _NameTagsGetTagNameFunc(nameTags, tagId); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate int _NameTagsGetTagId(IntPtr nameTags, string tagName); private static _NameTagsGetTagId _NameTagsGetTagIdFunc; internal static int NameTagsGetTagId(IntPtr nameTags, string tagName) { if (_NameTagsGetTagIdFunc == null) { _NameTagsGetTagIdFunc = (_NameTagsGetTagId)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsGetTagId"), typeof(_NameTagsGetTagId)); } return _NameTagsGetTagIdFunc(nameTags, tagName); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _NameTagsGetAllTags(IntPtr nameTags); private static _NameTagsGetAllTags _NameTagsGetAllTagsFunc; internal static IntPtr NameTagsGetAllTags(IntPtr nameTags) { if (_NameTagsGetAllTagsFunc == null) { _NameTagsGetAllTagsFunc = (_NameTagsGetAllTags)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsGetAllTags"), typeof(_NameTagsGetAllTags)); } return _NameTagsGetAllTagsFunc(nameTags); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _NameTagsTag(IntPtr nameTags, int objectId, int tagIdsC, int[] tagIdsV); private static _NameTagsTag _NameTagsTagFunc; internal static bool NameTagsTag(IntPtr nameTags, int objectId, int tagIdsC, int[] tagIdsV) { if (_NameTagsTagFunc == null) { _NameTagsTagFunc = (_NameTagsTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsTag"), typeof(_NameTagsTag)); } return _NameTagsTagFunc(nameTags, objectId, tagIdsC, tagIdsV); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _NameTagsUntag(IntPtr nameTags, int objectId, int tagIdsC, int[] tagIdsV); private static _NameTagsUntag _NameTagsUntagFunc; internal static bool NameTagsUntag(IntPtr nameTags, int objectId, int tagIdsC, int[] tagIdsV) { if (_NameTagsUntagFunc == null) { _NameTagsUntagFunc = (_NameTagsUntag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsUntag"), typeof(_NameTagsUntag)); } return _NameTagsUntagFunc(nameTags, objectId, tagIdsC, tagIdsV); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate bool _NameTagsHasTag(IntPtr nameTags, int objectId, int tagIdsC, int[] tagIdsV); private static _NameTagsHasTag _NameTagsHasTagFunc; internal static bool NameTagsHasTag(IntPtr nameTags, int objectId, int tagIdsC, int[] tagIdsV) { if (_NameTagsHasTagFunc == null) { _NameTagsHasTagFunc = (_NameTagsHasTag)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsHasTag"), typeof(_NameTagsHasTag)); } return _NameTagsHasTagFunc(nameTags, objectId, tagIdsC, tagIdsV); } [UnmanagedFunctionPointer(CallingConvention.Cdecl)] private delegate IntPtr _NameTagsQueryTags(IntPtr nameTags, int tagIdsC, int[] tagIdsV, bool excluded); private static _NameTagsQueryTags _NameTagsQueryTagsFunc; internal static IntPtr NameTagsQueryTags(IntPtr nameTags, int tagIdsC, int[] tagIdsV, bool excluded) { if (_NameTagsQueryTagsFunc == null) { _NameTagsQueryTagsFunc = (_NameTagsQueryTags)Marshal.GetDelegateForFunctionPointer(Interop.Torque6.DllLoadUtils.GetProcAddress(Interop.Torque6.Torque6LibHandle, "NameTagsQueryTags"), typeof(_NameTagsQueryTags)); } return _NameTagsQueryTagsFunc(nameTags, tagIdsC, tagIdsV, excluded); } } #endregion #region Properties #endregion #region Methods public int CreateTag(string newTagName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NameTagsCreateTag(ObjectPtr->ObjPtr, newTagName); } public int RenameTag(int tagId, string newTagName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NameTagsRenameTag(ObjectPtr->ObjPtr, tagId, newTagName); } public int DeleteTag(int tagId) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NameTagsDeleteTag(ObjectPtr->ObjPtr, tagId); } public int GetTagCount() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NameTagsGetTagCount(ObjectPtr->ObjPtr); } public string GetTagName(int tagId) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.NameTagsGetTagName(ObjectPtr->ObjPtr, tagId)); } public int GetTagId(string tagName) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NameTagsGetTagId(ObjectPtr->ObjPtr, tagName); } public string GetAllTags() { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.NameTagsGetAllTags(ObjectPtr->ObjPtr)); } public bool Tag(int objectId, int tagIdsC, int[] tagIdsV) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NameTagsTag(ObjectPtr->ObjPtr, objectId, tagIdsC, tagIdsV); } public bool Untag(int objectId, int tagIdsC, int[] tagIdsV) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NameTagsUntag(ObjectPtr->ObjPtr, objectId, tagIdsC, tagIdsV); } public bool HasTag(int objectId, int tagIdsC, int[] tagIdsV) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return InternalUnsafeMethods.NameTagsHasTag(ObjectPtr->ObjPtr, objectId, tagIdsC, tagIdsV); } public string QueryTags(int tagIdsC, int[] tagIdsV, bool excluded = false) { if (IsDead()) throw new Exceptions.SimObjectPointerInvalidException(); return Marshal.PtrToStringAnsi(InternalUnsafeMethods.NameTagsQueryTags(ObjectPtr->ObjPtr, tagIdsC, tagIdsV, excluded)); } #endregion } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System.Collections; using System.Collections.Generic; using System.Management.Automation.Internal; namespace System.Management.Automation { /// <summary> /// Implements the help provider for alias help. /// </summary> /// <remarks> /// Unlike other help providers, AliasHelpProvider directly inherits from HelpProvider /// instead of HelpProviderWithCache. This is because alias can be created/removed/updated /// in a Microsoft Command Shell session. And thus caching may result in old alias being cached. /// /// The real information for alias is stored in command help. To retrieve the real /// help information, help forwarding is needed. /// </remarks> internal class AliasHelpProvider : HelpProvider { /// <summary> /// Initializes a new instance of AliasHelpProvider class. /// </summary> internal AliasHelpProvider(HelpSystem helpSystem) : base(helpSystem) { _sessionState = helpSystem.ExecutionContext.SessionState; _commandDiscovery = helpSystem.ExecutionContext.CommandDiscovery; _context = helpSystem.ExecutionContext; } private readonly ExecutionContext _context; /// <summary> /// Session state for current Microsoft Command Shell session. /// </summary> /// <remarks> /// _sessionState is mainly used for alias help search in the case /// of wildcard search patterns. This is currently not achievable /// through _commandDiscovery. /// </remarks> private SessionState _sessionState; /// <summary> /// Command Discovery object for current session. /// </summary> /// <remarks> /// _commandDiscovery is mainly used for exact match help for alias. /// The AliasInfo object returned from _commandDiscovery is essential /// in creating AliasHelpInfo. /// </remarks> private CommandDiscovery _commandDiscovery; #region Common Properties /// <summary> /// Name of alias help provider. /// </summary> /// <value>Name of alias help provider</value> internal override string Name { get { return "Alias Help Provider"; } } /// <summary> /// Help category of alias help provider, which is a constant: HelpCategory.Alias. /// </summary> /// <value>Help category of alias help provider.</value> internal override HelpCategory HelpCategory { get { return HelpCategory.Alias; } } #endregion #region Help Provider Interface /// <summary> /// Exact match an alias help target. /// </summary> /// <remarks> /// This will /// a. use _commandDiscovery object to retrieve AliasInfo object. /// b. Create AliasHelpInfo object based on AliasInfo object /// </remarks> /// <param name="helpRequest">Help request object.</param> /// <returns>Help info found.</returns> internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest) { CommandInfo commandInfo = null; try { commandInfo = _commandDiscovery.LookupCommandInfo(helpRequest.Target); } catch (CommandNotFoundException) { // CommandNotFoundException is expected here if target doesn't match any // commandlet. Just ignore this exception and bail out. } if ((commandInfo != null) && (commandInfo.CommandType == CommandTypes.Alias)) { AliasInfo aliasInfo = (AliasInfo)commandInfo; HelpInfo helpInfo = AliasHelpInfo.GetHelpInfo(aliasInfo); if (helpInfo != null) { yield return helpInfo; } } } /// <summary> /// Search an alias help target. /// </summary> /// <remarks> /// This will, /// a. use _sessionState object to get a list of alias that match the target. /// b. for each alias, retrieve help info as in ExactMatchHelp. /// </remarks> /// <param name="helpRequest">Help request object.</param> /// <param name="searchOnlyContent"> /// If true, searches for pattern in the help content. Individual /// provider can decide which content to search in. /// /// If false, searches for pattern in the command names. /// </param> /// <returns>A IEnumerable of helpinfo object.</returns> internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { // aliases do not have help content...so doing nothing in that case if (!searchOnlyContent) { string target = helpRequest.Target; string pattern = target; Hashtable hashtable = new Hashtable(StringComparer.OrdinalIgnoreCase); if (!WildcardPattern.ContainsWildcardCharacters(target)) { pattern += "*"; } WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); IDictionary<string, AliasInfo> aliasTable = _sessionState.Internal.GetAliasTable(); foreach (string name in aliasTable.Keys) { if (matcher.IsMatch(name)) { HelpRequest exactMatchHelpRequest = helpRequest.Clone(); exactMatchHelpRequest.Target = name; // Duplicates?? foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest)) { // Component/Role/Functionality match is done only for SearchHelp // as "get-help * -category alias" should not forwad help to // CommandHelpProvider..(ExactMatchHelp does forward help to // CommandHelpProvider) if (!Match(helpInfo, helpRequest)) { continue; } if (hashtable.ContainsKey(name)) { continue; } hashtable.Add(name, null); yield return helpInfo; } } } CommandSearcher searcher = new CommandSearcher( pattern, SearchResolutionOptions.ResolveAliasPatterns, CommandTypes.Alias, _context); while (searcher.MoveNext()) { CommandInfo current = ((IEnumerator<CommandInfo>)searcher).Current; if (_context.CurrentPipelineStopping) { yield break; } AliasInfo alias = current as AliasInfo; if (alias != null) { string name = alias.Name; HelpRequest exactMatchHelpRequest = helpRequest.Clone(); exactMatchHelpRequest.Target = name; // Duplicates?? foreach (HelpInfo helpInfo in ExactMatchHelp(exactMatchHelpRequest)) { // Component/Role/Functionality match is done only for SearchHelp // as "get-help * -category alias" should not forwad help to // CommandHelpProvider..(ExactMatchHelp does forward help to // CommandHelpProvider) if (!Match(helpInfo, helpRequest)) { continue; } if (hashtable.ContainsKey(name)) { continue; } hashtable.Add(name, null); yield return helpInfo; } } } foreach (CommandInfo current in ModuleUtils.GetMatchingCommands(pattern, _context, helpRequest.CommandOrigin)) { if (_context.CurrentPipelineStopping) { yield break; } AliasInfo alias = current as AliasInfo; if (alias != null) { string name = alias.Name; HelpInfo helpInfo = AliasHelpInfo.GetHelpInfo(alias); if (hashtable.ContainsKey(name)) { continue; } hashtable.Add(name, null); yield return helpInfo; } } } } private static bool Match(HelpInfo helpInfo, HelpRequest helpRequest) { if (helpRequest == null) return true; if (0 == (helpRequest.HelpCategory & helpInfo.HelpCategory)) { return false; } if (!Match(helpInfo.Component, helpRequest.Component)) { return false; } if (!Match(helpInfo.Role, helpRequest.Role)) { return false; } if (!Match(helpInfo.Functionality, helpRequest.Functionality)) { return false; } return true; } private static bool Match(string target, string[] patterns) { // patterns should never be null as shell never accepts // empty inputs. Keeping this check as a safe measure. if (patterns == null || patterns.Length == 0) return true; foreach (string pattern in patterns) { if (Match(target, pattern)) { // we have a match so return true return true; } } // We dont have a match so far..so return false return false; } private static bool Match(string target, string pattern) { if (string.IsNullOrEmpty(pattern)) return true; if (string.IsNullOrEmpty(target)) target = string.Empty; WildcardPattern matcher = WildcardPattern.Get(pattern, WildcardOptions.IgnoreCase); return matcher.IsMatch(target); } #endregion } }
using System; using System.Collections.Generic; using System.Text; using Hydra.Framework.Mapping.Geometries; using Hydra.Framework.Mapping.CoordinateSystems; using Hydra.Framework.Mapping.CoordinateSystems.Transformations; namespace Hydra.Framework.Mapping.CoordinateSystems.Projections { // // ********************************************************************** /// <summary> /// Projections inherit from this abstract class to get access to useful mathematical functions. /// </summary> // ********************************************************************** // internal abstract class AbstractMapProjection : AbstractMathTransform, IProjection { #region Constants // // ********************************************************************** /// <summary> /// PI /// </summary> // ********************************************************************** // protected const double PI = Math.PI; // // ********************************************************************** /// <summary> /// Half of PI /// </summary> // ********************************************************************** // protected const double HALF_PI = (PI * 0.5); // // ********************************************************************** /// <summary> /// PI * 2 /// </summary> // ********************************************************************** // protected const double TWO_PI = (PI * 2.0); // // ********************************************************************** /// <summary> /// EPSLN /// </summary> // ********************************************************************** // protected const double EPSLN = 1.0e-10; // // ********************************************************************** /// <summary> /// S2R /// </summary> // ********************************************************************** // protected const double S2R = 4.848136811095359e-6; // // ********************************************************************** /// <summary> /// MAX_VAL /// </summary> // ********************************************************************** // protected const double MAX_VAL = 4; // // ********************************************************************** /// <summary> /// prjMAXLONG /// </summary> // ********************************************************************** // protected const double prjMAXLONG = 2147483647; // // ********************************************************************** /// <summary> /// DBLLONG /// </summary> // ********************************************************************** // protected const double DBLLONG = 4.61168601e18; #endregion #region Member Variables // // ********************************************************************** /// <summary> /// Is Inverse /// </summary> // ********************************************************************** // private bool m_IsInverse = false; // // ********************************************************************** /// <summary> /// Is Spherical /// </summary> // ********************************************************************** // private bool m_IsSpherical = false; // // ********************************************************************** /// <summary> /// Eccentricity /// </summary> // ********************************************************************** // private double m_Eccentricity; // // ********************************************************************** /// <summary> /// Eccentricity 2 /// </summary> // ********************************************************************** // private double m_Eccentricity2; // // ********************************************************************** /// <summary> /// Semi Major /// </summary> // ********************************************************************** // private double m_SemiMajor; // // ********************************************************************** /// <summary> /// Semi Minor /// </summary> // ********************************************************************** // private double m_SemiMinor; // // ********************************************************************** /// <summary> /// Abbreviation /// </summary> // ********************************************************************** // private string m_Abbreviation; // // ********************************************************************** /// <summary> /// Alias /// </summary> // ********************************************************************** // private string m_Alias; // // ********************************************************************** /// <summary> /// Authority /// </summary> // ********************************************************************** // private string m_Authority; // // ********************************************************************** /// <summary> /// Code /// </summary> // ********************************************************************** // private long m_Code; // // ********************************************************************** /// <summary> /// StateName /// </summary> // ********************************************************************** // private string m_Name; // // ********************************************************************** /// <summary> /// Comments /// </summary> // ********************************************************************** // private string m_Remarks; // // ********************************************************************** /// <summary> /// List of Projection Parameters /// </summary> // ********************************************************************** // private List<ProjectionParameter> m_Parameters; // // ********************************************************************** /// <summary> /// Inverse Transformation /// </summary> // ********************************************************************** // private AbstractMathTransform m_Inverse; #endregion #region Constants // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="AbstractMapProjection"/> class. /// </summary> /// <param name="parameters">The parameters.</param> /// <param name="isInverse">if set to <c>true</c> [is inverse].</param> // ********************************************************************** // protected AbstractMapProjection(List<ProjectionParameter> parameters, bool isInverse) : this(parameters) { m_IsInverse = isInverse; } // // ********************************************************************** /// <summary> /// Initializes a new instance of the <see cref="AbstractMapProjection"/> class. /// </summary> /// <param name="parameters">The parameters.</param> // ********************************************************************** // protected AbstractMapProjection(List<ProjectionParameter> parameters) { m_Parameters = parameters; // // TODO: Should really convert to the correct linear units?? // ProjectionParameter semimajor = GetParameter("semi_major"); ProjectionParameter semiminor = GetParameter("semi_minor"); if (semimajor == null) throw new ArgumentException("Missing projection parameter 'semi_major'"); if (semiminor == null) throw new ArgumentException("Missing projection parameter 'semi_minor'"); this.m_SemiMajor = semimajor.Value; this.m_SemiMinor = semiminor.Value; this.m_IsSpherical = (m_SemiMajor == m_SemiMinor); this.m_Eccentricity2 = 1.0 - (m_SemiMinor * m_SemiMinor) / (m_SemiMajor * m_SemiMajor); this.m_Eccentricity = Math.Sqrt(m_Eccentricity2); } #endregion #region Properties // // ********************************************************************** /// <summary> /// Gets or sets a value indicating whether this instance is inverse. /// </summary> /// <value> /// <c>true</c> if this instance is inverse; otherwise, <c>false</c>. /// </value> // ********************************************************************** // public bool IsInverse { get { return m_IsInverse; } set { m_IsInverse = value; } } // // ********************************************************************** /// <summary> /// Gets or sets a value indicating whether this instance is spherical. /// </summary> /// <value> /// <c>true</c> if this instance is spherical; otherwise, <c>false</c>. /// </value> // ********************************************************************** // public bool IsSpherical { get { return m_IsSpherical; } set { m_IsSpherical = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the eccentricity. /// </summary> /// <value>The eccentricity.</value> // ********************************************************************** // public double Eccentricity { get { return m_Eccentricity; } set { m_Eccentricity = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the eccentricity2. /// </summary> /// <value>The eccentricity2.</value> // ********************************************************************** // public double Eccentricity2 { get { return m_Eccentricity2; } set { m_Eccentricity2 = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the semi major. /// </summary> /// <value>The semi major.</value> // ********************************************************************** // public double SemiMajor { get { return m_SemiMajor; } set { m_SemiMajor = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the semi minor. /// </summary> /// <value>The semi minor.</value> // ********************************************************************** // public double SemiMinor { get { return m_SemiMinor; } set { m_SemiMinor = value; } } // // ********************************************************************** /// <summary> /// Gets number of parameters of the projection. /// </summary> /// <value></value> // ********************************************************************** // public int NumParameters { get { return this.m_Parameters.Count; } } // // ********************************************************************** /// <summary> /// Gets the projection classification name (e.g. 'Transverse_Mercator'). /// </summary> /// <value></value> // ********************************************************************** // public string ClassName { get { return this.ClassName; } } // // ********************************************************************** /// <summary> /// Gets or sets the abbreviation of the object. /// </summary> /// <value></value> // ********************************************************************** // public string Abbreviation { get { return m_Abbreviation; } set { m_Abbreviation = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the alias of the object. /// </summary> /// <value></value> // ********************************************************************** // public string Alias { get { return m_Alias; } set { m_Alias = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the authority name for this object, e.g., "EPSG", /// is this is a standard object with an authority specific /// identity code. Returns "CUSTOM" if this is a custom object. /// </summary> /// <value></value> // ********************************************************************** // public string Authority { get { return m_Authority; } set { m_Authority = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the authority specific identification code of the object /// </summary> /// <value></value> // ********************************************************************** // public long AuthorityCode { get { return m_Code; } set { m_Code = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the name of the object. /// </summary> /// <value></value> // ********************************************************************** // public string Name { get { return m_Name; } set { m_Name = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the provider-supplied remarks for the object. /// </summary> /// <value></value> // ********************************************************************** // public string Remarks { get { return m_Remarks; } set { m_Remarks = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the parameters. /// </summary> /// <value>The parameters.</value> // ********************************************************************** // public List<ProjectionParameter> Parameters { get { return m_Parameters; } set { m_Parameters = value; } } // // ********************************************************************** /// <summary> /// Gets or sets the inverse. /// </summary> /// <value>The inverse.</value> // ********************************************************************** // public AbstractMathTransform InverseProperty { get { return m_Inverse; } set { m_Inverse = value; } } // // ********************************************************************** /// <summary> /// Returns the Well-known text for this object /// as defined in the simple features specification. /// </summary> /// <value></value> // ********************************************************************** // public override string WKT { get { StringBuilder sb = new StringBuilder(); if (m_IsInverse) sb.Append("INVERSE_MT["); sb.AppendFormat("PARAM_MT[\"{0}\"", this.Name); for (int i = 0; i < this.NumParameters; i++) sb.AppendFormat(", {0}", this.GetParameter(i).WKT); sb.Append("]"); if (m_IsInverse) sb.Append("]"); return sb.ToString(); } } // // ********************************************************************** /// <summary> /// Gets an XML representation of this object /// </summary> /// <value></value> // ********************************************************************** // public override string XML { get { StringBuilder sb = new StringBuilder(); sb.Append("<CT_MathTransform>"); if (m_IsInverse) sb.AppendFormat("<CT_InverseTransform StateName=\"{0}\">", ClassName); else sb.AppendFormat("<CT_ParameterizedMathTransform StateName=\"{0}\">", ClassName); for (int i = 0; i < this.NumParameters; i++) sb.AppendFormat(this.GetParameter(i).XML); if (m_IsInverse) sb.Append("</CT_InverseTransform>"); else sb.Append("</CT_ParameterizedMathTransform>"); sb.Append("</CT_MathTransform>"); return sb.ToString(); } } #endregion #region Implementation of IProjection // // ********************************************************************** /// <summary> /// Gets the parameter. /// </summary> /// <param name="Index">The index.</param> /// <returns></returns> // ********************************************************************** // public ProjectionParameter GetParameter(int Index) { return this.m_Parameters[Index]; } // // ********************************************************************** /// <summary> /// Gets an named parameter of the projection. /// </summary> /// <remarks>The parameter name is case insensitive</remarks> /// <param name="name">StateName of parameter</param> /// <returns>parameter or null if not found</returns> // ********************************************************************** // public ProjectionParameter GetParameter(string name) { return m_Parameters.Find(delegate(ProjectionParameter par) { return par.Name.Equals(name, StringComparison.OrdinalIgnoreCase); }); } #endregion #region IMathTransform Implementation // // ********************************************************************** /// <summary> /// Meterses to degrees. /// </summary> /// <param name="p">The p.</param> /// <returns></returns> // ********************************************************************** // public abstract Hydra.Framework.Mapping.Geometries.Point MetersToDegrees(Hydra.Framework.Mapping.Geometries.Point p); // // ********************************************************************** /// <summary> /// Degreeses to meters. /// </summary> /// <param name="lonlat">The lonlat.</param> /// <returns></returns> // ********************************************************************** // public abstract Hydra.Framework.Mapping.Geometries.Point DegreesToMeters(Hydra.Framework.Mapping.Geometries.Point lonlat); // // ********************************************************************** /// <summary> /// Reverses the transformation /// </summary> // ********************************************************************** // public override void Invert() { m_IsInverse = !m_IsInverse; } // // ********************************************************************** /// <summary> /// Transforms the specified cp. /// </summary> /// <param name="cp">The cp.</param> /// <returns></returns> // ********************************************************************** // public override Hydra.Framework.Mapping.Geometries.Point Transform(Hydra.Framework.Mapping.Geometries.Point cp) { Point projectedPoint = new Point(); return (!m_IsInverse) ? this.DegreesToMeters(cp) : this.MetersToDegrees(cp); } // // ********************************************************************** /// <summary> /// Transforms the list. /// </summary> /// <param name="ord">The ord.</param> /// <returns></returns> // ********************************************************************** // public override List<Hydra.Framework.Mapping.Geometries.Point> TransformList(List<Hydra.Framework.Mapping.Geometries.Point> ord) { List<Hydra.Framework.Mapping.Geometries.Point> result = new List<Hydra.Framework.Mapping.Geometries.Point>(ord.Count); for (int i = 0; i < ord.Count; i++) { Hydra.Framework.Mapping.Geometries.Point point = ord[i]; result.Add(Transform(point)); } return result; } // // ********************************************************************** /// <summary> /// Checks whether the values of this instance is equal to the values of another instance. /// Only parameters used for coordinate system are used for comparison. /// StateName, abbreviation, authority, alias and remarks are ignored in the comparison. /// </summary> /// <param name="obj"></param> /// <returns>True if equal</returns> // ********************************************************************** // public bool EqualParams(object obj) { if (!(obj is AbstractMapProjection)) return false; AbstractMapProjection proj = obj as AbstractMapProjection; if (proj.NumParameters != this.NumParameters) return false; for (int i = 0; i < m_Parameters.Count; i++) { ProjectionParameter param = m_Parameters.Find(delegate(ProjectionParameter par) { return par.Name.Equals(proj.GetParameter(i).Name, StringComparison.OrdinalIgnoreCase); }); if (param == null) return false; if (param.Value != proj.GetParameter(i).Value) return false; } if (this.IsInverse != proj.IsInverse) return false; return true; } // // ********************************************************************** /// <summary> /// Returns the cube of a number. /// </summary> /// <param name="x">The x.</param> /// <returns></returns> // ********************************************************************** // protected static double CUBE(double x) { return Math.Pow(x, 3); /* x^3 */ } // // ********************************************************************** /// <summary> /// Returns the quad of a number. /// </summary> /// <param name="x">The x.</param> /// <returns></returns> // ********************************************************************** // protected static double QUAD(double x) { return Math.Pow(x, 4); /* x^4 */ } // // ********************************************************************** /// <summary> /// GMAXs the specified A. /// </summary> /// <param name="A">The A.</param> /// <param name="B">The B.</param> /// <returns></returns> // ********************************************************************** // protected static double GMAX(ref double A, ref double B) { return Math.Max(A, B); /* assign maximum of a and b */ } // // ********************************************************************** /// <summary> /// GMINs the specified A. /// </summary> /// <param name="A">The A.</param> /// <param name="B">The B.</param> /// <returns></returns> // ********************************************************************** // protected static double GMIN(ref double A, ref double B) { return ((A) < (B) ? (A) : (B)); /* assign minimum of a and b */ } // // ********************************************************************** /// <summary> /// IMODs the specified A. /// </summary> /// <param name="A">The A.</param> /// <param name="B">The B.</param> /// <returns></returns> // ********************************************************************** // protected static double IMOD(double A, double B) { return (A) - (((A) / (B)) * (B)); /* Integer mod function */ } // // ********************************************************************** /// <summary> /// Function to return the sign of an argument /// </summary> /// <param name="x">The x.</param> /// <returns></returns> // ********************************************************************** // protected static double sign(double x) { if (x < 0.0) return (-1); else return (1); } // // ********************************************************************** /// <summary> /// Adjust_lons the specified x. /// </summary> /// <param name="x">The x.</param> /// <returns></returns> // ********************************************************************** // protected static double adjust_lon(double x) { long count = 0; for (;;) { if (Math.Abs(x) <= PI) break; else if (((long)Math.Abs(x / Math.PI)) < 2) x = x - (sign(x) * TWO_PI); else if (((long)Math.Abs(x / TWO_PI)) < prjMAXLONG) { x = x - (((long)(x / TWO_PI)) * TWO_PI); } else if (((long)Math.Abs(x / (prjMAXLONG * TWO_PI))) < prjMAXLONG) { x = x - (((long)(x / (prjMAXLONG * TWO_PI))) * (TWO_PI * prjMAXLONG)); } else if (((long)Math.Abs(x / (DBLLONG * TWO_PI))) < prjMAXLONG) { x = x - (((long)(x / (DBLLONG * TWO_PI))) * (TWO_PI * DBLLONG)); } else x = x - (sign(x) * TWO_PI); count++; if (count > MAX_VAL) break; } return (x); } // // ********************************************************************** /// <summary> /// Function to compute the constant small m which is the radius of /// a parallel of latitude, phi, divided by the semimajor axis. /// </summary> /// <param name="eccent">The eccent.</param> /// <param name="sinphi">The sinphi.</param> /// <param name="cosphi">The cosphi.</param> /// <returns></returns> // ********************************************************************** // protected static double msfnz(double eccent, double sinphi, double cosphi) { double con; con = eccent * sinphi; return ((cosphi / (Math.Sqrt(1.0 - con * con)))); } // // ********************************************************************** /// <summary> /// Function to compute constant small q which is the radius of a /// parallel of latitude, phi, divided by the semimajor axis. /// </summary> /// <param name="eccent">The eccent.</param> /// <param name="sinphi">The sinphi.</param> /// <param name="cosphi">The cosphi.</param> /// <returns></returns> // ********************************************************************** // protected static double qsfnz(double eccent, double sinphi, double cosphi) { double con; if (eccent > 1.0e-7) { con = eccent * sinphi; return ((1.0 - eccent * eccent) * (sinphi / (1.0 - con * con) - (.5 / eccent) * Math.Log((1.0 - con) / (1.0 + con)))); } else return (2.0 * sinphi); } // // ********************************************************************** /// <summary> /// Function to calculate the sine and cosine in one call. Some computer /// systems have implemented this function, resulting in a faster implementation /// than calling each function separately. It is provided here for those /// computer systems which don`t implement this function /// </summary> /// <param name="val">The val.</param> /// <param name="sin_val">The sin_val.</param> /// <param name="cos_val">The cos_val.</param> // ********************************************************************** // protected static void sincos(double val, out double sin_val, out double cos_val) { sin_val = Math.Sin(val); cos_val = Math.Cos(val); } // // ********************************************************************** /// <summary> /// Function to compute the constant small t for use in the forward /// computations in the Lambert Conformal Conic and the Polar /// Stereographic projections. /// </summary> /// <param name="eccent">The eccent.</param> /// <param name="phi">The phi.</param> /// <param name="sinphi">The sinphi.</param> /// <returns></returns> // ********************************************************************** // protected static double tsfnz(double eccent, double phi, double sinphi) { double con; double com; con = eccent * sinphi; com = .5 * eccent; con = Math.Pow(((1.0 - con) / (1.0 + con)), com); return (Math.Tan(.5 * (HALF_PI - phi)) / con); } // // ********************************************************************** /// <summary> /// Phi1zs the specified eccent. /// </summary> /// <param name="eccent">The eccent.</param> /// <param name="qs">The qs.</param> /// <param name="flag">The flag.</param> /// <returns></returns> // ********************************************************************** // protected static double phi1z(double eccent, double qs, out long flag) { double eccnts; double dphi; double con; double com; double sinpi; double cospi; double phi; flag = 0; long i; phi = asinz(.5 * qs); if (eccent < EPSLN) return (phi); eccnts = eccent * eccent; for (i = 1; i <= 25; i++) { sincos(phi, out sinpi, out cospi); con = eccent * sinpi; com = 1.0 - con * con; dphi = .5 * com * com / cospi * (qs / (1.0 - eccnts) - sinpi / com + .5 / eccent * Math.Log((1.0 - con) / (1.0 + con))); phi = phi + dphi; if (Math.Abs(dphi) <= 1e-7) return (phi); } throw new ApplicationException("Convergence error."); } // // ********************************************************************** /// <summary> /// Function to eliminate roundoff errors in asin /// </summary> /// <param name="con">The con.</param> /// <returns></returns> // ********************************************************************** // protected static double asinz(double con) { if (Math.Abs(con) > 1.0) { if (con > 1.0) con = 1.0; else con = -1.0; } return (Math.Asin(con)); } // // ********************************************************************** /// <summary> /// Function to compute the latitude angle, phi2, for the inverse of the /// Lambert Conformal Conic and Polar Stereographic projections. /// </summary> /// <param name="eccent">The eccent.</param> /// <param name="ts">The ts.</param> /// <param name="flag">The flag.</param> /// <returns></returns> // ********************************************************************** // protected static double phi2z(double eccent, double ts, out long flag) { double con; double dphi; double sinpi; long i; flag = 0; double eccnth = .5 * eccent; double chi = HALF_PI - 2 * Math.Atan(ts); for (i = 0; i <= 15; i++) { sinpi = Math.Sin(chi); con = eccent * sinpi; dphi = HALF_PI - 2 * Math.Atan(ts * (Math.Pow(((1.0 - con) / (1.0 + con)), eccnth))) - chi; chi += dphi; if (Math.Abs(dphi) <= .0000000001) return (chi); } throw new ApplicationException("Convergence error - phi2z-conv"); } // // ********************************************************************** /// <summary> /// Functions to compute the constants e0, e1, e2, and e3 which are used /// in a series for calculating the distance along a meridian. The /// input x represents the eccentricity squared. /// </summary> /// <param name="x">The x.</param> /// <returns></returns> // ********************************************************************** // protected static double e0fn(double x) { return (1.0 - 0.25 * x * (1.0 + x / 16.0 * (3.0 + 1.25 * x))); } // // ********************************************************************** /// <summary> /// E1fns the specified x. /// </summary> /// <param name="x">The x.</param> /// <returns></returns> // ********************************************************************** // protected static double e1fn(double x) { return (0.375 * x * (1.0 + 0.25 * x * (1.0 + 0.46875 * x))); } // // ********************************************************************** /// <summary> /// E2fns the specified x. /// </summary> /// <param name="x">The x.</param> /// <returns></returns> // ********************************************************************** // protected static double e2fn(double x) { return (0.05859375 * x * x * (1.0 + 0.75 * x)); } // // ********************************************************************** /// <summary> /// E3fns the specified x. /// </summary> /// <param name="x">The x.</param> /// <returns></returns> // ********************************************************************** // protected static double e3fn(double x) { return (x * x * x * (35.0 / 3072.0)); } // // ********************************************************************** /// <summary> /// Function to compute the constant e4 from the input of the eccentricity /// of the spheroid, x. This constant is used in the Polar Stereographic /// projection. /// </summary> /// <param name="x">The x.</param> /// <returns></returns> // ********************************************************************** // protected static double e4fn(double x) { double con; double com; con = 1.0 + x; com = 1.0 - x; return (Math.Sqrt((Math.Pow(con, con)) * (Math.Pow(com, com)))); } // // ********************************************************************** /// <summary> /// Function computes the value of M which is the distance along a meridian /// from the Equator to latitude phi. /// </summary> /// <param name="e0">The e0.</param> /// <param name="e1">The e1.</param> /// <param name="e2">The e2.</param> /// <param name="e3">The e3.</param> /// <param name="phi">The phi.</param> /// <returns></returns> // ********************************************************************** // protected static double mlfn(double e0, double e1, double e2, double e3, double phi) { return (e0 * phi - e1 * Math.Sin(2.0 * phi) + e2 * Math.Sin(4.0 * phi) - e3 * Math.Sin(6.0 * phi)); } // // ********************************************************************** /// <summary> /// Function to calculate UTM zone number--NOTE Longitude entered in DEGREES!!! /// </summary> /// <param name="lon">The lon.</param> /// <returns></returns> // ********************************************************************** // protected static long calc_utm_zone(double lon) { return ((long)(((lon + 180.0) / 6.0) + 1.0)); } #endregion #region Static Methods; // // ********************************************************************** /// <summary> /// Converts a longitude value in degrees to radians. /// </summary> /// <param name="x">The value in degrees to convert to radians.</param> /// <param name="edge">If true, -180 and +180 are valid, otherwise they are considered out of range.</param> /// <returns></returns> // ********************************************************************** // static protected double LongitudeToRadians(double x, bool edge) { if (edge ? (x >= -180 && x <= 180) : (x > -180 && x < 180)) { return Degrees2Radians(x); } throw new ArgumentOutOfRangeException("x", x, " not a valid longitude in degrees."); } // // ********************************************************************** /// <summary> /// Converts a latitude value in degrees to radians. /// </summary> /// <param name="y">The value in degrees to to radians.</param> /// <param name="edge">If true, -90 and +90 are valid, otherwise they are considered out of range.</param> /// <returns></returns> // ********************************************************************** // static protected double LatitudeToRadians(double y, bool edge) { if (edge ? (y >= -90 && y <= 90) : (y > -90 && y < 90)) { return Degrees2Radians(y); } throw new ArgumentOutOfRangeException("x", y, " not a valid latitude in degrees."); } #endregion } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Text; using System.Diagnostics; namespace System.Xml { internal class UTF16Decoder : System.Text.Decoder { private bool _bigEndian; private int _lastByte; private const int CharSize = 2; public UTF16Decoder(bool bigEndian) { _lastByte = -1; _bigEndian = bigEndian; } public override int GetCharCount(byte[] bytes, int index, int count) { return GetCharCount(bytes, index, count, false); } public override int GetCharCount(byte[] bytes, int index, int count, bool flush) { int byteCount = count + ((_lastByte >= 0) ? 1 : 0); if (flush && (byteCount % CharSize != 0)) { throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, -1), (string)null); } return byteCount / CharSize; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { int charCount = GetCharCount(bytes, byteIndex, byteCount); if (_lastByte >= 0) { if (byteCount == 0) { return charCount; } int nextByte = bytes[byteIndex++]; byteCount--; chars[charIndex++] = _bigEndian ? (char)(_lastByte << 8 | nextByte) : (char)(nextByte << 8 | _lastByte); _lastByte = -1; } if ((byteCount & 1) != 0) { _lastByte = bytes[byteIndex + --byteCount]; } // use the fast BlockCopy if possible if (_bigEndian == BitConverter.IsLittleEndian) { int byteEnd = byteIndex + byteCount; if (_bigEndian) { while (byteIndex < byteEnd) { int hi = bytes[byteIndex++]; int lo = bytes[byteIndex++]; chars[charIndex++] = (char)(hi << 8 | lo); } } else { while (byteIndex < byteEnd) { int lo = bytes[byteIndex++]; int hi = bytes[byteIndex++]; chars[charIndex++] = (char)(hi << 8 | lo); } } } else { Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, byteCount); } return charCount; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { charsUsed = 0; bytesUsed = 0; if (_lastByte >= 0) { if (byteCount == 0) { completed = true; return; } int nextByte = bytes[byteIndex++]; byteCount--; bytesUsed++; chars[charIndex++] = _bigEndian ? (char)(_lastByte << 8 | nextByte) : (char)(nextByte << 8 | _lastByte); charCount--; charsUsed++; _lastByte = -1; } if (charCount * CharSize < byteCount) { byteCount = charCount * CharSize; completed = false; } else { completed = true; } if (_bigEndian == BitConverter.IsLittleEndian) { int i = byteIndex; int byteEnd = i + (byteCount & ~0x1); if (_bigEndian) { while (i < byteEnd) { int hi = bytes[i++]; int lo = bytes[i++]; chars[charIndex++] = (char)(hi << 8 | lo); } } else { while (i < byteEnd) { int lo = bytes[i++]; int hi = bytes[i++]; chars[charIndex++] = (char)(hi << 8 | lo); } } } else { Buffer.BlockCopy(bytes, byteIndex, chars, charIndex * CharSize, (int)(byteCount & ~0x1)); } charsUsed += byteCount / CharSize; bytesUsed += byteCount; if ((byteCount & 1) != 0) { _lastByte = bytes[byteIndex + byteCount - 1]; } } } internal class SafeAsciiDecoder : Decoder { public SafeAsciiDecoder() { } public override int GetCharCount(byte[] bytes, int index, int count) { return count; } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { int i = byteIndex; int j = charIndex; while (i < byteIndex + byteCount) { chars[j++] = (char)bytes[i++]; } return byteCount; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { if (charCount < byteCount) { byteCount = charCount; completed = false; } else { completed = true; } int i = byteIndex; int j = charIndex; int byteEndIndex = byteIndex + byteCount; while (i < byteEndIndex) { chars[j++] = (char)bytes[i++]; } charsUsed = byteCount; bytesUsed = byteCount; } } internal class Ucs4Encoding : Encoding { internal Ucs4Decoder ucs4Decoder; public override string WebName { get { return this.EncodingName; } } public override Decoder GetDecoder() { return ucs4Decoder; } public override int GetByteCount(char[] chars, int index, int count) { return checked(count * 4); } public override int GetByteCount(char[] chars) { return chars.Length * 4; } public override byte[] GetBytes(string s) { return null; //ucs4Decoder.GetByteCount(chars, index, count); } public override int GetBytes(char[] chars, int charIndex, int charCount, byte[] bytes, int byteIndex) { return 0; } public override int GetMaxByteCount(int charCount) { return 0; } public override int GetCharCount(byte[] bytes, int index, int count) { return ucs4Decoder.GetCharCount(bytes, index, count); } public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { return ucs4Decoder.GetChars(bytes, byteIndex, byteCount, chars, charIndex); } public override int GetMaxCharCount(int byteCount) { return (byteCount + 3) / 4; } public override int CodePage { get { return 0; } } public override int GetCharCount(byte[] bytes) { return bytes.Length / 4; } public override Encoder GetEncoder() { return null; } internal static Encoding UCS4_Littleendian { get { return new Ucs4Encoding4321(); } } internal static Encoding UCS4_Bigendian { get { return new Ucs4Encoding1234(); } } internal static Encoding UCS4_2143 { get { return new Ucs4Encoding2143(); } } internal static Encoding UCS4_3412 { get { return new Ucs4Encoding3412(); } } } internal sealed class Ucs4Encoding1234 : Ucs4Encoding { private static readonly byte[] s_preamble = new byte[4] { 0x00, 0x00, 0xfe, 0xff }; public Ucs4Encoding1234() { ucs4Decoder = new Ucs4Decoder1234(); } public override string EncodingName { get { return "ucs-4 (Bigendian)"; } } public override byte[] GetPreamble() { return new byte[4] { 0x00, 0x00, 0xfe, 0xff }; } public override ReadOnlySpan<byte> Preamble => s_preamble; } internal sealed class Ucs4Encoding4321 : Ucs4Encoding { private static readonly byte[] s_preamble = new byte[4] { 0xff, 0xfe, 0x00, 0x00 }; public Ucs4Encoding4321() { ucs4Decoder = new Ucs4Decoder4321(); } public override string EncodingName { get { return "ucs-4"; } } public override byte[] GetPreamble() { return new byte[4] { 0xff, 0xfe, 0x00, 0x00 }; } public override ReadOnlySpan<byte> Preamble => s_preamble; } internal sealed class Ucs4Encoding2143 : Ucs4Encoding { private static readonly byte[] s_preamble = new byte[4] { 0x00, 0x00, 0xff, 0xfe }; public Ucs4Encoding2143() { ucs4Decoder = new Ucs4Decoder2143(); } public override string EncodingName { get { return "ucs-4 (order 2143)"; } } public override byte[] GetPreamble() { return new byte[4] { 0x00, 0x00, 0xff, 0xfe }; } public override ReadOnlySpan<byte> Preamble => s_preamble; } internal sealed class Ucs4Encoding3412 : Ucs4Encoding { private static readonly byte[] s_preamble = new byte[4] { 0xfe, 0xff, 0x00, 0x00 }; public Ucs4Encoding3412() { ucs4Decoder = new Ucs4Decoder3412(); } public override string EncodingName { get { return "ucs-4 (order 3412)"; } } public override byte[] GetPreamble() { return new byte[4] { 0xfe, 0xff, 0x00, 0x00 }; } public override ReadOnlySpan<byte> Preamble => s_preamble; } internal abstract class Ucs4Decoder : Decoder { internal byte[] lastBytes = new byte[4]; internal int lastBytesCount = 0; public override int GetCharCount(byte[] bytes, int index, int count) { return (count + lastBytesCount) / 4; } internal abstract int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex); public override int GetChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { // finish a character from the bytes that were cached last time int i = lastBytesCount; if (lastBytesCount > 0) { // copy remaining bytes into the cache for (; lastBytesCount < 4 && byteCount > 0; lastBytesCount++) { lastBytes[lastBytesCount] = bytes[byteIndex]; byteIndex++; byteCount--; } // still not enough bytes -> return if (lastBytesCount < 4) { return 0; } // decode 1 character from the byte cache i = GetFullChars(lastBytes, 0, 4, chars, charIndex); Debug.Assert(i == 1); charIndex += i; lastBytesCount = 0; } else { i = 0; } // decode block of byte quadruplets i = GetFullChars(bytes, byteIndex, byteCount, chars, charIndex) + i; // cache remaining bytes that does not make up a character int bytesLeft = (byteCount & 0x3); if (bytesLeft >= 0) { for (int j = 0; j < bytesLeft; j++) { lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j]; } lastBytesCount = bytesLeft; } return i; } public override void Convert(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex, int charCount, bool flush, out int bytesUsed, out int charsUsed, out bool completed) { bytesUsed = 0; charsUsed = 0; // finish a character from the bytes that were cached last time int i = 0; int lbc = lastBytesCount; if (lbc > 0) { // copy remaining bytes into the cache for (; lbc < 4 && byteCount > 0; lbc++) { lastBytes[lbc] = bytes[byteIndex]; byteIndex++; byteCount--; bytesUsed++; } // still not enough bytes -> return if (lbc < 4) { lastBytesCount = lbc; completed = true; return; } // decode 1 character from the byte cache i = GetFullChars(lastBytes, 0, 4, chars, charIndex); charIndex += i; charCount -= i; charsUsed = i; lastBytesCount = 0; } else { i = 0; } // modify the byte count for GetFullChars depending on how many characters were requested if (charCount * 4 < byteCount) { byteCount = charCount * 4; completed = false; } else { completed = true; } bytesUsed += byteCount; // decode block of byte quadruplets charsUsed = GetFullChars(bytes, byteIndex, byteCount, chars, charIndex) + i; // cache remaining bytes that does not make up a character int bytesLeft = (byteCount & 0x3); if (bytesLeft >= 0) { for (int j = 0; j < bytesLeft; j++) { lastBytes[j] = bytes[byteIndex + byteCount - bytesLeft + j]; } lastBytesCount = bytesLeft; } } internal void Ucs4ToUTF16(uint code, char[] chars, int charIndex) { chars[charIndex] = (char)(XmlCharType.SurHighStart + (char)((code >> 16) - 1) + (char)((code >> 10) & 0x3F)); chars[charIndex + 1] = (char)(XmlCharType.SurLowStart + (char)(code & 0x3FF)); } } internal class Ucs4Decoder4321 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i + 3] << 24) | (bytes[i + 2] << 16) | (bytes[i + 1] << 8) | bytes[i]); if (code > 0x10FFFF) { throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } }; internal class Ucs4Decoder1234 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i] << 24) | (bytes[i + 1] << 16) | (bytes[i + 2] << 8) | bytes[i + 3]); if (code > 0x10FFFF) { throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } } internal class Ucs4Decoder2143 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i + 1] << 24) | (bytes[i] << 16) | (bytes[i + 3] << 8) | bytes[i + 2]); if (code > 0x10FFFF) { throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } } internal class Ucs4Decoder3412 : Ucs4Decoder { internal override int GetFullChars(byte[] bytes, int byteIndex, int byteCount, char[] chars, int charIndex) { uint code; int i, j; byteCount += byteIndex; for (i = byteIndex, j = charIndex; i + 3 < byteCount;) { code = (uint)((bytes[i + 2] << 24) | (bytes[i + 3] << 16) | (bytes[i] << 8) | bytes[i + 1]); if (code > 0x10FFFF) { throw new ArgumentException(SR.Format(SR.Enc_InvalidByteInEncoding, new object[1] { i }), (string)null); } else if (code > 0xFFFF) { Ucs4ToUTF16(code, chars, j); j++; } else { if (XmlCharType.IsSurrogate((int)code)) { throw new XmlException(SR.Xml_InvalidCharInThisEncoding, string.Empty); } else { chars[j] = (char)code; } } j++; i += 4; } return j - charIndex; } } }
// SNMP INTEGER type. // Copyright (C) 2008-2010 Malcolm Crowe, Lex Li, and other contributors. // // Permission is hereby granted, free of charge, to any person obtaining a copy of this // software and associated documentation files (the "Software"), to deal in the Software // without restriction, including without limitation the rights to use, copy, modify, merge, // publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons // to whom the Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all copies or // substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, // INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR // PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE // FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR // OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. using System; using System.Globalization; using System.IO; // ASN.1 BER encoding library by Malcolm Crowe at the University of the West of Scotland // See http://cis.paisley.ac.uk/crow-ci0 // This is version 0 of the library, please advise me about any bugs // mailto:malcolm.crowe@paisley.ac.uk // Restrictions: It is assumed that no encoding has index length greater than 2^31-1. // UNIVERSAL TYPES // Some of the more unusual Universal encodings are supported but not fully implemented // Should you require these types, as an alternative to changing this code // you can catch the exception that is thrown and examine the contents yourself. // APPLICATION TYPES // If you want to handle Application types systematically, you can derive index class from // Universal, and provide the Creator and Creators methods for your class // You will see an example of how to do this in the Snmplib // CONTEXT AND PRIVATE TYPES // Ad hoc coding can be used for these, as an alterative to derive index class as above. namespace GSF.Net.Snmp { /// <summary> /// Integer32 type in SMIv2 (or INTEGER in SMIv1). /// </summary> public sealed class Integer32 // This namespace has its own concept of Integer : ISnmpData, IEquatable<Integer32> { private readonly int _int; private readonly byte[] _length; /// <summary> /// Zero. /// </summary> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Security", "CA2104:DoNotDeclareReadOnlyMutableReferenceTypes")] public static readonly Integer32 Zero = new Integer32(0); private byte[] _raw; /// <summary> /// Creates an <see cref="Integer32"/> instance. /// </summary> /// <param name="raw">Raw bytes</param> internal Integer32(byte[] raw) : this(new Tuple<int, byte[]>(raw.Length, raw.Length.WritePayloadLength()), new MemoryStream(raw)) { // IMPORTANT: for test project only. } /// <summary> /// Creates an <see cref="Integer32"/> instance with a specific <see cref="Int32"/>. /// </summary> /// <param name="value">Value</param> public Integer32(int value) { _int = value; } /// <summary> /// Initializes a new instance of the <see cref="Integer32"/> class. /// </summary> /// <param name="length">The length.</param> /// <param name="stream">The stream.</param> public Integer32(Tuple<int, byte[]> length, Stream stream) { if (length == null) { throw new ArgumentNullException(nameof(length)); } if (stream == null) { throw new ArgumentNullException(nameof(stream)); } if (length.Item1 <= 0) { throw new ArgumentException("Byte length cannot be 0.", nameof(length)); } if (length.Item1 > 4) { throw new ArgumentException("Truncation error for 32-bit integer coding.", nameof(length)); } _raw = new byte[length.Item1]; stream.Read(_raw, 0, length.Item1); _int = ((_raw[0] & 0x80) == 0x80) ? -1 : 0; // sign extended! Guy McIlroy for (int j = 0; j < length.Item1; j++) { _int = (_int << 8) | _raw[j]; } _length = length.Item2; } /// <summary> /// Returns an <see cref="Int32"/> that represents this <see cref="Integer32"/>. /// </summary> /// <returns></returns> public int ToInt32() { return _int; } /// <summary> /// Converts to <see cref="ErrorCode"/>. /// </summary> /// <returns></returns> public ErrorCode ToErrorCode() { if (_int > 19 || _int < 0) { throw new InvalidCastException(); } return (ErrorCode)_int; } /// <summary> /// Returns a <see cref="String"/> that represents this <see cref="Integer32"/>. /// </summary> /// <returns></returns> public override string ToString() { return _int.ToString(CultureInfo.InvariantCulture); } /// <summary> /// Type code. /// </summary> public SnmpType TypeCode { get { return SnmpType.Integer32; } } /// <summary> /// Appends the bytes to <see cref="Stream"/>. /// </summary> /// <param name="stream">The stream.</param> public void AppendBytesTo(Stream stream) { if (stream == null) { throw new ArgumentNullException(nameof(stream)); } stream.AppendBytes(TypeCode, _length, _raw ?? (_raw = ByteTool.GetRawBytes(BitConverter.GetBytes(_int), _int < 0))); } /// <summary> /// Serves as a hash function for a particular type. /// </summary> /// <returns>A hash code for the current <see cref="Integer32"/>.</returns> public override int GetHashCode() { return ToInt32().GetHashCode(); } /// <summary> /// Determines whether the specified <see cref="Object"/> is equal to the current <see cref="Integer32"/>. /// </summary> /// <param name="obj">The <see cref="Object"/> to compare with the current <see cref="Integer32"/>. </param> /// <returns><value>true</value> if the specified <see cref="Object"/> is equal to the current <see cref="Integer32"/>; otherwise, <value>false</value>. /// </returns> public override bool Equals(object obj) { return Equals(this, obj as Integer32); } /// <summary> /// Indicates whether the current object is equal to another object of the same type. /// </summary> /// <param name="other">An object to compare with this object.</param> /// <returns><value>true</value> if the current object is equal to the <paramref name="other"/> parameter; otherwise, <value>false</value>. /// </returns> public bool Equals(Integer32 other) { return Equals(this, other); } /// <summary> /// The equality operator. /// </summary> /// <param name="left">Left <see cref="Integer32"/> object</param> /// <param name="right">Right <see cref="Integer32"/> object</param> /// <returns> /// Returns <c>true</c> if the values of its operands are equal, <c>false</c> otherwise.</returns> public static bool operator ==(Integer32 left, Integer32 right) { return Equals(left, right); } /// <summary> /// The inequality operator. /// </summary> /// <param name="left">Left <see cref="Integer32"/> object</param> /// <param name="right">Right <see cref="Integer32"/> object</param> /// <returns> /// Returns <c>true</c> if the values of its operands are not equal, <c>false</c> otherwise.</returns> public static bool operator !=(Integer32 left, Integer32 right) { return !(left == right); } /// <summary> /// The comparison. /// </summary> /// <param name="left">Left <see cref="Integer32"/> object</param> /// <param name="right">Right <see cref="Integer32"/> object</param> /// <returns> /// Returns <c>true</c> if the values of its operands are not equal, <c>false</c> otherwise.</returns> private static bool Equals(Integer32 left, Integer32 right) { object lo = left; object ro = right; if (lo == ro) { return true; } if (lo == null || ro == null) { return false; } return left.ToInt32() == right.ToInt32(); } } // all references here are to ITU-X.690-12/97 }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator 0.16.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Internal.Resources { using System; using System.Linq; using System.Collections.Generic; using System.Diagnostics; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure; using Models; /// <summary> /// Azure resources can be linked together to form logical relationships. /// You can establish links between resources belonging to different /// resource groups. However, all the linked resources must belong to the /// same subscription. Each resource can be linked to 50 other resources. /// If any of the linked resources are deleted or moved, the link owner /// must clean up the remaining link. /// </summary> public partial class ManagementLinkClient : ServiceClient<ManagementLinkClient>, IManagementLinkClient, IAzureClient { /// <summary> /// The base URI of the service. /// </summary> public Uri BaseUri { get; set; } /// <summary> /// Gets or sets json serialization settings. /// </summary> public JsonSerializerSettings SerializationSettings { get; private set; } /// <summary> /// Gets or sets json deserialization settings. /// </summary> public JsonSerializerSettings DeserializationSettings { get; private set; } /// <summary> /// Gets Azure subscription credentials. /// </summary> public ServiceClientCredentials Credentials { get; private set; } /// <summary> /// The ID of the target subscription. /// </summary> public string SubscriptionId { get; set; } /// <summary> /// The API version to use for the operation. /// </summary> public string ApiVersion { get; private set; } /// <summary> /// Gets or sets the preferred language for the response. /// </summary> public string AcceptLanguage { get; set; } /// <summary> /// Gets or sets the retry timeout in seconds for Long Running Operations. /// Default value is 30. /// </summary> public int? LongRunningOperationRetryTimeout { get; set; } /// <summary> /// When set to true a unique x-ms-client-request-id value is generated and /// included in each request. Default is true. /// </summary> public bool? GenerateClientRequestId { get; set; } /// <summary> /// Gets the IResourceLinksOperations. /// </summary> public virtual IResourceLinksOperations ResourceLinks { get; private set; } /// <summary> /// Initializes a new instance of the ManagementLinkClient class. /// </summary> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ManagementLinkClient(params DelegatingHandler[] handlers) : base(handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the ManagementLinkClient class. /// </summary> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ManagementLinkClient(HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : base(rootHandler, handlers) { this.Initialize(); } /// <summary> /// Initializes a new instance of the ManagementLinkClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ManagementLinkClient(Uri baseUri, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the ManagementLinkClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> protected ManagementLinkClient(Uri baseUri, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } this.BaseUri = baseUri; } /// <summary> /// Initializes a new instance of the ManagementLinkClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public ManagementLinkClient(ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ManagementLinkClient class. /// </summary> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public ManagementLinkClient(ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (credentials == null) { throw new ArgumentNullException("credentials"); } this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ManagementLinkClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public ManagementLinkClient(Uri baseUri, ServiceClientCredentials credentials, params DelegatingHandler[] handlers) : this(handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes a new instance of the ManagementLinkClient class. /// </summary> /// <param name='baseUri'> /// Optional. The base URI of the service. /// </param> /// <param name='credentials'> /// Required. Gets Azure subscription credentials. /// </param> /// <param name='rootHandler'> /// Optional. The http client handler used to handle http transport. /// </param> /// <param name='handlers'> /// Optional. The delegating handlers to add to the http client pipeline. /// </param> public ManagementLinkClient(Uri baseUri, ServiceClientCredentials credentials, HttpClientHandler rootHandler, params DelegatingHandler[] handlers) : this(rootHandler, handlers) { if (baseUri == null) { throw new ArgumentNullException("baseUri"); } if (credentials == null) { throw new ArgumentNullException("credentials"); } this.BaseUri = baseUri; this.Credentials = credentials; if (this.Credentials != null) { this.Credentials.InitializeServiceClient(this); } } /// <summary> /// Initializes client properties. /// </summary> private void Initialize() { this.ResourceLinks = new ResourceLinksOperations(this); this.BaseUri = new Uri("https://management.azure.com"); this.ApiVersion = "2016-09-01"; this.AcceptLanguage = "en-US"; this.LongRunningOperationRetryTimeout = 30; this.GenerateClientRequestId = true; SerializationSettings = new JsonSerializerSettings { Formatting = Formatting.Indented, DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings = new JsonSerializerSettings { DateFormatHandling = DateFormatHandling.IsoDateFormat, DateTimeZoneHandling = DateTimeZoneHandling.Utc, NullValueHandling = NullValueHandling.Ignore, ReferenceLoopHandling = ReferenceLoopHandling.Serialize, ContractResolver = new ReadOnlyJsonContractResolver(), Converters = new List<JsonConverter> { new Iso8601TimeSpanConverter() } }; DeserializationSettings.Converters.Add(new CloudErrorJsonConverter()); } } }
// Copyright 2019 DeepMind Technologies Limited // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Xml; using NUnit.Framework; using UnityEngine; using UnityEngine.TestTools; namespace Mujoco { [TestFixture] public class MjcfImporterTests { private GameObject _sceneRoot; private MjcfImporter _importer; [SetUp] public void SetUp() { _importer = new MjcfImporter(); } [TearDown] public void TearDown() { if (_sceneRoot != null) { UnityEngine.Object.DestroyImmediate(_sceneRoot); } } [Test] public void SceneRootIsGivenRequestedName() { var rootName = "rootName"; var mjcfString = "<mujoco><worldbody/></mujoco>"; _sceneRoot = _importer.ImportString(name: rootName, mjcfString: mjcfString); Assert.That(_sceneRoot.name, Is.EqualTo(rootName)); } [Test] public void ParsingAGeom() { var mjcfString = @"<mujoco> <worldbody> <geom size='1'/> </worldbody> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); Assert.That(_sceneRoot.transform.childCount, Is.EqualTo(1)); var geomChild = _sceneRoot.transform.GetChild(0).gameObject; Assert.That(geomChild, Is.Not.Null); Assert.That(geomChild.GetComponent<MjGeom>(), Is.Not.Null); } [TestCase("hinge", typeof(MjHingeJoint))] [TestCase("slide", typeof(MjSlideJoint))] [TestCase("free", typeof(MjFreeJoint))] public void ParsingJoints(string typeId, Type jointType) { var mjcfString = string.Format(@"<mujoco> <worldbody> <body> <joint type=""{0}""/> <geom size='1'/> </body> </worldbody> </mujoco>", typeId); _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); Assert.That(_sceneRoot.transform.childCount, Is.EqualTo(1)); var bodyChild = _sceneRoot.transform.GetChild(0).gameObject; Assert.That(bodyChild.transform.childCount, Is.EqualTo(2)); var jointChild = bodyChild.transform.GetChild(0).gameObject; Assert.That(jointChild, Is.Not.Null); Assert.That(jointChild.GetComponent(jointType), Is.Not.Null); } [Test] public void ParsingAFreeJointStandaloneNode() { var mjcfString = @"<mujoco> <worldbody> <body> <freejoint/> <geom size='1'/> </body> </worldbody> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); Assert.That(_sceneRoot.transform.childCount, Is.EqualTo(1)); var bodyChild = _sceneRoot.transform.GetChild(0).gameObject; Assert.That(bodyChild.transform.childCount, Is.EqualTo(2)); var jointChild = bodyChild.transform.GetChild(0).gameObject; Assert.That(jointChild, Is.Not.Null); Assert.That(jointChild.GetComponent<MjFreeJoint>(), Is.Not.Null); } [Test] public void ParsingABody() { var mjcfString = @"<mujoco> <worldbody> <body/> </worldbody> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); Assert.That(_sceneRoot.transform.childCount, Is.EqualTo(1)); var bodyChild = _sceneRoot.transform.GetChild(0).gameObject; Assert.That(bodyChild, Is.Not.Null); Assert.That(bodyChild.GetComponent<MjBody>(), Is.Not.Null); } [Test] public void ParsingChildrenOfABody() { var mjcfString = @"<mujoco> <worldbody> <body> <geom size='1'/> <body/> <joint type=""hinge""/> </body> </worldbody> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); Assert.That(_sceneRoot.transform.childCount, Is.EqualTo(1)); var bodyChild = _sceneRoot.transform.GetChild(0).gameObject; Assert.That(bodyChild, Is.Not.Null); Assert.That(bodyChild.transform.childCount, Is.EqualTo(3)); } [Test] public void AnonymousNodeReceivesGeneratedName() { var mjcfString = @"<mujoco> <worldbody> <body/> </worldbody> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); var bodyChild = _sceneRoot.transform.GetChild(0).gameObject; Assert.That(bodyChild.name, Is.EqualTo("body_0")); } [Test] public void AnonymousNodesReceiveTheSameNamesWithEveryImport() { var mjcfString = @"<mujoco> <worldbody> <body/> </worldbody> </mujoco>"; var scenes = new GameObject[] { _importer.ImportString(name: string.Empty, mjcfString: mjcfString), _importer.ImportString(name: string.Empty, mjcfString: mjcfString) }; // Ensure that the objects will be destroyed after the test is completed. _sceneRoot = new GameObject(); foreach (var scene in scenes) { scene.transform.parent = _sceneRoot.transform; } var children = scenes.Select(parent => parent.transform.GetChild(0).gameObject).ToArray(); Assert.That(children[0].name, Is.EqualTo(children[1].name)); } [Test] public void ApplyingDefaultOutsideWorldbody() { var mjcfString = @"<mujoco> <default> <general ctrllimited='true' ctrlrange='-1 1'/> </default> <worldbody> <body> <geom name=""root_geom"" size='1 2'/> <joint name='j'/> </body> </worldbody> <actuator> <general joint='j'/> </actuator> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); var actuator = _sceneRoot.GetComponentInChildren<MjActuator>(); Assert.That(actuator.CommonParams.CtrlLimited, Is.True); } [Test] public void ApplyingDefaultSettingsToNodeWithoutClass() { var mjcfString = @"<mujoco> <default> <geom type=""cylinder""/> </default> <worldbody> <geom name=""root_geom"" size='1 2'/> </worldbody> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); var rootGeom = _sceneRoot.GetComponentInChildren<MjGeom>(); Assert.That(rootGeom.ShapeType, Is.EqualTo(MjShapeComponent.ShapeTypes.Cylinder)); } [Test] public void ApplyingHierarchicalDefaultSettingsToNodeWithClass() { var mjcfString = @"<mujoco> <default> <geom type=""cylinder""/> <default class=""child""> <geom type=""box""/> </default> </default> <worldbody> <body childclass=""child""> <geom name=""body_geom"" size='1 2 3'/> </body> </worldbody> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); var bodyGeom = _sceneRoot.GetComponentInChildren<MjGeom>(); Assert.That(bodyGeom.ShapeType, Is.EqualTo(MjShapeComponent.ShapeTypes.Box)); } [Test] public void ReadingOption() { var mjcfString = @"<mujoco> <option impratio='1.2345'/> <worldbody/> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); var settings = _sceneRoot.GetComponentInChildren<MjGlobalSettings>(); Assert.That(settings.GlobalOptions.ImpRatio, Is.EqualTo(1.2345f)); } [Test] public void ReadingSize() { var mjcfString = @"<mujoco> <size njmax='1234'/> <worldbody/> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); var settings = _sceneRoot.GetComponentInChildren<MjGlobalSettings>(); Assert.That(settings.GlobalSizes.Njmax, Is.EqualTo(1234)); } [Test] public void ReadingOptionAndSize() { var mjcfString = @"<mujoco> <option impratio='5.4321'/> <size njmax='4321'/> <worldbody/> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); var settings = _sceneRoot.GetComponentInChildren<MjGlobalSettings>(); Assert.That(settings.GlobalOptions.ImpRatio, Is.EqualTo(5.4321f)); Assert.That(settings.GlobalSizes.Njmax, Is.EqualTo(4321)); } [Test] public void ReadingOptionFlags() { var mjcfString = @"<mujoco> <option> <flag gravity='disable' contact='disable' sensornoise='enable'/> </option> <worldbody/> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); var settings = _sceneRoot.GetComponentInChildren<MjGlobalSettings>(); Assert.That(settings.GlobalOptions.Flag.Gravity, Is.EqualTo(EnableDisableFlag.disable)); Assert.That(settings.GlobalOptions.Flag.Contact, Is.EqualTo(EnableDisableFlag.disable)); Assert.That(settings.GlobalOptions.Flag.SensorNoise, Is.EqualTo(EnableDisableFlag.enable)); } [Test] public void ParsedActuatorsAddedToDedicatedGameObjectAggregate() { var mjcfString = @"<mujoco> <worldbody> <body> <geom size='1'/> <joint name='1'/> </body> </worldbody> <actuator> <motor joint='1'/> </actuator> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); var actuator = _sceneRoot.GetComponentInChildren<MjActuator>(); Assert.That(actuator, Is.Not.Null); Assert.That(actuator.transform.parent.gameObject.name, Is.EqualTo("actuators")); } [Test] public void ParsedSensorsAddedToDedicatedGameObjectAggregate() { var mjcfString = @"<mujoco> <worldbody> <body name='1'/> </worldbody> <sensor> <framepos objtype='body' objname='1'/> </sensor> </mujoco>"; _sceneRoot = _importer.ImportString( name: string.Empty, mjcfString: mjcfString); var sensor = _sceneRoot.GetComponentInChildren<MjBaseSensor>(); Assert.That(sensor, Is.Not.Null); Assert.That(sensor.transform.parent.gameObject.name, Is.EqualTo("sensors")); } [Test] public void NodeHandlerCalledForMatchingelements() { var mjcfString = @"<mujoco> <worldbody> <body> <CustomTestNode/> </body> </worldbody> </mujoco>"; var customImporter = new MjcfImporter(); bool ranCustomFunction = false; customImporter.AddNodeHandler("CustomTestNode", (element, o) => { ranCustomFunction = true; }); var mjcfXml = new XmlDocument(); mjcfXml.LoadXml(mjcfString); customImporter.ImportXml(mjcfXml); Assert.That(ranCustomFunction, Is.True); } } }
// 7d505858-0d9e-4dee-bd56-390198f95d43 #pragma warning disable 219 using System; using Neutrino.Unity3D; namespace Neutrino { public class Effect_Stream : NeutrinoRenderer { public class Model : EffectModel { public class Emitter_DefaultEmitter : EmitterModel { public class ParticleImpl : Particle { public float _lifetime; public float _Max_Life; public _math.vec3 _Position; public _math.vec3 _Velocity; public float _Angle; public _math.vec3 _Color; public float _Colora; public override _math.vec2 origin() { return _math.vec2_(0.5F,0.5F); } public override float angle() { return _Angle; } public override _math.quat rotation() { return _math.quat_(1, 0, 0, 0); } public float size1_; public override float size1() { return size1_; } public override _math.vec2 size2() { return _math.vec2_(0, 0); } public _math.vec3 color_; public override _math.vec3 color() { return color_; } public float alpha_; public override float alpha() { return alpha_; } public override float gridIndex() { return 0; } public override AttachedEmitter[] attachedEmitters() { return null; } } public class EmitterData { public _math.vec3 _Color1 = _math.vec3_(0F,0F,1F); public _math.vec3 _Color2 = _math.vec3_(0F,1F,1F); } public class GeneratorImpl : GeneratorPeriodic.Impl { public float burst() { return 1F; } public float? fixedTime() { return null; } public float? fixedShots() { return null; } public float startPhase() { return 1F; } public float rate() { return 100F; } } float [][][] _plot = { new float[][] { new float[]{ 0F,0.19159F,0.290298F,0.355081F,0.401548F,0.436788F,0.464891F,0.488638F,0.510213F,0.531602F,0.554907F,0.582751F,0.619006F,0.670675F,0.755057F,1F,1F }} }; _math.vec2 [][,] _path = { new _math.vec2[,] {{_math.vec2_(403F,43F)},{_math.vec2_(400F,-43F)},{_math.vec2_(400F,-43F)}} }; float [][][] _plota = { new float[][] { new float[]{ 1F,1F,1F }, new float[]{ 1F,0F,0F }} }; public class ConstructorImpl : ConstructorQuads.Impl { public ConstructorQuads.RotationType rotationType() { return ConstructorQuads.RotationType.Faced; } public ConstructorQuads.SizeType sizeType() { return ConstructorQuads.SizeType.Quad; } public ConstructorQuads.TexMapType texMapType() { return ConstructorQuads.TexMapType.WholeRect; } public _math.vec2 gridSize() { return _math.vec2_(0, 0); } public ushort renderStyleIndex() { return 0; } } public override void updateEmitter(Emitter emitter) { EmitterData emitterData = (EmitterData)emitter.data(); GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator(); GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl(); } public override void initParticle(Emitter emitter, Particle particle) { ParticleImpl particleImpl = (ParticleImpl)particle; float dt = 0; EmitterData emitterData = (EmitterData)emitter.data(); GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator(); GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl(); particleImpl._lifetime = 0F; float rnd_ = 1F + emitter.random()() * (3F - 1F); particleImpl._Max_Life = rnd_; _math.vec3 value_ = _math.vec3_(0F, 0F, 0F); particleImpl._Position = _math.addv3_(value_, emitter.position()); float rnd_a = 0F + emitter.random()() * (1F - 0F); float _plot_out; float _plot_in0=(rnd_a<0F?0F:(rnd_a>1F?1F:rnd_a)); _math.PathRes _plot_srch0 = _math.pathRes(0,(_plot_in0-0F)*15F); _math.funcLerp(out _plot_out, this._plot[0][_plot_srch0.s],_plot_srch0.i); float _path_in = _math.clamp_(_plot_out, 0, 1); _math.PathRes _path_srch = _math.pathRes(0,(_path_in-0F)*1F); _math.vec2 _path_pos; _math.pathLerp1(out _path_pos, this._path[_path_srch.s], _path_srch.i); _math.vec3 conv3d_ = _math.vec3_(_path_pos.x, _path_pos.y, 0F); particleImpl._Velocity = _math.applyv3quat_(conv3d_, emitter.rotation()); particleImpl._Velocity = _math.addv3_(particleImpl._Velocity, emitter.velocity()); particleImpl._Angle = 0F; particleImpl._Color = emitterData._Color1; float rnd_b = 0F + emitter.random()() * (1F - 0F); particleImpl._Colora = rnd_b; particle.position_ = particleImpl._Position; } public override void initBurstParticle(Emitter emitter, Particle particle) { ParticleImpl particleImpl = (ParticleImpl)particle; float dt = 0; EmitterData emitterData = (EmitterData)emitter.data(); GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator(); GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl(); particleImpl._lifetime = 0F; float rnd_ = 1F + emitter.random()() * (3F - 1F); particleImpl._Max_Life = rnd_; _math.vec3 value_ = _math.vec3_(0F, 0F, 0F); particleImpl._Position = _math.addv3_(value_, emitter.position()); float rnd_a = 0F + emitter.random()() * (1F - 0F); float _plot_out; float _plot_in0=(rnd_a<0F?0F:(rnd_a>1F?1F:rnd_a)); _math.PathRes _plot_srch0 = _math.pathRes(0,(_plot_in0-0F)*15F); _math.funcLerp(out _plot_out, this._plot[0][_plot_srch0.s],_plot_srch0.i); float _path_in = _math.clamp_(_plot_out, 0, 1); _math.PathRes _path_srch = _math.pathRes(0,(_path_in-0F)*1F); _math.vec2 _path_pos; _math.pathLerp1(out _path_pos, this._path[_path_srch.s], _path_srch.i); _math.vec3 conv3d_ = _math.vec3_(_path_pos.x, _path_pos.y, 0F); particleImpl._Velocity = _math.applyv3quat_(conv3d_, emitter.rotation()); particleImpl._Velocity = _math.addv3_(particleImpl._Velocity, emitter.velocity()); particleImpl._Angle = 0F; particleImpl._Color = emitterData._Color1; float rnd_b = 0F + emitter.random()() * (1F - 0F); particleImpl._Colora = rnd_b; particle.position_ = particleImpl._Position; } public override void updateParticle(Emitter emitter, Particle particle, float dt) { ParticleImpl particleImpl = (ParticleImpl)particle; EmitterData emitterData = (EmitterData)emitter.data(); GeneratorPeriodic generator = (GeneratorPeriodic)emitter.generator(); GeneratorImpl generatorImpl = (GeneratorImpl)generator.impl(); particleImpl._lifetime += dt; _math.vec3 value_ = _math.vec3_(0F, -100F, 0F); _math.vec3 fmove_fs = value_; _math.vec3 fmove_vs = _math.vec3_(0F,0F,0F); float fmove_dtl = dt; _math.vec3 fmove_v = particleImpl._Velocity; _math.vec3 fmove_p = particleImpl._Position; while (fmove_dtl > 0.0001F) { float fmove_dtp = fmove_dtl; _math.vec3 fmove_fsd = fmove_fs; _math.vec3 fmove_rw = _math.subv3_(fmove_vs, fmove_v); float fmove_rwl = _math.lengthv3sq_(fmove_rw); if (fmove_rwl > 0.0001F) { fmove_rwl = (float)Math.Sqrt(fmove_rwl); _math.vec3 fmove_rwn = _math.divv3scalar_(fmove_rw, fmove_rwl); float fmove_df = 0.01F * 0.3F * fmove_rwl; if (fmove_df * fmove_dtp > 0.2F) fmove_dtp = 0.2F / fmove_df; _math.addv3(out fmove_fsd, fmove_fsd, _math.mulv3scalar_(fmove_rwn, fmove_rwl * fmove_df)); } _math.addv3(out fmove_v, fmove_v, _math.mulv3scalar_(fmove_fsd, fmove_dtp)); _math.addv3(out fmove_p, fmove_p, _math.mulv3scalar_(fmove_v, fmove_dtp)); fmove_dtl -= fmove_dtp; } particleImpl._Position = fmove_p; particleImpl._Velocity = fmove_v; particle.position_ = particleImpl._Position; if (particleImpl._lifetime > particleImpl._Max_Life) { particle.dead_ = true; } float value_a = 30F; _math.vec3 expr_ = _math.addv3_(particleImpl._Color, _math.mulv3scalar_(_math.subv3_(emitterData._Color2, particleImpl._Color), particleImpl._Colora)); float expr_a = (particleImpl._lifetime / particleImpl._Max_Life); float _plota_out; float _plota_in0=(expr_a<0F?0F:(expr_a>1F?1F:expr_a)); _math.PathRes _plota_srch0 = _plota_in0<0.79269?_math.pathRes(0,(_plota_in0-0F)*1.26153F):_math.pathRes(1,(_plota_in0-0.79269F)*4.82369F); _math.funcLerp(out _plota_out, this._plota[0][_plota_srch0.s],_plota_srch0.i); particleImpl.size1_ = value_a; particleImpl.color_ = expr_; particleImpl.alpha_ = _plota_out; } public Emitter_DefaultEmitter() { addProperty("Color1", PropertyType.VEC3, (object emitterData) => { return ((EmitterData)emitterData)._Color1; }, (object emitterData, object value) => { _math.copyv3(out ((EmitterData)emitterData)._Color1, (_math.vec3)value); }); addProperty("Color2", PropertyType.VEC3, (object emitterData) => { return ((EmitterData)emitterData)._Color2; }, (object emitterData, object value) => { _math.copyv3(out ((EmitterData)emitterData)._Color2, (_math.vec3)value); }); generatorCreator_ = (Emitter emitter) => { return new GeneratorPeriodic(emitter, new GeneratorImpl()); }; constructorCreator_ = (Emitter emitter) => { return new ConstructorQuads(emitter, new ConstructorImpl()); }; name_ = "DefaultEmitter"; maxNumParticles_ = 200; sorting_ = Emitter.Sorting.OldToYoung; particleCreator_ = (Effect effect) => { return new ParticleImpl(); }; emitterDataCreator_ = () => { return new EmitterData(); }; } } public Model() { textures_ = new string[] { "glowing_dot.png" }; materials_ = new RenderMaterial[] { RenderMaterial.Add }; renderStyles_ = new RenderStyle[] { new RenderStyle(0,new uint[] {0}) }; frameTime_ = 0.0333333F; presimulateTime_ = 0F; maxNumRenderCalls_ = 200; maxNumParticles_ = 200; emitterModels_ = new EmitterModel[]{ new Emitter_DefaultEmitter() }; activeEmitterModels_ = new uint[] { 0 }; randomGeneratorCreator_ = () => { return _math.rand_; }; } } static Model modelInstance_ = null; public override EffectModel createModel() { if (modelInstance_ == null) modelInstance_ = new Model(); return modelInstance_; } } } #pragma warning restore 219
#region License /* * WebSocketSessionManager.cs * * The MIT License * * Copyright (c) 2012-2015 sta.blockhead * * 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.Collections; using System.Collections.Generic; using System.IO; using System.Text; using System.Threading; using System.Timers; namespace CustomWebSocketSharp.Server { /// <summary> /// Manages the sessions in a Websocket service. /// </summary> public class WebSocketSessionManager { #region Private Fields private volatile bool _clean; private object _forSweep; private Logger _logger; private Dictionary<string, IWebSocketSession> _sessions; private volatile ServerState _state; private volatile bool _sweeping; private System.Timers.Timer _sweepTimer; private object _sync; private TimeSpan _waitTime; #endregion #region Internal Constructors internal WebSocketSessionManager () : this (new Logger ()) { } internal WebSocketSessionManager (Logger logger) { _logger = logger; _clean = true; _forSweep = new object (); _sessions = new Dictionary<string, IWebSocketSession> (); _state = ServerState.Ready; _sync = ((ICollection) _sessions).SyncRoot; _waitTime = TimeSpan.FromSeconds (1); setSweepTimer (60000); } #endregion #region Internal Properties internal ServerState State { get { return _state; } } #endregion #region Public Properties /// <summary> /// Gets the IDs for the active sessions in the Websocket service. /// </summary> /// <value> /// An <c>IEnumerable&lt;string&gt;</c> instance that provides an enumerator which /// supports the iteration over the collection of the IDs for the active sessions. /// </value> public IEnumerable<string> ActiveIDs { get { foreach (var res in Broadping (WebSocketFrame.EmptyPingBytes, _waitTime)) if (res.Value) yield return res.Key; } } /// <summary> /// Gets the number of the sessions in the Websocket service. /// </summary> /// <value> /// An <see cref="int"/> that represents the number of the sessions. /// </value> public int Count { get { lock (_sync) return _sessions.Count; } } /// <summary> /// Gets the IDs for the sessions in the Websocket service. /// </summary> /// <value> /// An <c>IEnumerable&lt;string&gt;</c> instance that provides an enumerator which /// supports the iteration over the collection of the IDs for the sessions. /// </value> public IEnumerable<string> IDs { get { if (_state == ServerState.ShuttingDown) return new string[0]; lock (_sync) return _sessions.Keys.ToList (); } } /// <summary> /// Gets the IDs for the inactive sessions in the Websocket service. /// </summary> /// <value> /// An <c>IEnumerable&lt;string&gt;</c> instance that provides an enumerator which /// supports the iteration over the collection of the IDs for the inactive sessions. /// </value> public IEnumerable<string> InactiveIDs { get { foreach (var res in Broadping (WebSocketFrame.EmptyPingBytes, _waitTime)) if (!res.Value) yield return res.Key; } } /// <summary> /// Gets the session with the specified <paramref name="id"/>. /// </summary> /// <value> /// A <see cref="IWebSocketSession"/> instance that provides the access to /// the information in the session, or <see langword="null"/> if it's not found. /// </value> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> public IWebSocketSession this[string id] { get { IWebSocketSession session; TryGetSession (id, out session); return session; } } /// <summary> /// Gets a value indicating whether the manager cleans up the inactive sessions in /// the WebSocket service periodically. /// </summary> /// <value> /// <c>true</c> if the manager cleans up the inactive sessions every 60 seconds; /// otherwise, <c>false</c>. /// </value> public bool KeepClean { get { return _clean; } internal set { if (!(value ^ _clean)) return; _clean = value; if (_state == ServerState.Start) _sweepTimer.Enabled = value; } } /// <summary> /// Gets the sessions in the Websocket service. /// </summary> /// <value> /// An <c>IEnumerable&lt;IWebSocketSession&gt;</c> instance that provides an enumerator /// which supports the iteration over the collection of the sessions in the service. /// </value> public IEnumerable<IWebSocketSession> Sessions { get { if (_state == ServerState.ShuttingDown) return new IWebSocketSession[0]; lock (_sync) return _sessions.Values.ToList (); } } /// <summary> /// Gets the wait time for the response to the WebSocket Ping or Close. /// </summary> /// <value> /// A <see cref="TimeSpan"/> that represents the wait time. /// </value> public TimeSpan WaitTime { get { return _waitTime; } internal set { if (value == _waitTime) return; _waitTime = value; foreach (var session in Sessions) session.Context.WebSocket.WaitTime = value; } } #endregion #region Private Methods private void broadcast (Opcode opcode, byte[] data, Action completed) { var cache = new Dictionary<CompressionMethod, byte[]> (); try { Broadcast (opcode, data, cache); if (completed != null) completed (); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); } finally { cache.Clear (); } } private void broadcast (Opcode opcode, Stream stream, Action completed) { var cache = new Dictionary <CompressionMethod, Stream> (); try { Broadcast (opcode, stream, cache); if (completed != null) completed (); } catch (Exception ex) { _logger.Fatal (ex.ToString ()); } finally { foreach (var cached in cache.Values) cached.Dispose (); cache.Clear (); } } private void broadcastAsync (Opcode opcode, byte[] data, Action completed) { ThreadPool.QueueUserWorkItem (state => broadcast (opcode, data, completed)); } private void broadcastAsync (Opcode opcode, Stream stream, Action completed) { ThreadPool.QueueUserWorkItem (state => broadcast (opcode, stream, completed)); } private static string createID () { return Guid.NewGuid ().ToString ("N"); } private void setSweepTimer (double interval) { _sweepTimer = new System.Timers.Timer (interval); _sweepTimer.Elapsed += (sender, e) => Sweep (); } private void stop (PayloadData payloadData, bool send) { var bytes = send ? WebSocketFrame.CreateCloseFrame (payloadData, false).ToArray () : null; lock (_sync) { _state = ServerState.ShuttingDown; _sweepTimer.Enabled = false; foreach (var session in _sessions.Values.ToList ()) session.Context.WebSocket.Close (payloadData, bytes); _state = ServerState.Stop; } } private bool tryGetSession (string id, out IWebSocketSession session) { bool ret; lock (_sync) ret = _sessions.TryGetValue (id, out session); if (!ret) _logger.Error ("A session with the specified ID isn't found:\n ID: " + id); return ret; } #endregion #region Internal Methods internal string Add (IWebSocketSession session) { lock (_sync) { if (_state != ServerState.Start) return null; var id = createID (); _sessions.Add (id, session); return id; } } internal void Broadcast ( Opcode opcode, byte[] data, Dictionary<CompressionMethod, byte[]> cache) { foreach (var session in Sessions) { if (_state != ServerState.Start) break; session.Context.WebSocket.Send (opcode, data, cache); } } internal void Broadcast ( Opcode opcode, Stream stream, Dictionary <CompressionMethod, Stream> cache) { foreach (var session in Sessions) { if (_state != ServerState.Start) break; session.Context.WebSocket.Send (opcode, stream, cache); } } internal Dictionary<string, bool> Broadping (byte[] frameAsBytes, TimeSpan timeout) { var ret = new Dictionary<string, bool> (); foreach (var session in Sessions) { if (_state != ServerState.Start) break; ret.Add (session.ID, session.Context.WebSocket.Ping (frameAsBytes, timeout)); } return ret; } internal bool Remove (string id) { lock (_sync) return _sessions.Remove (id); } internal void Start () { lock (_sync) { _sweepTimer.Enabled = _clean; _state = ServerState.Start; } } internal void Stop (ushort code, string reason) { if (code == 1005) { // == no status stop (PayloadData.Empty, true); return; } stop (new PayloadData (code, reason), !code.IsReserved ()); } internal void Stop (CloseEventArgs e, byte[] frameAsBytes, bool receive) { lock (_sync) { _state = ServerState.ShuttingDown; _sweepTimer.Enabled = false; foreach (var session in _sessions.Values.ToList ()) session.Context.WebSocket.Close (e, frameAsBytes, receive); _state = ServerState.Stop; } } #endregion #region Public Methods /// <summary> /// Sends binary <paramref name="data"/> to every client in the WebSocket service. /// </summary> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> public void Broadcast (byte[] data) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckSendParameter (data); if (msg != null) { _logger.Error (msg); return; } if (data.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, null); else broadcast (Opcode.Binary, new MemoryStream (data), null); } /// <summary> /// Sends text <paramref name="data"/> to every client in the WebSocket service. /// </summary> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> public void Broadcast (string data) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckSendParameter (data); if (msg != null) { _logger.Error (msg); return; } var bytes = data.UTF8Encode (); if (bytes.LongLength <= WebSocket.FragmentLength) broadcast (Opcode.Text, bytes, null); else broadcast (Opcode.Text, new MemoryStream (bytes), null); } /// <summary> /// Sends binary <paramref name="data"/> asynchronously to every client in /// the WebSocket service. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <param name="completed"> /// An <see cref="Action"/> delegate that references the method(s) called when /// the send is complete. /// </param> public void BroadcastAsync (byte[] data, Action completed) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckSendParameter (data); if (msg != null) { _logger.Error (msg); return; } if (data.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Binary, data, completed); else broadcastAsync (Opcode.Binary, new MemoryStream (data), completed); } /// <summary> /// Sends text <paramref name="data"/> asynchronously to every client in /// the WebSocket service. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <param name="completed"> /// An <see cref="Action"/> delegate that references the method(s) called when /// the send is complete. /// </param> public void BroadcastAsync (string data, Action completed) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckSendParameter (data); if (msg != null) { _logger.Error (msg); return; } var bytes = data.UTF8Encode (); if (bytes.LongLength <= WebSocket.FragmentLength) broadcastAsync (Opcode.Text, bytes, completed); else broadcastAsync (Opcode.Text, new MemoryStream (bytes), completed); } /// <summary> /// Sends binary data from the specified <see cref="Stream"/> asynchronously to /// every client in the WebSocket service. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> from which contains the binary data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that represents the number of bytes to send. /// </param> /// <param name="completed"> /// An <see cref="Action"/> delegate that references the method(s) called when /// the send is complete. /// </param> public void BroadcastAsync (Stream stream, int length, Action completed) { var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckSendParameters (stream, length); if (msg != null) { _logger.Error (msg); return; } stream.ReadBytesAsync ( length, data => { var len = data.Length; if (len == 0) { _logger.Error ("The data cannot be read from 'stream'."); return; } if (len < length) _logger.Warn ( String.Format ( "The data with 'length' cannot be read from 'stream':\n expected: {0}\n actual: {1}", length, len)); if (len <= WebSocket.FragmentLength) broadcast (Opcode.Binary, data, completed); else broadcast (Opcode.Binary, new MemoryStream (data), completed); }, ex => _logger.Fatal (ex.ToString ())); } /// <summary> /// Sends a Ping to every client in the WebSocket service. /// </summary> /// <returns> /// A <c>Dictionary&lt;string, bool&gt;</c> that contains a collection of pairs of /// a session ID and a value indicating whether the manager received a Pong from /// each client in a time. /// </returns> public Dictionary<string, bool> Broadping () { var msg = _state.CheckIfAvailable (false, true, false); if (msg != null) { _logger.Error (msg); return null; } return Broadping (WebSocketFrame.EmptyPingBytes, _waitTime); } /// <summary> /// Sends a Ping with the specified <paramref name="message"/> to every client in /// the WebSocket service. /// </summary> /// <returns> /// A <c>Dictionary&lt;string, bool&gt;</c> that contains a collection of pairs of /// a session ID and a value indicating whether the manager received a Pong from /// each client in a time. /// </returns> /// <param name="message"> /// A <see cref="string"/> that represents the message to send. /// </param> public Dictionary<string, bool> Broadping (string message) { if (message == null || message.Length == 0) return Broadping (); byte[] data = null; var msg = _state.CheckIfAvailable (false, true, false) ?? WebSocket.CheckPingParameter (message, out data); if (msg != null) { _logger.Error (msg); return null; } return Broadping (WebSocketFrame.CreatePingFrame (data, false).ToArray (), _waitTime); } /// <summary> /// Closes the session with the specified <paramref name="id"/>. /// </summary> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to close. /// </param> public void CloseSession (string id) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Close (); } /// <summary> /// Closes the session with the specified <paramref name="id"/>, <paramref name="code"/>, /// and <paramref name="reason"/>. /// </summary> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to close. /// </param> /// <param name="code"> /// A <see cref="ushort"/> that represents the status code indicating the reason for the close. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the close. /// </param> public void CloseSession (string id, ushort code, string reason) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Close (code, reason); } /// <summary> /// Closes the session with the specified <paramref name="id"/>, <paramref name="code"/>, /// and <paramref name="reason"/>. /// </summary> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to close. /// </param> /// <param name="code"> /// One of the <see cref="CloseStatusCode"/> enum values, represents the status code /// indicating the reason for the close. /// </param> /// <param name="reason"> /// A <see cref="string"/> that represents the reason for the close. /// </param> public void CloseSession (string id, CloseStatusCode code, string reason) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Close (code, reason); } /// <summary> /// Sends a Ping to the client on the session with the specified <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if the manager receives a Pong from the client in a time; /// otherwise, <c>false</c>. /// </returns> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> public bool PingTo (string id) { IWebSocketSession session; return TryGetSession (id, out session) && session.Context.WebSocket.Ping (); } /// <summary> /// Sends a Ping with the specified <paramref name="message"/> to the client on /// the session with the specified <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if the manager receives a Pong from the client in a time; /// otherwise, <c>false</c>. /// </returns> /// <param name="message"> /// A <see cref="string"/> that represents the message to send. /// </param> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> public bool PingTo (string message, string id) { IWebSocketSession session; return TryGetSession (id, out session) && session.Context.WebSocket.Ping (message); } /// <summary> /// Sends binary <paramref name="data"/> to the client on the session with /// the specified <paramref name="id"/>. /// </summary> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> public void SendTo (byte[] data, string id) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Send (data); } /// <summary> /// Sends text <paramref name="data"/> to the client on the session with /// the specified <paramref name="id"/>. /// </summary> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> public void SendTo (string data, string id) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.Send (data); } /// <summary> /// Sends binary <paramref name="data"/> asynchronously to the client on /// the session with the specified <paramref name="id"/>. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="data"> /// An array of <see cref="byte"/> that represents the binary data to send. /// </param> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="completed"> /// An <c>Action&lt;bool&gt;</c> delegate that references the method(s) called when /// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c> /// if the send is complete successfully. /// </param> public void SendToAsync (byte[] data, string id, Action<bool> completed) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.SendAsync (data, completed); } /// <summary> /// Sends text <paramref name="data"/> asynchronously to the client on /// the session with the specified <paramref name="id"/>. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="data"> /// A <see cref="string"/> that represents the text data to send. /// </param> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="completed"> /// An <c>Action&lt;bool&gt;</c> delegate that references the method(s) called when /// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c> /// if the send is complete successfully. /// </param> public void SendToAsync (string data, string id, Action<bool> completed) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.SendAsync (data, completed); } /// <summary> /// Sends binary data from the specified <see cref="Stream"/> asynchronously to /// the client on the session with the specified <paramref name="id"/>. /// </summary> /// <remarks> /// This method doesn't wait for the send to be complete. /// </remarks> /// <param name="stream"> /// A <see cref="Stream"/> from which contains the binary data to send. /// </param> /// <param name="length"> /// An <see cref="int"/> that represents the number of bytes to send. /// </param> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="completed"> /// An <c>Action&lt;bool&gt;</c> delegate that references the method(s) called when /// the send is complete. A <see cref="bool"/> passed to this delegate is <c>true</c> /// if the send is complete successfully. /// </param> public void SendToAsync (Stream stream, int length, string id, Action<bool> completed) { IWebSocketSession session; if (TryGetSession (id, out session)) session.Context.WebSocket.SendAsync (stream, length, completed); } /// <summary> /// Cleans up the inactive sessions in the WebSocket service. /// </summary> public void Sweep () { if (_state != ServerState.Start || _sweeping || Count == 0) return; lock (_forSweep) { _sweeping = true; foreach (var id in InactiveIDs) { if (_state != ServerState.Start) break; lock (_sync) { IWebSocketSession session; if (_sessions.TryGetValue (id, out session)) { var state = session.State; if (state == WebSocketState.Open) session.Context.WebSocket.Close (CloseStatusCode.ProtocolError); else if (state == WebSocketState.Closing) continue; else _sessions.Remove (id); } } } _sweeping = false; } } /// <summary> /// Tries to get the session with the specified <paramref name="id"/>. /// </summary> /// <returns> /// <c>true</c> if the session is successfully found; otherwise, <c>false</c>. /// </returns> /// <param name="id"> /// A <see cref="string"/> that represents the ID of the session to find. /// </param> /// <param name="session"> /// When this method returns, a <see cref="IWebSocketSession"/> instance that /// provides the access to the information in the session, or <see langword="null"/> /// if it's not found. This parameter is passed uninitialized. /// </param> public bool TryGetSession (string id, out IWebSocketSession session) { var msg = _state.CheckIfAvailable (false, true, false) ?? id.CheckIfValidSessionID (); if (msg != null) { _logger.Error (msg); session = null; return false; } return tryGetSession (id, out session); } #endregion } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. namespace TestResources { public static class AnalyzerTests { private static byte[] s_faultyAnalyzer; public static byte[] FaultyAnalyzer => ResourceLoader.GetOrCreateResource(ref s_faultyAnalyzer, "Analyzers.FaultyAnalyzer.dll"); } public static class AssemblyLoadTests { private static byte[] s_alpha; public static byte[] Alpha => ResourceLoader.GetOrCreateResource(ref s_alpha, "AssemblyLoadTests.Alpha.dll"); private static byte[] s_beta; public static byte[] Beta => ResourceLoader.GetOrCreateResource(ref s_beta, "AssemblyLoadTests.Beta.dll"); private static byte[] s_delta; public static byte[] Delta => ResourceLoader.GetOrCreateResource(ref s_delta, "AssemblyLoadTests.Delta.dll"); private static byte[] s_gamma; public static byte[] Gamma => ResourceLoader.GetOrCreateResource(ref s_gamma, "AssemblyLoadTests.Gamma.dll"); } public static class DiagnosticTests { private static byte[] s_badresfile; public static byte[] badresfile => ResourceLoader.GetOrCreateResource(ref s_badresfile, "DiagnosticTests.badresfile.res"); private static byte[] s_errTestLib01; public static byte[] ErrTestLib01 => ResourceLoader.GetOrCreateResource(ref s_errTestLib01, "DiagnosticTests.ErrTestLib01.dll"); private static byte[] s_errTestLib02; public static byte[] ErrTestLib02 => ResourceLoader.GetOrCreateResource(ref s_errTestLib02, "DiagnosticTests.ErrTestLib02.dll"); private static byte[] s_errTestLib11; public static byte[] ErrTestLib11 => ResourceLoader.GetOrCreateResource(ref s_errTestLib11, "DiagnosticTests.ErrTestLib11.dll"); private static byte[] s_errTestMod01; public static byte[] ErrTestMod01 => ResourceLoader.GetOrCreateResource(ref s_errTestMod01, "DiagnosticTests.ErrTestMod01.netmodule"); private static byte[] s_errTestMod02; public static byte[] ErrTestMod02 => ResourceLoader.GetOrCreateResource(ref s_errTestMod02, "DiagnosticTests.ErrTestMod02.netmodule"); } public static class Basic { private static byte[] s_members; public static byte[] Members => ResourceLoader.GetOrCreateResource(ref s_members, "MetadataTests.Members.dll"); private static byte[] s_nativeApp; public static byte[] NativeApp => ResourceLoader.GetOrCreateResource(ref s_nativeApp, "MetadataTests.NativeApp.exe"); } } namespace TestResources.MetadataTests { public static class InterfaceAndClass { private static byte[] s_CSClasses01; public static byte[] CSClasses01 => ResourceLoader.GetOrCreateResource(ref s_CSClasses01, "MetadataTests.InterfaceAndClass.CSClasses01.dll"); private static byte[] s_CSInterfaces01; public static byte[] CSInterfaces01 => ResourceLoader.GetOrCreateResource(ref s_CSInterfaces01, "MetadataTests.InterfaceAndClass.CSInterfaces01.dll"); private static byte[] s_VBClasses01; public static byte[] VBClasses01 => ResourceLoader.GetOrCreateResource(ref s_VBClasses01, "MetadataTests.InterfaceAndClass.VBClasses01.dll"); private static byte[] s_VBClasses02; public static byte[] VBClasses02 => ResourceLoader.GetOrCreateResource(ref s_VBClasses02, "MetadataTests.InterfaceAndClass.VBClasses02.dll"); private static byte[] s_VBInterfaces01; public static byte[] VBInterfaces01 => ResourceLoader.GetOrCreateResource(ref s_VBInterfaces01, "MetadataTests.InterfaceAndClass.VBInterfaces01.dll"); } public static class Interop { private static byte[] s_indexerWithByRefParam; public static byte[] IndexerWithByRefParam => ResourceLoader.GetOrCreateResource(ref s_indexerWithByRefParam, "MetadataTests.Interop.IndexerWithByRefParam.dll"); private static byte[] s_interop_Mock01; public static byte[] Interop_Mock01 => ResourceLoader.GetOrCreateResource(ref s_interop_Mock01, "MetadataTests.Interop.Interop.Mock01.dll"); private static byte[] s_interop_Mock01_Impl; public static byte[] Interop_Mock01_Impl => ResourceLoader.GetOrCreateResource(ref s_interop_Mock01_Impl, "MetadataTests.Interop.Interop.Mock01.Impl.dll"); } public static class Invalid { private static byte[] s_classLayout; public static byte[] ClassLayout => ResourceLoader.GetOrCreateResource(ref s_classLayout, "MetadataTests.Invalid.ClassLayout.dll"); private static byte[] s_customAttributeTableUnsorted; public static byte[] CustomAttributeTableUnsorted => ResourceLoader.GetOrCreateResource(ref s_customAttributeTableUnsorted, "MetadataTests.Invalid.CustomAttributeTableUnsorted.dll"); private static byte[] s_emptyModuleTable; public static byte[] EmptyModuleTable => ResourceLoader.GetOrCreateResource(ref s_emptyModuleTable, "MetadataTests.Invalid.EmptyModuleTable.netmodule"); private static byte[] s_incorrectCustomAssemblyTableSize_TooManyMethodSpecs; public static byte[] IncorrectCustomAssemblyTableSize_TooManyMethodSpecs => ResourceLoader.GetOrCreateResource(ref s_incorrectCustomAssemblyTableSize_TooManyMethodSpecs, "MetadataTests.Invalid.IncorrectCustomAssemblyTableSize_TooManyMethodSpecs.dll"); private static byte[] s_invalidDynamicAttributeArgs; public static byte[] InvalidDynamicAttributeArgs => ResourceLoader.GetOrCreateResource(ref s_invalidDynamicAttributeArgs, "MetadataTests.Invalid.InvalidDynamicAttributeArgs.dll"); private static byte[] s_invalidFuncDelegateName; public static byte[] InvalidFuncDelegateName => ResourceLoader.GetOrCreateResource(ref s_invalidFuncDelegateName, "MetadataTests.Invalid.InvalidFuncDelegateName.dll"); private static byte[] s_invalidGenericType; public static byte[] InvalidGenericType => ResourceLoader.GetOrCreateResource(ref s_invalidGenericType, "MetadataTests.Invalid.InvalidGenericType.dll"); private static byte[] s_invalidModuleName; public static byte[] InvalidModuleName => ResourceLoader.GetOrCreateResource(ref s_invalidModuleName, "MetadataTests.Invalid.InvalidModuleName.dll"); private static byte[] s_longTypeFormInSignature; public static byte[] LongTypeFormInSignature => ResourceLoader.GetOrCreateResource(ref s_longTypeFormInSignature, "MetadataTests.Invalid.LongTypeFormInSignature.dll"); private static string s_manyMethodSpecs; public static string ManyMethodSpecs => ResourceLoader.GetOrCreateResource(ref s_manyMethodSpecs, "MetadataTests.Invalid.ManyMethodSpecs.vb"); private static byte[] s_obfuscated; public static byte[] Obfuscated => ResourceLoader.GetOrCreateResource(ref s_obfuscated, "MetadataTests.Invalid.Obfuscated.dll"); private static byte[] s_obfuscated2; public static byte[] Obfuscated2 => ResourceLoader.GetOrCreateResource(ref s_obfuscated2, "MetadataTests.Invalid.Obfuscated2.dll"); public static class Signatures { private static byte[] s_signatureCycle2; public static byte[] SignatureCycle2 => ResourceLoader.GetOrCreateResource(ref s_signatureCycle2, "MetadataTests.Invalid.Signatures.SignatureCycle2.exe"); private static byte[] s_typeSpecInWrongPlace; public static byte[] TypeSpecInWrongPlace => ResourceLoader.GetOrCreateResource(ref s_typeSpecInWrongPlace, "MetadataTests.Invalid.Signatures.TypeSpecInWrongPlace.exe"); } } public static class NetModule01 { private static byte[] s_appCS; public static byte[] AppCS => ResourceLoader.GetOrCreateResource(ref s_appCS, "MetadataTests.NetModule01.AppCS.exe"); private static byte[] s_moduleCS00; public static byte[] ModuleCS00 => ResourceLoader.GetOrCreateResource(ref s_moduleCS00, "MetadataTests.NetModule01.ModuleCS00.mod"); private static byte[] s_moduleCS01; public static byte[] ModuleCS01 => ResourceLoader.GetOrCreateResource(ref s_moduleCS01, "MetadataTests.NetModule01.ModuleCS01.mod"); private static byte[] s_moduleVB01; public static byte[] ModuleVB01 => ResourceLoader.GetOrCreateResource(ref s_moduleVB01, "MetadataTests.NetModule01.ModuleVB01.mod"); } } namespace TestResources.NetFX { public static class aacorlib_v15_0_3928 { private static string s_aacorlib_v15_0_3928_cs; public static string aacorlib_v15_0_3928_cs => ResourceLoader.GetOrCreateResource(ref s_aacorlib_v15_0_3928_cs, "NetFX.aacorlib.aacorlib.v15.0.3928.cs"); } public static class Minimal { private static byte[] s_mincorlib; public static byte[] mincorlib => ResourceLoader.GetOrCreateResource(ref s_mincorlib, "NetFX.Minimal.mincorlib.dll"); private static byte[] s_minasync; public static byte[] minasync => ResourceLoader.GetOrCreateResource(ref s_minasync, "NetFX.Minimal.minasync.dll"); private static byte [] s_minasynccorlib; public static byte [] minasynccorlib => ResourceLoader.GetOrCreateResource(ref s_minasynccorlib, "NetFX.Minimal.minasynccorlib.dll"); } public static class ValueTuple { private static byte[] s_tuplelib; public static byte[] tuplelib => ResourceLoader.GetOrCreateResource(ref s_tuplelib, "NetFX.ValueTuple.System.ValueTuple.dll"); private static string s_tuplelib_cs; public static string tuplelib_cs => ResourceLoader.GetOrCreateResource(ref s_tuplelib_cs, "NetFX.ValueTuple.ValueTuple.cs"); } } namespace TestResources { public static class PerfTests { private static string s_CSPerfTest; public static string CSPerfTest => ResourceLoader.GetOrCreateResource(ref s_CSPerfTest, "PerfTests.CSPerfTest.cs"); private static string s_VBPerfTest; public static string VBPerfTest => ResourceLoader.GetOrCreateResource(ref s_VBPerfTest, "PerfTests.VBPerfTest.vb"); } public static class General { private static byte[] s_bigVisitor; public static byte[] BigVisitor => ResourceLoader.GetOrCreateResource(ref s_bigVisitor, "SymbolsTests.BigVisitor.dll"); private static byte[] s_delegateByRefParamArray; public static byte[] DelegateByRefParamArray => ResourceLoader.GetOrCreateResource(ref s_delegateByRefParamArray, "SymbolsTests.Delegates.DelegateByRefParamArray.dll"); private static byte[] s_delegatesWithoutInvoke; public static byte[] DelegatesWithoutInvoke => ResourceLoader.GetOrCreateResource(ref s_delegatesWithoutInvoke, "SymbolsTests.Delegates.DelegatesWithoutInvoke.dll"); private static byte[] s_shiftJisSource; public static byte[] ShiftJisSource => ResourceLoader.GetOrCreateResource(ref s_shiftJisSource, "Encoding.sjis.cs"); private static byte[] s_events; public static byte[] Events => ResourceLoader.GetOrCreateResource(ref s_events, "SymbolsTests.Events.dll"); private static byte[] s_CSharpExplicitInterfaceImplementation; public static byte[] CSharpExplicitInterfaceImplementation => ResourceLoader.GetOrCreateResource(ref s_CSharpExplicitInterfaceImplementation, "SymbolsTests.ExplicitInterfaceImplementation.CSharpExplicitInterfaceImplementation.dll"); private static byte[] s_CSharpExplicitInterfaceImplementationEvents; public static byte[] CSharpExplicitInterfaceImplementationEvents => ResourceLoader.GetOrCreateResource(ref s_CSharpExplicitInterfaceImplementationEvents, "SymbolsTests.ExplicitInterfaceImplementation.CSharpExplicitInterfaceImplementationEvents.dll"); private static byte[] s_CSharpExplicitInterfaceImplementationProperties; public static byte[] CSharpExplicitInterfaceImplementationProperties => ResourceLoader.GetOrCreateResource(ref s_CSharpExplicitInterfaceImplementationProperties, "SymbolsTests.ExplicitInterfaceImplementation.CSharpExplicitInterfaceImplementationProperties.dll"); private static byte[] s_ILExplicitInterfaceImplementation; public static byte[] ILExplicitInterfaceImplementation => ResourceLoader.GetOrCreateResource(ref s_ILExplicitInterfaceImplementation, "SymbolsTests.ExplicitInterfaceImplementation.ILExplicitInterfaceImplementation.dll"); private static byte[] s_ILExplicitInterfaceImplementationProperties; public static byte[] ILExplicitInterfaceImplementationProperties => ResourceLoader.GetOrCreateResource(ref s_ILExplicitInterfaceImplementationProperties, "SymbolsTests.ExplicitInterfaceImplementation.ILExplicitInterfaceImplementationProperties.dll"); private static byte[] s_FSharpTestLibrary; public static byte[] FSharpTestLibrary => ResourceLoader.GetOrCreateResource(ref s_FSharpTestLibrary, "SymbolsTests.FSharpTestLibrary.dll"); private static byte[] s_indexers; public static byte[] Indexers => ResourceLoader.GetOrCreateResource(ref s_indexers, "SymbolsTests.Indexers.dll"); private static byte[] s_inheritIComparable; public static byte[] InheritIComparable => ResourceLoader.GetOrCreateResource(ref s_inheritIComparable, "SymbolsTests.InheritIComparable.dll"); private static byte[] s_MDTestLib1; public static byte[] MDTestLib1 => ResourceLoader.GetOrCreateResource(ref s_MDTestLib1, "SymbolsTests.MDTestLib1.dll"); private static byte[] s_MDTestLib2; public static byte[] MDTestLib2 => ResourceLoader.GetOrCreateResource(ref s_MDTestLib2, "SymbolsTests.MDTestLib2.dll"); private static byte[] s_nativeCOFFResources; public static byte[] nativeCOFFResources => ResourceLoader.GetOrCreateResource(ref s_nativeCOFFResources, "SymbolsTests.nativeCOFFResources.obj"); private static byte[] s_properties; public static byte[] Properties => ResourceLoader.GetOrCreateResource(ref s_properties, "SymbolsTests.Properties.dll"); private static byte[] s_propertiesWithByRef; public static byte[] PropertiesWithByRef => ResourceLoader.GetOrCreateResource(ref s_propertiesWithByRef, "SymbolsTests.PropertiesWithByRef.dll"); private static byte[] s_regress40025DLL; public static byte[] Regress40025DLL => ResourceLoader.GetOrCreateResource(ref s_regress40025DLL, "SymbolsTests.Regress40025DLL.dll"); private static byte[] s_snKey; public static byte[] snKey => ResourceLoader.GetOrCreateResource(ref s_snKey, "SymbolsTests.snKey.snk"); private static byte[] s_snKey2; public static byte[] snKey2 => ResourceLoader.GetOrCreateResource(ref s_snKey2, "SymbolsTests.snKey2.snk"); private static byte[] s_snPublicKey; public static byte[] snPublicKey => ResourceLoader.GetOrCreateResource(ref s_snPublicKey, "SymbolsTests.snPublicKey.snk"); private static byte[] s_snPublicKey2; public static byte[] snPublicKey2 => ResourceLoader.GetOrCreateResource(ref s_snPublicKey2, "SymbolsTests.snPublicKey2.snk"); private static byte[] s_CSharpErrors; public static byte[] CSharpErrors => ResourceLoader.GetOrCreateResource(ref s_CSharpErrors, "SymbolsTests.UseSiteErrors.CSharpErrors.dll"); private static byte[] s_ILErrors; public static byte[] ILErrors => ResourceLoader.GetOrCreateResource(ref s_ILErrors, "SymbolsTests.UseSiteErrors.ILErrors.dll"); private static byte[] s_unavailable; public static byte[] Unavailable => ResourceLoader.GetOrCreateResource(ref s_unavailable, "SymbolsTests.UseSiteErrors.Unavailable.dll"); private static byte[] s_VBConversions; public static byte[] VBConversions => ResourceLoader.GetOrCreateResource(ref s_VBConversions, "SymbolsTests.VBConversions.dll"); private static byte[] s_culture_AR_SA; public static byte[] Culture_AR_SA => ResourceLoader.GetOrCreateResource(ref s_culture_AR_SA, "SymbolsTests.Versioning.AR_SA.Culture.dll"); private static byte[] s_culture_EN_US; public static byte[] Culture_EN_US => ResourceLoader.GetOrCreateResource(ref s_culture_EN_US, "SymbolsTests.Versioning.EN_US.Culture.dll"); private static byte[] s_C1; public static byte[] C1 => ResourceLoader.GetOrCreateResource(ref s_C1, "SymbolsTests.Versioning.V1.C.dll"); private static byte[] s_C2; public static byte[] C2 => ResourceLoader.GetOrCreateResource(ref s_C2, "SymbolsTests.Versioning.V2.C.dll"); private static byte[] s_with_Spaces; public static byte[] With_Spaces => ResourceLoader.GetOrCreateResource(ref s_with_Spaces, "SymbolsTests.With Spaces.dll"); private static byte[] s_with_SpacesModule; public static byte[] With_SpacesModule => ResourceLoader.GetOrCreateResource(ref s_with_SpacesModule, "SymbolsTests.With Spaces.netmodule"); } } namespace TestResources.SymbolsTests { public static class CorLibrary { private static byte[] s_fakeMsCorLib; public static byte[] FakeMsCorLib => ResourceLoader.GetOrCreateResource(ref s_fakeMsCorLib, "SymbolsTests.CorLibrary.FakeMsCorLib.dll"); private static byte[] s_guidTest2; public static byte[] GuidTest2 => ResourceLoader.GetOrCreateResource(ref s_guidTest2, "SymbolsTests.CorLibrary.GuidTest2.exe"); private static byte[] s_noMsCorLibRef; public static byte[] NoMsCorLibRef => ResourceLoader.GetOrCreateResource(ref s_noMsCorLibRef, "SymbolsTests.CorLibrary.NoMsCorLibRef.dll"); } public static class CustomModifiers { private static byte[] s_cppCli; public static byte[] CppCli => ResourceLoader.GetOrCreateResource(ref s_cppCli, "SymbolsTests.CustomModifiers.CppCli.dll"); private static byte[] s_modifiers; public static byte[] Modifiers => ResourceLoader.GetOrCreateResource(ref s_modifiers, "SymbolsTests.CustomModifiers.Modifiers.dll"); private static byte[] s_modifiersModule; public static byte[] ModifiersModule => ResourceLoader.GetOrCreateResource(ref s_modifiersModule, "SymbolsTests.CustomModifiers.Modifiers.netmodule"); private static byte[] s_modoptTests; public static byte[] ModoptTests => ResourceLoader.GetOrCreateResource(ref s_modoptTests, "SymbolsTests.CustomModifiers.ModoptTests.dll"); } public static class Cyclic { private static byte[] s_cyclic1; public static byte[] Cyclic1 => ResourceLoader.GetOrCreateResource(ref s_cyclic1, "SymbolsTests.Cyclic.Cyclic1.dll"); private static byte[] s_cyclic2; public static byte[] Cyclic2 => ResourceLoader.GetOrCreateResource(ref s_cyclic2, "SymbolsTests.Cyclic.Cyclic2.dll"); } public static class CyclicInheritance { private static byte[] s_class1; public static byte[] Class1 => ResourceLoader.GetOrCreateResource(ref s_class1, "SymbolsTests.CyclicInheritance.Class1.dll"); private static byte[] s_class2; public static byte[] Class2 => ResourceLoader.GetOrCreateResource(ref s_class2, "SymbolsTests.CyclicInheritance.Class2.dll"); private static byte[] s_class3; public static byte[] Class3 => ResourceLoader.GetOrCreateResource(ref s_class3, "SymbolsTests.CyclicInheritance.Class3.dll"); } public static class CyclicStructure { private static byte[] s_cycledstructs; public static byte[] cycledstructs => ResourceLoader.GetOrCreateResource(ref s_cycledstructs, "SymbolsTests.CyclicStructure.cycledstructs.dll"); } public static class DifferByCase { private static byte[] s_consumer; public static byte[] Consumer => ResourceLoader.GetOrCreateResource(ref s_consumer, "SymbolsTests.DifferByCase.Consumer.dll"); private static byte[] s_csharpCaseSen; public static byte[] CsharpCaseSen => ResourceLoader.GetOrCreateResource(ref s_csharpCaseSen, "SymbolsTests.DifferByCase.CsharpCaseSen.dll"); private static byte[] s_CSharpDifferCaseOverloads; public static byte[] CSharpDifferCaseOverloads => ResourceLoader.GetOrCreateResource(ref s_CSharpDifferCaseOverloads, "SymbolsTests.DifferByCase.CSharpDifferCaseOverloads.dll"); private static byte[] s_typeAndNamespaceDifferByCase; public static byte[] TypeAndNamespaceDifferByCase => ResourceLoader.GetOrCreateResource(ref s_typeAndNamespaceDifferByCase, "SymbolsTests.DifferByCase.TypeAndNamespaceDifferByCase.dll"); } public static class Fields { private static byte[] s_constantFields; public static byte[] ConstantFields => ResourceLoader.GetOrCreateResource(ref s_constantFields, "SymbolsTests.Fields.ConstantFields.dll"); private static byte[] s_CSFields; public static byte[] CSFields => ResourceLoader.GetOrCreateResource(ref s_CSFields, "SymbolsTests.Fields.CSFields.dll"); private static byte[] s_VBFields; public static byte[] VBFields => ResourceLoader.GetOrCreateResource(ref s_VBFields, "SymbolsTests.Fields.VBFields.dll"); } public static class Interface { private static byte[] s_MDInterfaceMapping; public static byte[] MDInterfaceMapping => ResourceLoader.GetOrCreateResource(ref s_MDInterfaceMapping, "SymbolsTests.Interface.MDInterfaceMapping.dll"); private static byte[] s_staticMethodInInterface; public static byte[] StaticMethodInInterface => ResourceLoader.GetOrCreateResource(ref s_staticMethodInInterface, "SymbolsTests.Interface.StaticMethodInInterface.dll"); } public static class Metadata { private static byte[] s_attributeInterop01; public static byte[] AttributeInterop01 => ResourceLoader.GetOrCreateResource(ref s_attributeInterop01, "SymbolsTests.Metadata.AttributeInterop01.dll"); private static byte[] s_attributeInterop02; public static byte[] AttributeInterop02 => ResourceLoader.GetOrCreateResource(ref s_attributeInterop02, "SymbolsTests.Metadata.AttributeInterop02.dll"); private static byte[] s_attributeTestDef01; public static byte[] AttributeTestDef01 => ResourceLoader.GetOrCreateResource(ref s_attributeTestDef01, "SymbolsTests.Metadata.AttributeTestDef01.dll"); private static byte[] s_attributeTestLib01; public static byte[] AttributeTestLib01 => ResourceLoader.GetOrCreateResource(ref s_attributeTestLib01, "SymbolsTests.Metadata.AttributeTestLib01.dll"); private static byte[] s_dynamicAttribute; public static byte[] DynamicAttribute => ResourceLoader.GetOrCreateResource(ref s_dynamicAttribute, "SymbolsTests.Metadata.DynamicAttribute.dll"); private static byte[] s_invalidCharactersInAssemblyName; public static byte[] InvalidCharactersInAssemblyName => ResourceLoader.GetOrCreateResource(ref s_invalidCharactersInAssemblyName, "SymbolsTests.Metadata.InvalidCharactersInAssemblyName.dll"); private static byte[] s_invalidPublicKey; public static byte[] InvalidPublicKey => ResourceLoader.GetOrCreateResource(ref s_invalidPublicKey, "SymbolsTests.Metadata.InvalidPublicKey.dll"); private static byte[] s_MDTestAttributeApplicationLib; public static byte[] MDTestAttributeApplicationLib => ResourceLoader.GetOrCreateResource(ref s_MDTestAttributeApplicationLib, "SymbolsTests.Metadata.MDTestAttributeApplicationLib.dll"); private static byte[] s_MDTestAttributeDefLib; public static byte[] MDTestAttributeDefLib => ResourceLoader.GetOrCreateResource(ref s_MDTestAttributeDefLib, "SymbolsTests.Metadata.MDTestAttributeDefLib.dll"); private static byte[] s_mscorlibNamespacesAndTypes; public static byte[] MscorlibNamespacesAndTypes => ResourceLoader.GetOrCreateResource(ref s_mscorlibNamespacesAndTypes, "SymbolsTests.Metadata.MscorlibNamespacesAndTypes.bsl"); private static byte[] s_publicAndPrivateFlags; public static byte[] PublicAndPrivateFlags => ResourceLoader.GetOrCreateResource(ref s_publicAndPrivateFlags, "SymbolsTests.Metadata.public-and-private.dll"); } public static class Methods { private static byte[] s_byRefReturn; public static byte[] ByRefReturn => ResourceLoader.GetOrCreateResource(ref s_byRefReturn, "SymbolsTests.Methods.ByRefReturn.dll"); private static byte[] s_CSMethods; public static byte[] CSMethods => ResourceLoader.GetOrCreateResource(ref s_CSMethods, "SymbolsTests.Methods.CSMethods.dll"); private static byte[] s_ILMethods; public static byte[] ILMethods => ResourceLoader.GetOrCreateResource(ref s_ILMethods, "SymbolsTests.Methods.ILMethods.dll"); private static byte[] s_VBMethods; public static byte[] VBMethods => ResourceLoader.GetOrCreateResource(ref s_VBMethods, "SymbolsTests.Methods.VBMethods.dll"); } public static class MissingTypes { private static byte[] s_CL2; public static byte[] CL2 => ResourceLoader.GetOrCreateResource(ref s_CL2, "SymbolsTests.MissingTypes.CL2.dll"); private static byte[] s_CL3; public static byte[] CL3 => ResourceLoader.GetOrCreateResource(ref s_CL3, "SymbolsTests.MissingTypes.CL3.dll"); private static string s_CL3_VB; public static string CL3_VB => ResourceLoader.GetOrCreateResource(ref s_CL3_VB, "SymbolsTests.MissingTypes.CL3.vb"); private static byte[] s_MDMissingType; public static byte[] MDMissingType => ResourceLoader.GetOrCreateResource(ref s_MDMissingType, "SymbolsTests.MissingTypes.MDMissingType.dll"); private static byte[] s_MDMissingTypeLib; public static byte[] MDMissingTypeLib => ResourceLoader.GetOrCreateResource(ref s_MDMissingTypeLib, "SymbolsTests.MissingTypes.MDMissingTypeLib.dll"); private static byte[] s_MDMissingTypeLib_New; public static byte[] MDMissingTypeLib_New => ResourceLoader.GetOrCreateResource(ref s_MDMissingTypeLib_New, "SymbolsTests.MissingTypes.MDMissingTypeLib_New.dll"); private static byte[] s_missingTypesEquality1; public static byte[] MissingTypesEquality1 => ResourceLoader.GetOrCreateResource(ref s_missingTypesEquality1, "SymbolsTests.MissingTypes.MissingTypesEquality1.dll"); private static byte[] s_missingTypesEquality2; public static byte[] MissingTypesEquality2 => ResourceLoader.GetOrCreateResource(ref s_missingTypesEquality2, "SymbolsTests.MissingTypes.MissingTypesEquality2.dll"); } public static class MultiModule { private static byte[] s_consumer; public static byte[] Consumer => ResourceLoader.GetOrCreateResource(ref s_consumer, "SymbolsTests.MultiModule.Consumer.dll"); private static byte[] s_mod2; public static byte[] mod2 => ResourceLoader.GetOrCreateResource(ref s_mod2, "SymbolsTests.MultiModule.mod2.netmodule"); private static byte[] s_mod3; public static byte[] mod3 => ResourceLoader.GetOrCreateResource(ref s_mod3, "SymbolsTests.MultiModule.mod3.netmodule"); private static byte[] s_multiModuleDll; public static byte[] MultiModuleDll => ResourceLoader.GetOrCreateResource(ref s_multiModuleDll, "SymbolsTests.MultiModule.MultiModule.dll"); } public static class MultiTargeting { private static byte[] s_source1Module; public static byte[] Source1Module => ResourceLoader.GetOrCreateResource(ref s_source1Module, "SymbolsTests.MultiTargeting.Source1Module.netmodule"); private static byte[] s_source3Module; public static byte[] Source3Module => ResourceLoader.GetOrCreateResource(ref s_source3Module, "SymbolsTests.MultiTargeting.Source3Module.netmodule"); private static byte[] s_source4Module; public static byte[] Source4Module => ResourceLoader.GetOrCreateResource(ref s_source4Module, "SymbolsTests.MultiTargeting.Source4Module.netmodule"); private static byte[] s_source5Module; public static byte[] Source5Module => ResourceLoader.GetOrCreateResource(ref s_source5Module, "SymbolsTests.MultiTargeting.Source5Module.netmodule"); private static byte[] s_source7Module; public static byte[] Source7Module => ResourceLoader.GetOrCreateResource(ref s_source7Module, "SymbolsTests.MultiTargeting.Source7Module.netmodule"); } public static class netModule { private static byte[] s_crossRefLib; public static byte[] CrossRefLib => ResourceLoader.GetOrCreateResource(ref s_crossRefLib, "SymbolsTests.netModule.CrossRefLib.dll"); private static byte[] s_crossRefModule1; public static byte[] CrossRefModule1 => ResourceLoader.GetOrCreateResource(ref s_crossRefModule1, "SymbolsTests.netModule.CrossRefModule1.netmodule"); private static byte[] s_crossRefModule2; public static byte[] CrossRefModule2 => ResourceLoader.GetOrCreateResource(ref s_crossRefModule2, "SymbolsTests.netModule.CrossRefModule2.netmodule"); private static byte[] s_hash_module; public static byte[] hash_module => ResourceLoader.GetOrCreateResource(ref s_hash_module, "SymbolsTests.netModule.hash_module.netmodule"); private static byte[] s_netModule1; public static byte[] netModule1 => ResourceLoader.GetOrCreateResource(ref s_netModule1, "SymbolsTests.netModule.netModule1.netmodule"); private static byte[] s_netModule2; public static byte[] netModule2 => ResourceLoader.GetOrCreateResource(ref s_netModule2, "SymbolsTests.netModule.netModule2.netmodule"); private static byte[] s_x64COFF; public static byte[] x64COFF => ResourceLoader.GetOrCreateResource(ref s_x64COFF, "SymbolsTests.netModule.x64COFF.obj"); } public static class NoPia { private static byte[] s_A; public static byte[] A => ResourceLoader.GetOrCreateResource(ref s_A, "SymbolsTests.NoPia.A.dll"); private static byte[] s_B; public static byte[] B => ResourceLoader.GetOrCreateResource(ref s_B, "SymbolsTests.NoPia.B.dll"); private static byte[] s_C; public static byte[] C => ResourceLoader.GetOrCreateResource(ref s_C, "SymbolsTests.NoPia.C.dll"); private static byte[] s_D; public static byte[] D => ResourceLoader.GetOrCreateResource(ref s_D, "SymbolsTests.NoPia.D.dll"); private static byte[] s_externalAsm1; public static byte[] ExternalAsm1 => ResourceLoader.GetOrCreateResource(ref s_externalAsm1, "SymbolsTests.NoPia.ExternalAsm1.dll"); private static byte[] s_generalPia; public static byte[] GeneralPia => ResourceLoader.GetOrCreateResource(ref s_generalPia, "SymbolsTests.NoPia.GeneralPia.dll"); private static byte[] s_generalPiaCopy; public static byte[] GeneralPiaCopy => ResourceLoader.GetOrCreateResource(ref s_generalPiaCopy, "SymbolsTests.NoPia.GeneralPiaCopy.dll"); private static byte[] s_library1; public static byte[] Library1 => ResourceLoader.GetOrCreateResource(ref s_library1, "SymbolsTests.NoPia.Library1.dll"); private static byte[] s_library2; public static byte[] Library2 => ResourceLoader.GetOrCreateResource(ref s_library2, "SymbolsTests.NoPia.Library2.dll"); private static byte[] s_localTypes1; public static byte[] LocalTypes1 => ResourceLoader.GetOrCreateResource(ref s_localTypes1, "SymbolsTests.NoPia.LocalTypes1.dll"); private static byte[] s_localTypes2; public static byte[] LocalTypes2 => ResourceLoader.GetOrCreateResource(ref s_localTypes2, "SymbolsTests.NoPia.LocalTypes2.dll"); private static byte[] s_localTypes3; public static byte[] LocalTypes3 => ResourceLoader.GetOrCreateResource(ref s_localTypes3, "SymbolsTests.NoPia.LocalTypes3.dll"); private static byte[] s_missingPIAAttributes; public static byte[] MissingPIAAttributes => ResourceLoader.GetOrCreateResource(ref s_missingPIAAttributes, "SymbolsTests.NoPia.MissingPIAAttributes.dll"); private static byte[] s_noPIAGenerics1_Asm1; public static byte[] NoPIAGenerics1_Asm1 => ResourceLoader.GetOrCreateResource(ref s_noPIAGenerics1_Asm1, "SymbolsTests.NoPia.NoPIAGenerics1-Asm1.dll"); private static byte[] s_pia1; public static byte[] Pia1 => ResourceLoader.GetOrCreateResource(ref s_pia1, "SymbolsTests.NoPia.Pia1.dll"); private static byte[] s_pia1Copy; public static byte[] Pia1Copy => ResourceLoader.GetOrCreateResource(ref s_pia1Copy, "SymbolsTests.NoPia.Pia1Copy.dll"); private static byte[] s_pia2; public static byte[] Pia2 => ResourceLoader.GetOrCreateResource(ref s_pia2, "SymbolsTests.NoPia.Pia2.dll"); private static byte[] s_pia3; public static byte[] Pia3 => ResourceLoader.GetOrCreateResource(ref s_pia3, "SymbolsTests.NoPia.Pia3.dll"); private static byte[] s_pia4; public static byte[] Pia4 => ResourceLoader.GetOrCreateResource(ref s_pia4, "SymbolsTests.NoPia.Pia4.dll"); private static byte[] s_pia5; public static byte[] Pia5 => ResourceLoader.GetOrCreateResource(ref s_pia5, "SymbolsTests.NoPia.Pia5.dll"); private static byte[] s_parametersWithoutNames; public static byte[] ParametersWithoutNames => ResourceLoader.GetOrCreateResource(ref s_parametersWithoutNames, "SymbolsTests.NoPia.ParametersWithoutNames.dll"); } } namespace TestResources.SymbolsTests.RetargetingCycle { public static class RetV1 { private static byte[] s_classA; public static byte[] ClassA => ResourceLoader.GetOrCreateResource(ref s_classA, "SymbolsTests.RetargetingCycle.V1.ClassA.dll"); private static byte[] s_classB; public static byte[] ClassB => ResourceLoader.GetOrCreateResource(ref s_classB, "SymbolsTests.RetargetingCycle.V1.ClassB.netmodule"); } public static class RetV2 { private static byte[] s_classA; public static byte[] ClassA => ResourceLoader.GetOrCreateResource(ref s_classA, "SymbolsTests.RetargetingCycle.V2.ClassA.dll"); private static byte[] s_classB; public static byte[] ClassB => ResourceLoader.GetOrCreateResource(ref s_classB, "SymbolsTests.RetargetingCycle.V2.ClassB.dll"); } } namespace TestResources.SymbolsTests { public static class TypeForwarders { private static byte[] s_forwarded; public static byte[] Forwarded => ResourceLoader.GetOrCreateResource(ref s_forwarded, "SymbolsTests.TypeForwarders.Forwarded.netmodule"); private static byte[] s_typeForwarder; public static byte[] TypeForwarder => ResourceLoader.GetOrCreateResource(ref s_typeForwarder, "SymbolsTests.TypeForwarders.TypeForwarder.dll"); private static byte[] s_typeForwarderBase; public static byte[] TypeForwarderBase => ResourceLoader.GetOrCreateResource(ref s_typeForwarderBase, "SymbolsTests.TypeForwarders.TypeForwarderBase.dll"); private static byte[] s_typeForwarderLib; public static byte[] TypeForwarderLib => ResourceLoader.GetOrCreateResource(ref s_typeForwarderLib, "SymbolsTests.TypeForwarders.TypeForwarderLib.dll"); } public static class V1 { private static byte[] s_MTTestLib1; public static byte[] MTTestLib1 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib1, "SymbolsTests.V1.MTTestLib1.Dll"); private static string s_MTTestLib1_V1; public static string MTTestLib1_V1 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib1_V1, "SymbolsTests.V1.MTTestLib1_V1.vb"); private static byte[] s_MTTestLib2; public static byte[] MTTestLib2 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib2, "SymbolsTests.V1.MTTestLib2.Dll"); private static string s_MTTestLib2_V1; public static string MTTestLib2_V1 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib2_V1, "SymbolsTests.V1.MTTestLib2_V1.vb"); private static byte[] s_MTTestModule1; public static byte[] MTTestModule1 => ResourceLoader.GetOrCreateResource(ref s_MTTestModule1, "SymbolsTests.V1.MTTestModule1.netmodule"); private static byte[] s_MTTestModule2; public static byte[] MTTestModule2 => ResourceLoader.GetOrCreateResource(ref s_MTTestModule2, "SymbolsTests.V1.MTTestModule2.netmodule"); } public static class V2 { private static byte[] s_MTTestLib1; public static byte[] MTTestLib1 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib1, "SymbolsTests.V2.MTTestLib1.Dll"); private static string s_MTTestLib1_V2; public static string MTTestLib1_V2 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib1_V2, "SymbolsTests.V2.MTTestLib1_V2.vb"); private static byte[] s_MTTestLib3; public static byte[] MTTestLib3 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib3, "SymbolsTests.V2.MTTestLib3.Dll"); private static string s_MTTestLib3_V2; public static string MTTestLib3_V2 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib3_V2, "SymbolsTests.V2.MTTestLib3_V2.vb"); private static byte[] s_MTTestModule1; public static byte[] MTTestModule1 => ResourceLoader.GetOrCreateResource(ref s_MTTestModule1, "SymbolsTests.V2.MTTestModule1.netmodule"); private static byte[] s_MTTestModule3; public static byte[] MTTestModule3 => ResourceLoader.GetOrCreateResource(ref s_MTTestModule3, "SymbolsTests.V2.MTTestModule3.netmodule"); } public static class V3 { private static byte[] s_MTTestLib1; public static byte[] MTTestLib1 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib1, "SymbolsTests.V3.MTTestLib1.Dll"); private static string s_MTTestLib1_V3; public static string MTTestLib1_V3 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib1_V3, "SymbolsTests.V3.MTTestLib1_V3.vb"); private static byte[] s_MTTestLib4; public static byte[] MTTestLib4 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib4, "SymbolsTests.V3.MTTestLib4.Dll"); private static string s_MTTestLib4_V3; public static string MTTestLib4_V3 => ResourceLoader.GetOrCreateResource(ref s_MTTestLib4_V3, "SymbolsTests.V3.MTTestLib4_V3.vb"); private static byte[] s_MTTestModule1; public static byte[] MTTestModule1 => ResourceLoader.GetOrCreateResource(ref s_MTTestModule1, "SymbolsTests.V3.MTTestModule1.netmodule"); private static byte[] s_MTTestModule4; public static byte[] MTTestModule4 => ResourceLoader.GetOrCreateResource(ref s_MTTestModule4, "SymbolsTests.V3.MTTestModule4.netmodule"); } public static class WithEvents { private static byte[] s_simpleWithEvents; public static byte[] SimpleWithEvents => ResourceLoader.GetOrCreateResource(ref s_simpleWithEvents, "SymbolsTests.WithEvents.SimpleWithEvents.dll"); } } namespace TestResources { public static class WinRt { private static byte[] s_W1; public static byte[] W1 => ResourceLoader.GetOrCreateResource(ref s_W1, "WinRt.W1.winmd"); private static byte[] s_W2; public static byte[] W2 => ResourceLoader.GetOrCreateResource(ref s_W2, "WinRt.W2.winmd"); private static byte[] s_WB; public static byte[] WB => ResourceLoader.GetOrCreateResource(ref s_WB, "WinRt.WB.winmd"); private static byte[] s_WB_Version1; public static byte[] WB_Version1 => ResourceLoader.GetOrCreateResource(ref s_WB_Version1, "WinRt.WB_Version1.winmd"); private static byte[] s_WImpl; public static byte[] WImpl => ResourceLoader.GetOrCreateResource(ref s_WImpl, "WinRt.WImpl.winmd"); private static byte[] s_windows_dump; public static byte[] Windows_dump => ResourceLoader.GetOrCreateResource(ref s_windows_dump, "WinRt.Windows.ildump"); private static byte[] s_windows_Languages_WinRTTest; public static byte[] Windows_Languages_WinRTTest => ResourceLoader.GetOrCreateResource(ref s_windows_Languages_WinRTTest, "WinRt.Windows.Languages.WinRTTest.winmd"); private static byte[] s_windows; public static byte[] Windows => ResourceLoader.GetOrCreateResource(ref s_windows, "WinRt.Windows.winmd"); private static byte[] s_winMDPrefixing_dump; public static byte[] WinMDPrefixing_dump => ResourceLoader.GetOrCreateResource(ref s_winMDPrefixing_dump, "WinRt.WinMDPrefixing.ildump"); private static byte[] s_winMDPrefixing; public static byte[] WinMDPrefixing => ResourceLoader.GetOrCreateResource(ref s_winMDPrefixing, "WinRt.WinMDPrefixing.winmd"); } }
//------------------------------------------------------------------------------ // <copyright file="ClientBuildManager.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ /************************************************************************************************************/ namespace System.Web.Compilation { using System; using System.CodeDom; using System.CodeDom.Compiler; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.Remoting; using System.Security.Permissions; using System.Threading; using System.Web; using System.Web.Hosting; using System.Web.Util; using Debug = System.Web.Util.Debug; // Flags that drive the behavior of precompilation [Flags] public enum PrecompilationFlags { Default = 0x00000000, // determines whether the deployed app will be updatable Updatable = 0x00000001, // determines whether the target directory can be overwritten OverwriteTarget = 0x00000002, // determines whether the compiler will emit debug information ForceDebug = 0x00000004, // determines whether the application is built clean Clean = 0x00000008, // determines whether the /define:CodeAnalysis flag needs to be added // as compilation symbol CodeAnalysis = 0x00000010, // determines whether to generate APTCA attribute. AllowPartiallyTrustedCallers = 0x00000020, // determines whether to delaySign the generate assemblies. DelaySign = 0x00000040, // determines whether to use fixed assembly names FixedNames = 0x00000080, // determines whether to skip BadImageFormatException IgnoreBadImageFormatException = 0x00000100, } [Serializable] public class ClientBuildManagerParameter { private string _strongNameKeyFile; private string _strongNameKeyContainer; private PrecompilationFlags _precompilationFlags = PrecompilationFlags.Default; private List<string> _excludedVirtualPaths; public List<string> ExcludedVirtualPaths { get { if (_excludedVirtualPaths == null) { _excludedVirtualPaths = new List<string>(); } return _excludedVirtualPaths; } } // Determines the behavior of the precompilation public PrecompilationFlags PrecompilationFlags { get { return _precompilationFlags; } set { _precompilationFlags = value; } } public string StrongNameKeyFile { get { return _strongNameKeyFile; } set { _strongNameKeyFile = value; } } public string StrongNameKeyContainer { get { return _strongNameKeyContainer; } set { _strongNameKeyContainer = value; } } } // // This class provide access to the BuildManager outside of an IIS environment // Instances of this class are created in the caller's App Domain. // // It creates and configures the new App Domain for handling BuildManager calls // using System.Web.Hosting.ApplicationHost.CreateApplicationHost() // [PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)] [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)] public sealed class ClientBuildManager : MarshalByRefObject, IDisposable { private VirtualPath _virtualPath; private string _physicalPath; private string _installPath; private string _appId; private IApplicationHost _appHost; private string _codeGenDir; private HostingEnvironmentParameters _hostingParameters; private ClientBuildManagerTypeDescriptionProviderBridge _cbmTdpBridge; private WaitCallback _onAppDomainUnloadedCallback; private WaitCallback _onAppDomainShutdown; private ApplicationShutdownReason _reason; private BuildManagerHost _host; private Exception _hostCreationException; private bool _hostCreationPending; public event BuildManagerHostUnloadEventHandler AppDomainUnloaded; public event EventHandler AppDomainStarted; public event BuildManagerHostUnloadEventHandler AppDomainShutdown; // internal lock used for host creation. private object _lock = new object(); // Whether to wait for the call back from the previous host unloading before creating a new one private bool _waitForCallBack; private const string IISExpressPrefix = "/IISExpress/"; /* * Creates an instance of the ClientBuildManager. * appPhysicalSourceDir points to the physical root of the application (e.g "c:\myapp") * virtualPath is the virtual path to the app root. It can be anything (e.g. "/dummy"), * but ideally it should match the path later given to Cassini, in order for * compilation that happens here to be reused there. */ public ClientBuildManager(string appVirtualDir, string appPhysicalSourceDir) : this(appVirtualDir, appPhysicalSourceDir, appPhysicalTargetDir: null, parameter: null) { } /* * Creates an instance of the PrecompilationManager. * appPhysicalSourceDir points to the physical root of the application (e.g "c:\myapp") * appVirtualDir is the virtual path to the app root. It can be anything (e.g. "/dummy"), * but ideally it should match the path later given to Cassini, in order for * compilation that happens here to be reused there. * appPhysicalTargetDir is the directory where the precompiled site is placed */ public ClientBuildManager(string appVirtualDir, string appPhysicalSourceDir, string appPhysicalTargetDir) : this(appVirtualDir, appPhysicalSourceDir, appPhysicalTargetDir, parameter: null) { } /* * Creates an instance of the PrecompilationManager. * appPhysicalSourceDir points to the physical root of the application (e.g "c:\myapp") * appVirtualDir is the virtual path to the app root. It can be anything (e.g. "/dummy"), * but ideally it should match the path later given to Cassini, in order for * compilation that happens here to be reused there. * appPhysicalTargetDir is the directory where the precompiled site is placed * flags determines the behavior of the precompilation */ public ClientBuildManager(string appVirtualDir, string appPhysicalSourceDir, string appPhysicalTargetDir, ClientBuildManagerParameter parameter) : this(appVirtualDir, appPhysicalSourceDir, appPhysicalTargetDir, parameter, typeDescriptionProvider: null) { } /* * Creates an instance of the PrecompilationManager. * appPhysicalSourceDir points to the physical root of the application (e.g "c:\myapp") * appVirtualDir is the virtual path to the app root. It can be anything (e.g. "/dummy"), * but ideally it should match the path later given to Cassini, in order for * compilation that happens here to be reused there. * appPhysicalTargetDir is the directory where the precompiled site is placed * typeDescriptionProvider is the provider used for retrieving type * information for multi-targeting */ public ClientBuildManager(string appVirtualDir, string appPhysicalSourceDir, string appPhysicalTargetDir, ClientBuildManagerParameter parameter, TypeDescriptionProvider typeDescriptionProvider) { if (parameter == null) { parameter = new ClientBuildManagerParameter(); } InitializeCBMTDPBridge(typeDescriptionProvider); // Always build clean in precompilation for deployment mode, // since building incrementally raises all kind of issues (VSWhidbey 382954). if (!String.IsNullOrEmpty(appPhysicalTargetDir)) { parameter.PrecompilationFlags |= PrecompilationFlags.Clean; } _hostingParameters = new HostingEnvironmentParameters(); _hostingParameters.HostingFlags = HostingEnvironmentFlags.DontCallAppInitialize | HostingEnvironmentFlags.ClientBuildManager; _hostingParameters.ClientBuildManagerParameter = parameter; _hostingParameters.PrecompilationTargetPhysicalDirectory = appPhysicalTargetDir; if (typeDescriptionProvider != null) { _hostingParameters.HostingFlags |= HostingEnvironmentFlags.SupportsMultiTargeting; } // Make sure the app virtual dir starts with / if (appVirtualDir[0] != '/') appVirtualDir = "/" + appVirtualDir; if (appPhysicalSourceDir == null && appVirtualDir.StartsWith(IISExpressPrefix, StringComparison.OrdinalIgnoreCase) && appVirtualDir.Length > IISExpressPrefix.Length) { // appVirtualDir should have the form "/IISExpress/<version>/LM/W3SVC/", // and we will try to extract the version. The version will be validated // when it is passed to IISVersionHelper..ctor. int endSlash = appVirtualDir.IndexOf('/', IISExpressPrefix.Length); if (endSlash > 0) { _hostingParameters.IISExpressVersion = appVirtualDir.Substring(IISExpressPrefix.Length, endSlash - IISExpressPrefix.Length); appVirtualDir = appVirtualDir.Substring(endSlash); } } Initialize(VirtualPath.CreateNonRelative(appVirtualDir), appPhysicalSourceDir); } /* * returns the codegendir used by runtime appdomain */ public string CodeGenDir { get { if (_codeGenDir == null) { EnsureHostCreated(); _codeGenDir = _host.CodeGenDir; } return _codeGenDir; } } /* * Indicates whether the host is created. */ public bool IsHostCreated { get { return _host != null; } } /* * Create an object in the runtime appdomain */ public IRegisteredObject CreateObject(Type type, bool failIfExists) { if (type == null) { throw new ArgumentNullException("type"); } EnsureHostCreated(); Debug.Assert(_appId != null); Debug.Assert(_appHost != null); _host.RegisterAssembly(type.Assembly.FullName, type.Assembly.Location); ApplicationManager appManager = ApplicationManager.GetApplicationManager(); return appManager.CreateObjectInternal(_appId, type, _appHost, failIfExists, _hostingParameters); } /* * Return the list of directories that would cause appdomain shutdown. */ public string[] GetAppDomainShutdownDirectories() { Debug.Trace("CBM", "GetAppDomainShutdownDirectories"); return FileChangesMonitor.s_dirsToMonitor; } /* * Makes sure that all the top level files are compiled (code, global.asax, ...) */ public void CompileApplicationDependencies() { Debug.Trace("CBM", "CompileApplicationDependencies"); EnsureHostCreated(); _host.CompileApplicationDependencies(); } public IDictionary GetBrowserDefinitions() { Debug.Trace("CBM", "GetBrowserDefinitions"); EnsureHostCreated(); return _host.GetBrowserDefinitions(); } /* * Returns the physical path of the generated file corresponding to the virtual directory. * Note the virtualPath needs to use this format: * "/[appname]/App_WebReferences/{[subDir]/}" */ public string GetGeneratedSourceFile(string virtualPath) { Debug.Trace("CBM", "GetGeneratedSourceFile " + virtualPath); if (virtualPath == null) { throw new ArgumentNullException("virtualPath"); } EnsureHostCreated(); return _host.GetGeneratedSourceFile(VirtualPath.CreateTrailingSlash(virtualPath)); } /* * Returns the virtual path of the corresponding generated file. * Note the filepath needs to be a full path. */ public string GetGeneratedFileVirtualPath(string filePath) { Debug.Trace("CBM", "GetGeneratedFileVirtualPath " + filePath); if (filePath == null) { throw new ArgumentNullException("filePath"); } EnsureHostCreated(); return _host.GetGeneratedFileVirtualPath(filePath); } /* * Returns an array of the virtual paths to all the code directories in the app thru the hosted appdomain */ public string[] GetVirtualCodeDirectories() { Debug.Trace("CBM", "GetHostedVirtualCodeDirectories"); EnsureHostCreated(); return _host.GetVirtualCodeDirectories(); } /* * Returns an array of the assemblies defined in the bin and assembly reference config section */ public String[] GetTopLevelAssemblyReferences(string virtualPath) { Debug.Trace("CBM", "GetHostedVirtualCodeDirectories"); if (virtualPath == null) { throw new ArgumentNullException("virtualPath"); } EnsureHostCreated(); return _host.GetTopLevelAssemblyReferences(VirtualPath.Create(virtualPath)); } /* * Returns the compiler type and parameters that need to be used to build * a given code directory. Also, returns the directory containing all the code * files generated from non-code files in the code directory (e.g. wsdl files) */ public void GetCodeDirectoryInformation(string virtualCodeDir, out Type codeDomProviderType, out CompilerParameters compilerParameters, out string generatedFilesDir) { Debug.Trace("CBM", "GetCodeDirectoryInformation " + virtualCodeDir); if (virtualCodeDir == null) { throw new ArgumentNullException("virtualCodeDir"); } EnsureHostCreated(); _host.GetCodeDirectoryInformation(VirtualPath.CreateTrailingSlash(virtualCodeDir), out codeDomProviderType, out compilerParameters, out generatedFilesDir); Debug.Trace("CBM", "GetCodeDirectoryInformation " + virtualCodeDir + " end"); } /* * Returns the compiler type and parameters that need to be used to build * a given file. */ public void GetCompilerParameters(string virtualPath, out Type codeDomProviderType, out CompilerParameters compilerParameters) { Debug.Trace("CBM", "GetCompilerParameters " + virtualPath); if (virtualPath == null) { throw new ArgumentNullException("virtualPath"); } EnsureHostCreated(); _host.GetCompilerParams(VirtualPath.Create(virtualPath), out codeDomProviderType, out compilerParameters); } /* * Returns the codedom tree and the compiler type/param for a given file. */ public CodeCompileUnit GenerateCodeCompileUnit( string virtualPath, out Type codeDomProviderType, out CompilerParameters compilerParameters, out IDictionary linePragmasTable) { Debug.Trace("CBM", "GenerateCodeCompileUnit " + virtualPath); return GenerateCodeCompileUnit(virtualPath, null, out codeDomProviderType, out compilerParameters, out linePragmasTable); } public CodeCompileUnit GenerateCodeCompileUnit( string virtualPath, String virtualFileString, out Type codeDomProviderType, out CompilerParameters compilerParameters, out IDictionary linePragmasTable) { Debug.Trace("CBM", "GenerateCodeCompileUnit " + virtualPath); if (virtualPath == null) { throw new ArgumentNullException("virtualPath"); } EnsureHostCreated(); return _host.GenerateCodeCompileUnit(VirtualPath.Create(virtualPath), virtualFileString, out codeDomProviderType, out compilerParameters, out linePragmasTable); } public string GenerateCode( string virtualPath, String virtualFileString, out IDictionary linePragmasTable) { Debug.Trace("CBM", "GenerateCode " + virtualPath); if (virtualPath == null) { throw new ArgumentNullException("virtualPath"); } EnsureHostCreated(); return _host.GenerateCode(VirtualPath.Create(virtualPath), virtualFileString, out linePragmasTable); } /* * Returns the compiled type for an input file */ public Type GetCompiledType(string virtualPath) { Debug.Trace("CBM", "GetCompiledType " + virtualPath); if (virtualPath == null) { throw new ArgumentNullException("virtualPath"); } EnsureHostCreated(); string[] typeAndAsemblyName = _host.GetCompiledTypeAndAssemblyName(VirtualPath.Create(virtualPath), null); if (typeAndAsemblyName == null) return null; Assembly a = Assembly.LoadFrom(typeAndAsemblyName[1]); Type t = a.GetType(typeAndAsemblyName[0]); return t; } /* * Compile a file */ public void CompileFile(string virtualPath) { CompileFile(virtualPath, null); } public void CompileFile(string virtualPath, ClientBuildManagerCallback callback) { Debug.Trace("CBM", "CompileFile " + virtualPath); if (virtualPath == null) { throw new ArgumentNullException("virtualPath"); } try { EnsureHostCreated(); _host.GetCompiledTypeAndAssemblyName(VirtualPath.Create(virtualPath), callback); } finally { // DevDiv 180798. We are returning null in ClientBuildManagerCallback.InitializeLifetimeService, // so we need to manually disconnect the instance so that it will be released. if (callback != null) { RemotingServices.Disconnect(callback); } } } /* * Indicates whether an assembly is a code assembly. */ public bool IsCodeAssembly(string assemblyName) { Debug.Trace("CBM", "IsCodeAssembly " + assemblyName); if (assemblyName == null) { throw new ArgumentNullException("assemblyName"); } // EnsureHostCreated(); bool result = _host.IsCodeAssembly(assemblyName); Debug.Trace("CBM", "IsCodeAssembly " + result.ToString()); return result; } public bool Unload() { Debug.Trace("CBM", "Unload"); BuildManagerHost host = _host; if (host != null) { _host = null; return host.UnloadAppDomain(); } return false; } /* * Precompile an application */ public void PrecompileApplication() { PrecompileApplication(null); } /* * Precompile an application with callback support */ public void PrecompileApplication(ClientBuildManagerCallback callback) { PrecompileApplication(callback, false); } public void PrecompileApplication(ClientBuildManagerCallback callback, bool forceCleanBuild) { Debug.Trace("CBM", "PrecompileApplication"); PrecompilationFlags savedFlags = _hostingParameters.ClientBuildManagerParameter.PrecompilationFlags; if (forceCleanBuild) { // If there was a previous host, it will be unloaded by CBM and we will wait for the callback. // If there was no previous host, we don't do any waiting. // DevDiv 46290 _waitForCallBack = _host != null; Debug.Trace("CBM", "Started Unload"); // Unload the existing appdomain so the new one will be created with the clean flag Unload(); _hostingParameters.ClientBuildManagerParameter.PrecompilationFlags = savedFlags | PrecompilationFlags.Clean; WaitForCallBack(); } try { EnsureHostCreated(); _host.PrecompileApp(callback, _hostingParameters.ClientBuildManagerParameter.ExcludedVirtualPaths); } finally { if (forceCleanBuild) { // Revert precompilationFlags _hostingParameters.ClientBuildManagerParameter.PrecompilationFlags = savedFlags; } // DevDiv 180798. We are returning null in ClientBuildManagerCallback.InitializeLifetimeService, // so we need to manually disconnect the instance so that it will be released. if (callback != null) { RemotingServices.Disconnect(callback); } } } // _waitForCallBack is set to false in OnAppDomainUnloaded. // This method waits until it is set to false before continuing, so that // we do not run into a concurrency issue where _host could be set to null. // DevDiv 46290 private void WaitForCallBack() { Debug.Trace("CBM", "WaitForCallBack"); int waited = 0; while (_waitForCallBack && waited <= 50) { Thread.Sleep(200); waited++; } if (_waitForCallBack) { Debug.Trace("CBM", "timeout while waiting for callback"); } else { Debug.Trace("CBM", "callback received before timeout"); } } public override Object InitializeLifetimeService() { return null; // never expire lease } internal void Initialize(VirtualPath virtualPath, string physicalPath) { Debug.Trace("CBM", "Initialize"); _virtualPath = virtualPath; _physicalPath = FileUtil.FixUpPhysicalDirectory(physicalPath); _onAppDomainUnloadedCallback = new WaitCallback(OnAppDomainUnloadedCallback); _onAppDomainShutdown = new WaitCallback(OnAppDomainShutdownCallback); _installPath = RuntimeEnvironment.GetRuntimeDirectory(); // Do not create host during intialization. It will be done on demand. //CreateHost(); } private void EnsureHostCreated() { if (_host == null) { lock (_lock) { // Create the host if necessary if (_host == null) { CreateHost(); Debug.Trace("CBM", "EnsureHostCreated: after CreateHost()"); } } } // If an exception happened during host creation, rethrow it if (_hostCreationException != null) { Debug.Trace("CBM", "EnsureHostCreated: failed. " + _hostCreationException); // We need to wrap it in a new exception, otherwise we lose the original stack. throw new HttpException(_hostCreationException.Message, _hostCreationException); } } private void CreateHost() { Debug.Trace("CBM", "CreateHost"); Debug.Assert(_host == null); Debug.Assert(!_hostCreationPending, "CreateHost: creation already pending"); _hostCreationPending = true; // Use a local to avoid having a partially created _host BuildManagerHost host = null; try { string appId; IApplicationHost appHost; ApplicationManager appManager = ApplicationManager.GetApplicationManager(); host = (BuildManagerHost) appManager.CreateObjectWithDefaultAppHostAndAppId( _physicalPath, _virtualPath, typeof(BuildManagerHost), false /*failIfExists*/, _hostingParameters, out appId, out appHost); // host appdomain cannot be unloaded during creation. host.AddPendingCall(); host.Configure(this); _host = host; _appId = appId; _appHost = appHost; _hostCreationException = _host.InitializationException; } catch (Exception e) { // If an exception happens, keep track of it _hostCreationException = e; // Even though the host initialization failed, keep track of it so subsequent // request will see the error _host = host; } finally { _hostCreationPending = false; if (host != null) { // Notify the client that the host is ready if (AppDomainStarted != null) { AppDomainStarted(this, EventArgs.Empty); } // The host can be unloaded safely now. host.RemovePendingCall(); } } Debug.Trace("CBM", "CreateHost LEAVE"); } // Called by BuildManagerHost when the ASP appdomain is unloaded internal void OnAppDomainUnloaded(ApplicationShutdownReason reason) { Debug.Trace("CBM", "OnAppDomainUnloaded " + reason.ToString()); _reason = reason; _waitForCallBack = false; // Don't do anything that can be slow here. Instead queue in a worker thread ThreadPool.QueueUserWorkItem(_onAppDomainUnloadedCallback); } internal void ResetHost() { lock (_lock) { // Though _appId and _appHost are created along with _host, // we need not reset those here as they always correspond to // default app id and app host. _host = null; _hostCreationException = null; } } [PermissionSet(SecurityAction.Assert, Unrestricted = true)] private void OnAppDomainUnloadedCallback(Object unused) { Debug.Trace("CBM", "OnAppDomainUnloadedCallback"); // Notify the client that the appdomain is unloaded if (AppDomainUnloaded != null) { AppDomainUnloaded(this, new BuildManagerHostUnloadEventArgs(_reason)); } } [PermissionSet(SecurityAction.Assert, Unrestricted = true)] private void OnAppDomainShutdownCallback(Object o) { if (AppDomainShutdown != null) { AppDomainShutdown(this, new BuildManagerHostUnloadEventArgs((ApplicationShutdownReason)o)); } } internal void OnAppDomainShutdown(ApplicationShutdownReason reason) { // Don't do anything that can be slow here. Instead queue in a worker thread ThreadPool.QueueUserWorkItem(_onAppDomainShutdown, reason); } private void InitializeCBMTDPBridge(TypeDescriptionProvider typeDescriptionProvider) { if (typeDescriptionProvider == null){ return; } _cbmTdpBridge = new ClientBuildManagerTypeDescriptionProviderBridge(typeDescriptionProvider); } internal ClientBuildManagerTypeDescriptionProviderBridge CBMTypeDescriptionProviderBridge { get { return _cbmTdpBridge; } } #region IDisposable //Dispose the runtime appdomain properly when CBM is disposed void IDisposable.Dispose() { Unload(); } #endregion } [PermissionSet(SecurityAction.LinkDemand, Unrestricted = true)] [PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)] public class BuildManagerHostUnloadEventArgs : EventArgs { ApplicationShutdownReason _reason; public BuildManagerHostUnloadEventArgs(ApplicationShutdownReason reason) { _reason = reason; } // Get the reason for the hosted appdomain shutdown public ApplicationShutdownReason Reason { get { return _reason; } } } public delegate void BuildManagerHostUnloadEventHandler(object sender, BuildManagerHostUnloadEventArgs e); /* * Type of the entries in the table returned by GenerateCodeCompileUnit */ [Serializable] public sealed class LinePragmaCodeInfo { public LinePragmaCodeInfo() { } public LinePragmaCodeInfo(int startLine, int startColumn, int startGeneratedColumn, int codeLength, bool isCodeNugget) { this._startLine = startLine; this._startColumn = startColumn; this._startGeneratedColumn = startGeneratedColumn; this._codeLength = codeLength; this._isCodeNugget = isCodeNugget; } // Starting line in ASPX file internal int _startLine; public int StartLine { get { return _startLine; } } // Starting column in the ASPX file internal int _startColumn; public int StartColumn { get { return _startColumn; } } // Starting column in the generated source file (assuming no indentations are used) internal int _startGeneratedColumn; public int StartGeneratedColumn { get { return _startGeneratedColumn; } } // Length of the code snippet internal int _codeLength; public int CodeLength { get { return _codeLength; } } // Whether the script block is a nugget. internal bool _isCodeNugget; public bool IsCodeNugget { get { return _isCodeNugget; } } } }
using System; using System.Diagnostics; namespace OTFontFile.OTL { public class ScriptListTable { /************************ * constructor */ public ScriptListTable(ushort offset, MBOBuffer bufTable) { m_offsetScriptListTable = offset; m_bufTable = bufTable; } /************************ * field offset values */ public enum FieldOffsets { ScriptCount = 0, ScriptRecords = 2 } /************************ * accessors */ public ushort ScriptCount { get {return m_bufTable.GetUshort(m_offsetScriptListTable + (uint)FieldOffsets.ScriptCount);} } public class ScriptRecord { public OTTag ScriptTag; public ushort ScriptTableOffset; } public ScriptRecord GetScriptRecord(uint i) { ScriptRecord sr = null; if (i < ScriptCount) { uint offset = m_offsetScriptListTable + (uint)FieldOffsets.ScriptRecords + i*6; sr = new ScriptRecord(); sr.ScriptTag = m_bufTable.GetTag(offset); sr.ScriptTableOffset = m_bufTable.GetUshort(offset+4); } return sr; } public virtual ScriptTable GetScriptTable(ScriptRecord sr) { return new ScriptTable((ushort)(m_offsetScriptListTable + sr.ScriptTableOffset), m_bufTable); } /************************ * member data */ protected ushort m_offsetScriptListTable; protected MBOBuffer m_bufTable; } public class ScriptTable { /************************ * constructor */ public ScriptTable(ushort offset, MBOBuffer bufTable) { m_offsetScriptTable = offset; m_bufTable = bufTable; } /************************ * field offset values */ public enum FieldOffsets { DefaultLangSysOffset = 0, LangSysCount = 2, LangSysRecord = 4 } /************************ * accessors */ public ushort DefaultLangSysOffset { get {return m_bufTable.GetUshort(m_offsetScriptTable + (uint)FieldOffsets.DefaultLangSysOffset);} } public ushort LangSysCount { get {return m_bufTable.GetUshort(m_offsetScriptTable + (uint)FieldOffsets.LangSysCount);} } public class LangSysRecord { public OTTag LangSysTag; public ushort LangSysOffset; } public LangSysRecord GetLangSysRecord(uint i) { LangSysRecord lsr = null; if (i < LangSysCount) { uint offset = m_offsetScriptTable + (uint)FieldOffsets.LangSysRecord + i*6; lsr = new LangSysRecord(); lsr.LangSysTag = m_bufTable.GetTag(offset); lsr.LangSysOffset = m_bufTable.GetUshort(offset+4); } return lsr; } public virtual LangSysTable GetDefaultLangSysTable() { LangSysTable lst = null; if (DefaultLangSysOffset != 0) { lst = new LangSysTable((ushort)(m_offsetScriptTable + DefaultLangSysOffset), m_bufTable);; } return lst; } public virtual LangSysTable GetLangSysTable(LangSysRecord lsr) { return new LangSysTable((ushort)(m_offsetScriptTable + lsr.LangSysOffset), m_bufTable); } /************************ * member data */ protected ushort m_offsetScriptTable; protected MBOBuffer m_bufTable; } public class LangSysTable { /************************ * constructor */ public LangSysTable(ushort offset, MBOBuffer bufTable) { m_offsetLangSysTable = offset; m_bufTable = bufTable; } /************************ * field offset values */ public enum FieldOffsets { LookupOrder = 0, ReqFeatureIndex = 2, FeatureCount = 4, FeatureIndexArray = 6 } /************************ * accessors */ public ushort LookupOrder { get {return m_bufTable.GetUshort(m_offsetLangSysTable + (uint)FieldOffsets.LookupOrder);} } public ushort ReqFeatureIndex { get {return m_bufTable.GetUshort(m_offsetLangSysTable + (uint)FieldOffsets.ReqFeatureIndex);} } public ushort FeatureCount { get {return m_bufTable.GetUshort(m_offsetLangSysTable + (uint)FieldOffsets.FeatureCount);} } public ushort GetFeatureIndex(uint i) { uint offset = m_offsetLangSysTable + (uint)FieldOffsets.FeatureIndexArray + i*2; return m_bufTable.GetUshort(offset); } /************************ * member data */ protected ushort m_offsetLangSysTable; protected MBOBuffer m_bufTable; } public class FeatureListTable { /************************ * constructor */ public FeatureListTable(ushort offset, MBOBuffer bufTable) { m_offsetFeatureListTable = offset; m_bufTable = bufTable; } /************************ * field offset values */ public enum FieldOffsets { FeatureCount = 0, FeatureRecordArray = 2 } /************************ * accessors */ public ushort FeatureCount { get {return m_bufTable.GetUshort(m_offsetFeatureListTable + (uint)FieldOffsets.FeatureCount);} } public class FeatureRecord { public OTTag FeatureTag; public ushort FeatureTableOffset; } public FeatureRecord GetFeatureRecord(uint i) { FeatureRecord fr = null; if (i < FeatureCount) { uint offset = m_offsetFeatureListTable + (uint)FieldOffsets.FeatureRecordArray + i*6; if (offset+6 <= m_bufTable.GetLength()) { fr = new FeatureRecord(); fr.FeatureTag = m_bufTable.GetTag(offset); fr.FeatureTableOffset = m_bufTable.GetUshort(offset + 4); } } return fr; } public virtual FeatureTable GetFeatureTable(FeatureRecord fr) { return new FeatureTable((ushort)(m_offsetFeatureListTable + fr.FeatureTableOffset), m_bufTable); } /************************ * member data */ protected ushort m_offsetFeatureListTable; protected MBOBuffer m_bufTable; } public class FeatureTable { /************************ * constructor */ public FeatureTable(ushort offset, MBOBuffer bufTable) { m_offsetFeatureTable = offset; m_bufTable = bufTable; } /************************ * field offset values */ public enum FieldOffsets { FeatureParams = 0, LookupCount = 2, LookupListIndexArray = 4 } /************************ * accessors */ public ushort FeatureParams { get {return m_bufTable.GetUshort(m_offsetFeatureTable + (uint)FieldOffsets.FeatureParams);} } public ushort LookupCount { get {return m_bufTable.GetUshort(m_offsetFeatureTable + (uint)FieldOffsets.LookupCount);} } public ushort GetLookupListIndex(uint i) { uint offset = m_offsetFeatureTable + (uint)FieldOffsets.LookupListIndexArray + i*2; return m_bufTable.GetUshort(offset); } /************************ * member data */ protected ushort m_offsetFeatureTable; protected MBOBuffer m_bufTable; } public class LookupListTable { /************************ * constructor */ public LookupListTable(ushort offset, MBOBuffer bufTable, OTTag tag) { m_offsetLookupListTable = offset; m_bufTable = bufTable; m_tag = tag; } /************************ * field offset values */ public enum FieldOffsets { LookupCount = 0, LookupArray = 2 } /************************ * accessors */ public ushort LookupCount { get {return m_bufTable.GetUshort(m_offsetLookupListTable + (uint)FieldOffsets.LookupCount);} } public ushort GetLookupOffset(uint i) { return m_bufTable.GetUshort(m_offsetLookupListTable + (uint)FieldOffsets.LookupArray + i*2); } public virtual LookupTable GetLookupTable(uint i) { LookupTable lt = null; if (i < LookupCount) { ushort offset = (ushort)(m_offsetLookupListTable + GetLookupOffset(i)); if (offset + 6 <= m_bufTable.GetLength()) // minimum lookuptable with zero entries is six bytes { lt = new LookupTable(offset, m_bufTable, m_tag); } } return lt; } /************************ * member data */ protected ushort m_offsetLookupListTable; protected MBOBuffer m_bufTable; protected OTTag m_tag; } public class LookupTable { /************************ * constructor */ public LookupTable(ushort offset, MBOBuffer bufTable, OTTag tag) { m_offsetLookupTable = offset; m_bufTable = bufTable; m_tag = tag; } /************************ * field offset values */ public enum FieldOffsets { LookupType = 0, LookupFlag = 2, SubTableCount = 4, SubTableOffsetArray = 6 } /************************ * accessors */ public ushort LookupType { get {return m_bufTable.GetUshort(m_offsetLookupTable + (uint)FieldOffsets.LookupType);} } public ushort LookupFlag { get {return m_bufTable.GetUshort(m_offsetLookupTable + (uint)FieldOffsets.LookupFlag);} } public ushort SubTableCount { get {return m_bufTable.GetUshort(m_offsetLookupTable + (uint)FieldOffsets.SubTableCount);} } public ushort GetSubTableOffset(uint i) { if (i >= SubTableCount) { throw new ArgumentOutOfRangeException(); } return m_bufTable.GetUshort(m_offsetLookupTable + (uint)FieldOffsets.SubTableOffsetArray + i*2); } public virtual SubTable GetSubTable(uint i) { if (i >= SubTableCount) { throw new ArgumentOutOfRangeException(); } SubTable st = null; uint stOffset = m_offsetLookupTable + (uint)GetSubTableOffset(i); if ((string)m_tag == "GPOS") { switch (LookupType) { case 1: st = new Table_GPOS.SinglePos (stOffset, m_bufTable); break; case 2: st = new Table_GPOS.PairPos (stOffset, m_bufTable); break; case 3: st = new Table_GPOS.CursivePos (stOffset, m_bufTable); break; case 4: st = new Table_GPOS.MarkBasePos (stOffset, m_bufTable); break; case 5: st = new Table_GPOS.MarkLigPos (stOffset, m_bufTable); break; case 6: st = new Table_GPOS.MarkMarkPos (stOffset, m_bufTable); break; case 7: st = new Table_GPOS.ContextPos (stOffset, m_bufTable); break; case 8: st = new Table_GPOS.ChainContextPos(stOffset, m_bufTable); break; case 9: st = new Table_GPOS.ExtensionPos (stOffset, m_bufTable); break; } } else if ((string)m_tag == "GSUB") { switch (LookupType) { case 1: st = new Table_GSUB.SingleSubst (stOffset, m_bufTable); break; case 2: st = new Table_GSUB.MultipleSubst (stOffset, m_bufTable); break; case 3: st = new Table_GSUB.AlternateSubst (stOffset, m_bufTable); break; case 4: st = new Table_GSUB.LigatureSubst (stOffset, m_bufTable); break; case 5: st = new Table_GSUB.ContextSubst (stOffset, m_bufTable); break; case 6: st = new Table_GSUB.ChainContextSubst(stOffset, m_bufTable); break; case 7: st = new Table_GSUB.ExtensionSubst (stOffset, m_bufTable); break; case 8: st = new Table_GSUB.ReverseChainSubst(stOffset, m_bufTable); break; } } else { throw new InvalidOperationException("unknown table type"); } return st; } /************************ * member data */ protected ushort m_offsetLookupTable; protected MBOBuffer m_bufTable; protected OTTag m_tag; } public abstract class SubTable { public SubTable(uint offset, MBOBuffer bufTable) { m_offsetSubTable = offset; m_bufTable = bufTable; } // this is needed for calculating OS2.usMaxContext public abstract uint GetMaxContextLength(); protected uint m_offsetSubTable; protected MBOBuffer m_bufTable; } public class CoverageTable { /************************ * constructor */ public CoverageTable(uint offset, MBOBuffer bufTable) { m_offsetCoverageTable = offset; m_bufTable = bufTable; } /************************ * field offset values */ public enum FieldOffsets { CoverageFormat = 0 } public enum FieldOffsets1 { GlyphCount = 2, GlyphArray = 4 } public enum FieldOffsets2 { RangeCount = 2, RangeRecordArray = 4 } /************************ * accessors */ public ushort CoverageFormat { get {return m_bufTable.GetUshort(m_offsetCoverageTable + (uint)FieldOffsets.CoverageFormat);} } // format 1 only! public ushort F1GlyphCount { get { if (CoverageFormat != 1) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort(m_offsetCoverageTable + (uint)FieldOffsets1.GlyphCount); } } public ushort F1GetGlyphID(uint iPos) { if (CoverageFormat != 1) { throw new System.InvalidOperationException(); } uint offset = m_offsetCoverageTable + (uint)FieldOffsets1.GlyphArray + iPos*2; return m_bufTable.GetUshort(offset); } // format 2 only! public ushort F2RangeCount { get { if (CoverageFormat != 2) { throw new System.InvalidOperationException(); } return m_bufTable.GetUshort(m_offsetCoverageTable + (uint)FieldOffsets2.RangeCount); } } public RangeRecord F2GetRangeRecord(uint i) { if (CoverageFormat != 2) { throw new System.InvalidOperationException(); } RangeRecord rr = null; if (i < F2RangeCount) { rr = new RangeRecord(); uint rrOffset = m_offsetCoverageTable + (uint)FieldOffsets2.RangeRecordArray + i*6; rr.Start = m_bufTable.GetUshort(rrOffset); rr.End = m_bufTable.GetUshort(rrOffset + 2); rr.StartCoverageIndex = m_bufTable.GetUshort(rrOffset + 4); } return rr; } public class RangeRecord { public ushort Start; public ushort End; public ushort StartCoverageIndex; } // either format public CoverageResults GetGlyphCoverage(ushort nGlyph) { CoverageResults cr; cr.bCovered = false; cr.CoverageIndex = 0; if (CoverageFormat == 1) { ushort count = F1GlyphCount; for (ushort i=0; i<count; i++) { if (nGlyph == F1GetGlyphID(i)) { cr.bCovered = true; cr.CoverageIndex = i; break; } } } else if (CoverageFormat == 2) { ushort FirstIndexOfRange = 0; for (uint i=0; i<F2RangeCount; i++) { RangeRecord rr = F2GetRangeRecord(i); if (nGlyph >= rr.Start && nGlyph <= rr.End) { cr.bCovered = true; cr.CoverageIndex = (ushort)(FirstIndexOfRange + nGlyph - rr.Start); break; } FirstIndexOfRange += (ushort)(rr.End-rr.Start+1); } } else { Debug.Assert(false); } return cr; } public struct CoverageResults { public bool bCovered; public ushort CoverageIndex; } /************************ * member data */ protected uint m_offsetCoverageTable; protected MBOBuffer m_bufTable; } public class ClassDefTable { /************************ * constructor */ public ClassDefTable(uint offset, MBOBuffer bufTable) { m_offsetClassDefTable = offset; m_bufTable = bufTable; } /************************ * field offset values */ public enum FieldOffsets { ClassFormat = 0 } /************************ * nested classes */ protected class ClassDefFormat1 { public ClassDefFormat1(uint offset, MBOBuffer bufTable) { m_offsetClassDefFormat1 = offset; m_bufTable = bufTable; } public enum FieldOffsets { ClassFormat = 0, StartGlyph = 2, GlyphCount = 4, ClassValueArray = 6 } public ushort ClassFormat { get {return m_bufTable.GetUshort(m_offsetClassDefFormat1 + (uint)FieldOffsets.ClassFormat);} } public ushort StartGlyph { get {return m_bufTable.GetUshort(m_offsetClassDefFormat1 + (uint)FieldOffsets.StartGlyph);} } public ushort GlyphCount { get {return m_bufTable.GetUshort(m_offsetClassDefFormat1 + (uint)FieldOffsets.GlyphCount);} } public ushort GetClassValue(uint i) { ushort val = 0; ushort start = StartGlyph; ushort count = GlyphCount; if (i >= start && i < start + count) { uint index = i - start; uint ArrayOffset = m_offsetClassDefFormat1 + (uint)FieldOffsets.ClassValueArray; val = m_bufTable.GetUshort(ArrayOffset + index*2); } return val; } protected uint m_offsetClassDefFormat1; protected MBOBuffer m_bufTable; } protected class ClassDefFormat2 { public ClassDefFormat2(uint offset, MBOBuffer bufTable) { m_offsetClassDefFormat2 = offset; m_bufTable = bufTable; } public enum FieldOffsets { ClassFormat = 0, ClassRangeCount = 2, ClassRangeRecordArray = 4 } public ushort ClassFormat { get {return m_bufTable.GetUshort(m_offsetClassDefFormat2 + (uint)FieldOffsets.ClassFormat);} } public ushort ClassRangeCount { get {return m_bufTable.GetUshort(m_offsetClassDefFormat2 + (uint)FieldOffsets.ClassRangeCount);} } public ClassRangeRecord GetClassRangeRecord(uint i) { ClassRangeRecord crr = null; if (i < ClassRangeCount) { crr = new ClassRangeRecord(); uint crrOffset = m_offsetClassDefFormat2 + (uint)FieldOffsets.ClassRangeRecordArray + i*6; crr.Start = m_bufTable.GetUshort(crrOffset); crr.End = m_bufTable.GetUshort(crrOffset + 2); crr.Class = m_bufTable.GetUshort(crrOffset + 4); } return crr; } public class ClassRangeRecord { public ushort Start; public ushort End; public ushort Class; } protected uint m_offsetClassDefFormat2; protected MBOBuffer m_bufTable; } /************************ * accessors */ public ushort ClassFormat { get {return m_bufTable.GetUshort(m_offsetClassDefTable + (uint)FieldOffsets.ClassFormat);} } ClassDefFormat1 GetClassDefFormat1() { return new ClassDefFormat1(m_offsetClassDefTable, m_bufTable); } ClassDefFormat2 GetClassDefFormat2() { return new ClassDefFormat2(m_offsetClassDefTable, m_bufTable); } // get class value for a given glyph for either format public ushort GetClassValue(ushort nGlyph) { ushort val = 0; if (ClassFormat == 1) { ClassDefFormat1 cdf1 = GetClassDefFormat1(); val = cdf1.GetClassValue(nGlyph); } else if (ClassFormat == 2) { ClassDefFormat2 cdf2 = GetClassDefFormat2(); for (uint i=0; i<cdf2.ClassRangeCount; i++) { ClassDefFormat2.ClassRangeRecord crr = cdf2.GetClassRangeRecord(i); if (nGlyph >= crr.Start && nGlyph <= crr.End) { val = crr.Class; break; } } } else { Debug.Assert(false); } return val; } /************************ * member data */ protected uint m_offsetClassDefTable; protected MBOBuffer m_bufTable; } public class DeviceTable { public DeviceTable(uint offset, MBOBuffer bufTable) { m_offsetDeviceTable = offset; m_bufTable = bufTable; } public enum FieldOffsets { StartSize = 0, EndSize = 2, DeltaFormat = 4, DeltaValueArray = 6 } public ushort StartSize { get {return m_bufTable.GetUshort(m_offsetDeviceTable + (uint)FieldOffsets.StartSize);} } public ushort EndSize { get {return m_bufTable.GetUshort(m_offsetDeviceTable + (uint)FieldOffsets.EndSize);} } public ushort DeltaFormat { get {return m_bufTable.GetUshort(m_offsetDeviceTable + (uint)FieldOffsets.DeltaFormat);} } public ushort GetDeltaValueUint(uint i) { uint offset = m_offsetDeviceTable + (uint)FieldOffsets.DeltaValueArray + i*2; return m_bufTable.GetUshort(offset); } public uint m_offsetDeviceTable; public MBOBuffer m_bufTable; } }
using Abp.Application.Services.Dto; using Abp.Authorization; using Abp.AutoMapper; using Abp.Domain.Uow; using Abp.Extensions; using Abp.MultiTenancy; using Abp.Runtime.Security; using Abp.UI; using Castle.Components.DictionaryAdapter; using Cinotam.AbpModuleZero.Authorization; using Cinotam.AbpModuleZero.Authorization.Roles; using Cinotam.AbpModuleZero.Editions; using Cinotam.AbpModuleZero.MultiTenancy; using Cinotam.AbpModuleZero.Tools.DatatablesJsModels.GenericTypes; using Cinotam.AbpModuleZero.Users; using Cinotam.ModuleZero.AppModule.Features.Dto; using Cinotam.ModuleZero.AppModule.Features.FeatureManager; using Cinotam.ModuleZero.AppModule.MultiTenancy.Dto; using Cinotam.ModuleZero.Notifications.MultiTenancyNotifications.Sender; using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using System.Threading.Tasks; namespace Cinotam.ModuleZero.AppModule.MultiTenancy { [AbpAuthorize(PermissionNames.PagesTenants)] public class TenantAppService : CinotamModuleZeroAppServiceBase, ITenantAppService { private readonly RoleManager _roleManager; private readonly EditionManager _editionManager; private readonly IAbpZeroDbMigrator _abpZeroDbMigrator; private readonly ICustomEditionManager _customEditionManager; private readonly IMultitenancyNotificationSender _multitenancyNotificationSender; public TenantAppService( RoleManager roleManager, EditionManager editionManager, IAbpZeroDbMigrator abpZeroDbMigrator, ICustomEditionManager customEditionManager, IMultitenancyNotificationSender multitenancyNotificationSender) { _roleManager = roleManager; _editionManager = editionManager; _abpZeroDbMigrator = abpZeroDbMigrator; _customEditionManager = customEditionManager; _multitenancyNotificationSender = multitenancyNotificationSender; } public ListResultDto<TenantListDto> GetTenants() { return new ListResultDto<TenantListDto>( TenantManager.Tenants .OrderBy(t => t.TenancyName) .ToList() .MapTo<List<TenantListDto>>() ); } public async Task SetFeatureValuesForTenant(CustomEditionInput input) { if (AbpSession.TenantId == null) { CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.MustHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete); } var tenant = await TenantManager.GetByIdAsync(input.TenantId); foreach (var inputFeature in input.Features) { await TenantManager.SetFeatureValueAsync(tenant, inputFeature.Name, inputFeature.DefaultValue); } await CurrentUnitOfWork.SaveChangesAsync(); } public async Task<CustomEditionInput> GetFeaturesForTenant(int tenantId) { if (AbpSession.TenantId == null) { CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.MustHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete); } var tenant = await TenantManager.GetByIdAsync(tenantId); if (tenant.EditionId == null) throw new UserFriendlyException(L("NoEditionIsSetForTenant")); var edition = await _editionManager.FindByIdAsync(tenant.EditionId.Value); var mapped = edition.MapTo<CustomEditionInput>(); mapped.TenantId = tenantId; mapped.Features = await _customEditionManager.GetAllFeatures(edition.Id, tenantId); return mapped; } public async Task ResetFeatures(int tenantId) { if (AbpSession.TenantId == null) { CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.MustHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete); } var tenant = await TenantManager.GetByIdAsync(tenantId); if (tenant.EditionId == null) throw new UserFriendlyException(L("NoEditionIsSetForTenant")); var editionFeatures = await _editionManager.GetFeatureValuesAsync(tenant.EditionId.Value); await TenantManager.SetFeatureValuesAsync(tenantId, editionFeatures.ToArray()); //await _multitenancyNotificationSender.SendTenantFeaturesChanged(tenant); } public ReturnModel<TenantListDto> GetTenantsTable(RequestModel<object> input) { if (AbpSession.TenantId == null) { CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.MustHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete); } int count; var query = TenantManager.Tenants; List<Expression<Func<Tenant, string>>> searchs = new EditableList<Expression<Func<Tenant, string>>>(); searchs.Add(a => a.Name); searchs.Add(a => a.TenancyName); var filteredByLength = GenerateTableModel(input, query, searchs, "Id", out count); return new ReturnModel<TenantListDto>() { iTotalDisplayRecords = count, recordsTotal = query.Count(), recordsFiltered = filteredByLength.Count, length = input.length, data = filteredByLength.Select(a => a.MapTo<TenantListDto>()).ToArray(), draw = input.draw, }; } public async Task<TenantViewModel> GetTenantViewModel(int tenantId) { if (AbpSession.TenantId == null) { CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.MustHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete); } var tenant = await TenantManager.GetByIdAsync(tenantId); return tenant.MapTo<TenantViewModel>(); } public async Task<EditionsForTenantOutput> GetEditionsForTenant(int tenantId) { if (AbpSession.TenantId == null) { CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.MustHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete); } var allEditions = _editionManager.Editions.ToList(); var editionCList = new List<EditionDtoCustom>(); foreach (var allEdition in allEditions) { var mappedEdition = allEdition.MapTo<EditionDtoCustom>(); mappedEdition.IsEnabledForTenant = await IsThisEditionActive(tenantId, allEdition.Id); editionCList.Add(mappedEdition); } return new EditionsForTenantOutput() { Editions = editionCList, TenantId = tenantId }; } private async Task<bool> IsThisEditionActive(int tenantId, int editionId) { var tenant = await TenantManager.GetByIdAsync(tenantId); return tenant.EditionId == editionId; } public async Task SetTenantEdition(SetTenantEditionInput input) { if (AbpSession.TenantId == null) { CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.MustHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete); } var tenant = await TenantManager.GetByIdAsync(input.TenantId); var edition = await _editionManager.FindByIdAsync(input.EditionId); if (edition != null) { tenant.EditionId = edition.Id; } await CurrentUnitOfWork.SaveChangesAsync(); //await _multitenancyNotificationSender.SendTenantEditionChanged(tenant, edition); } public async Task CreateTenant(CreateTenantInput input) { //Create tenant var tenant = input.MapTo<Tenant>(); tenant.ConnectionString = input.ConnectionString.IsNullOrEmpty() ? null : SimpleStringCipher.Instance.Encrypt(input.ConnectionString); var defaultEdition = await _editionManager.FindByNameAsync(EditionManager.DefaultEditionName); if (defaultEdition != null) { tenant.EditionId = defaultEdition.Id; } CheckErrors(await TenantManager.CreateAsync(tenant)); await CurrentUnitOfWork.SaveChangesAsync(); //To get new tenant's id. //Create tenant database _abpZeroDbMigrator.CreateOrMigrateForTenant(tenant); //We are working entities of new tenant, so changing tenant filter using (CurrentUnitOfWork.SetTenantId(tenant.Id)) { //Create static roles for new tenant CheckErrors(await _roleManager.CreateStaticRoles(tenant.Id)); await CurrentUnitOfWork.SaveChangesAsync(); //To get static role ids //grant all permissions to admin role var adminRole = _roleManager.Roles.Single(r => r.Name == StaticRoleNames.Tenants.Admin); await _roleManager.GrantAllPermissionsAsync(adminRole); //Create admin user for the tenant var adminUser = User.CreateTenantAdminUser(tenant.Id, input.AdminEmailAddress, User.DefaultPassword); CheckErrors(await UserManager.CreateAsync(adminUser)); await CurrentUnitOfWork.SaveChangesAsync(); //To get admin user's id //Assign admin user to role! CheckErrors(await UserManager.AddToRoleAsync(adminUser.Id, adminRole.Name)); await CurrentUnitOfWork.SaveChangesAsync(); await _multitenancyNotificationSender.SendTenantCreatedNotification(tenant, await GetCurrentUserAsync()); } } public async Task DeleteTenant(int tenantId) { var tenant = await TenantManager.FindByIdAsync(tenantId); await TenantManager.DeleteAsync(tenant); await _multitenancyNotificationSender.SendDeletedNotification(tenant, await GetCurrentUserAsync()); } public async Task RestoreTenant(int tenantId) { if (AbpSession.TenantId == null) { CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.MustHaveTenant); CurrentUnitOfWork.DisableFilter(AbpDataFilters.SoftDelete); } var tenant = await TenantManager.FindByIdAsync(tenantId); tenant.IsDeleted = false; await TenantManager.UpdateAsync(tenant); await _multitenancyNotificationSender.SendTenantRestoredNotification(tenant, await GetCurrentUserAsync()); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Text; using System.Collections.Generic; using System.Composition; using System.Composition.Hosting; using System.Composition.Hosting.Providers; using System.Linq; using Xunit; namespace System.Composition.UnitTests { public interface ISharedTestingClass { void Method(); } [Export(typeof(ISharedTestingClass))] public class NonSharedClass : ISharedTestingClass { [ImportingConstructor] public NonSharedClass() { } public void Method() { } } [Export(typeof(ISharedTestingClass))] [Shared] public class SharedClass : ISharedTestingClass { [ImportingConstructor] public SharedClass() { } public void Method() { } } [Export] [Shared] public class ClassWithExportFactoryShared { private readonly ExportFactory<ISharedTestingClass> _fact; [ImportingConstructor] public ClassWithExportFactoryShared(ExportFactory<ISharedTestingClass> factory) { _fact = factory; } public ISharedTestingClass Method() { using (var b = _fact.CreateExport()) { return b.Value; } } } [Export] public class ClassWithExportFactoryNonShared { private readonly ExportFactory<ISharedTestingClass> _fact; [ImportingConstructor] public ClassWithExportFactoryNonShared(ExportFactory<ISharedTestingClass> factory) { _fact = factory; } public ISharedTestingClass Method() { using (var b = _fact.CreateExport()) { return b.Value; } } } [Export] public class ClassWithExportFactoryAsAProperty { [Import] public ExportFactory<ISharedTestingClass> _fact { get; set; } public ClassWithExportFactoryAsAProperty() { } public ISharedTestingClass Method() { using (var b = _fact.CreateExport()) { return b.Value; } } } internal interface IX { } internal interface IY { } [Export] [Shared("Boundary")] public class A { public int SharedState { get; set; } } [Export] public class B { public A InstanceA { get; set; } public D InstanceD { get; set; } [ImportingConstructor] public B(A a, D d) { InstanceA = a; InstanceD = d; } } [Export] public class D { public A InstanceA; [ImportingConstructor] public D(A a) { InstanceA = a; } } [Export] public class C { private readonly ExportFactory<B> _fact; [ImportingConstructor] public C([SharingBoundary("Boundary")]ExportFactory<B> fact) { _fact = fact; } public B CreateInstance() { using (var b = _fact.CreateExport()) { return b.Value; } } } [Export] public class CPrime { private readonly ExportFactory<B> _fact; [ImportingConstructor] public CPrime(ExportFactory<B> fact) { _fact = fact; } public B CreateInstance() { using (var b = _fact.CreateExport()) { return b.Value; } } } [Export] [Shared("Boundary")] public class CirC { public CirA DepA { get; private set; } [ImportingConstructor] public CirC(CirA a) { DepA = a; } } [Export] [Shared] public class CirA { public int SharedState; private readonly ExportFactory<CirB> _fact; [ImportingConstructor] public CirA([SharingBoundary("Boundary")]ExportFactory<CirB> b) { _fact = b; } public CirB CreateInstance() { using (var ins = _fact.CreateExport()) { return ins.Value; } } } [Export] public class CirB { public CirC DepC { get; private set; } [ImportingConstructor] public CirB(CirC c) { DepC = c; } } public interface IProj { } [Export] public class SolA { private readonly IEnumerable<ExportFactory<IProj>> _fact; public List<IProj> Projects { get; private set; } [ImportingConstructor] public SolA([ImportMany][SharingBoundary("B1", "B2")] IEnumerable<ExportFactory<IProj>> c) { Projects = new List<IProj>(); _fact = c; } public void SetupProject() { foreach (var fact in _fact) { using (var instance = fact.CreateExport()) { Projects.Add(instance.Value); } } } } [Export(typeof(IProj))] public class ProjA : IProj { [ImportingConstructor] public ProjA(DocA docA, ColA colA) { } } [Export(typeof(IProj))] public class ProjB : IProj { [ImportingConstructor] public ProjB(DocB docA, ColB colA) { } } [Export] public class DocA { [ImportingConstructor] public DocA(ColA colA) { } } [Export] public class DocB { [ImportingConstructor] public DocB(ColB colB) { } } [Export] [Shared("B1")] public class ColA { public ColA() { } } [Export] [Shared("B2")] public class ColB { public ColB() { } } public interface ICol { } [Export(typeof(IX)), Export(typeof(IY)), Shared] public class XY : IX, IY { } public class SharingTest : ContainerTests { /// <summary> /// Two issues here One is that the message could be improved /// "The component (unknown) cannot be created outside the Boundary sharing boundary." /// Second is we don`t fail when we getExport for CPrime /// we fail only when we create instance of B.. is that correct. /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void BoundaryExposedBoundaryButNoneImported() { try { var cc = CreateContainer(typeof(A), typeof(B), typeof(CPrime), typeof(D)); var cInstance = cc.GetExport<CPrime>(); var bIn1 = cInstance.CreateInstance(); } catch (Exception ex) { Assert.True(ex.Message.Contains("The component (unknown) cannot be created outside the Boundary sharing boundary")); } } /// <summary> /// Need a partcreationpolicy currently. /// Needs to be fixed so that specifying boundary would automatically create the shared /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void BoundarySharingTest() { var cc = CreateContainer(typeof(A), typeof(B), typeof(C), typeof(D)); var cInstance = cc.GetExport<C>(); var bIn1 = cInstance.CreateInstance(); var bIn2 = cInstance.CreateInstance(); bIn1.InstanceA.SharedState = 1; var val1 = bIn1.InstanceD.InstanceA; bIn2.InstanceA.SharedState = 5; var val2 = bIn2.InstanceD.InstanceA; Assert.True(val1.SharedState == 1); Assert.True(val2.SharedState == 5); } /// <summary> /// CirA root of the composition has to be shared explicitly. /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void CircularBoundarySharingTest() { var cc = CreateContainer(typeof(CirA), typeof(CirB), typeof(CirC)); var cInstance = cc.GetExport<CirA>(); cInstance.SharedState = 1; var bInstance1 = cInstance.CreateInstance(); Assert.Equal(bInstance1.DepC.DepA.SharedState, 1); bInstance1.DepC.DepA.SharedState = 10; cInstance.CreateInstance(); Assert.Equal(bInstance1.DepC.DepA.SharedState, 10); } /// <summary> /// Something is badly busted here.. I am getting a null ref exception /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void MultipleBoundarySpecified() { var cc = CreateContainer(typeof(ProjA), typeof(ProjB), typeof(SolA), typeof(DocA), typeof(DocB), typeof(ColA), typeof(ColB)); var solInstance = cc.GetExport<SolA>(); solInstance.SetupProject(); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void SharedPartExportingMultipleContractsSharesAnInstance() { var cc = CreateContainer(typeof(XY)); var x = cc.GetExport<IX>(); var y = cc.GetExport<IY>(); Assert.Same(x, y); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void GetExportsCreatesInstancedObjectByDefault() { var cc = CreateContainer(typeof(NonSharedClass)); var val1 = cc.GetExport<ISharedTestingClass>(); var val2 = cc.GetExport<ISharedTestingClass>(); Assert.NotSame(val1, val2); } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void GetExportsCreatesSharedObjectsWhenSpecified() { var cc = CreateContainer(typeof(SharedClass)); var val1 = cc.GetExport<ISharedTestingClass>(); var val2 = cc.GetExport<ISharedTestingClass>(); Assert.Same(val1, val2); } /// <summary> /// Class with export factory that, which is shared that has a part that is non shared /// verify that GetExport returns only one instance regardless of times it is called /// verify that On Method call different instances are returned. /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ExportFactoryCreatesNewInstances() { var cc = CreateContainer(typeof(ClassWithExportFactoryShared), typeof(NonSharedClass)); var b1 = cc.GetExport<ClassWithExportFactoryShared>(); var b2 = cc.GetExport<ClassWithExportFactoryShared>(); var inst1 = b1.Method(); var inst2 = b1.Method(); Assert.Same(b1, b2); Assert.NotSame(inst1, inst2); } /// <summary> /// ExportFactory should be importable as a property /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ClassWithExportFactoryAsAProperty() { var cc = CreateContainer(typeof(ClassWithExportFactoryAsAProperty), typeof(NonSharedClass)); var b1 = cc.GetExport<ClassWithExportFactoryAsAProperty>(); var inst1 = b1.Method(); var inst2 = b1.Method(); Assert.NotNull(b1._fact); Assert.NotSame(inst1, inst2); } /// <summary> /// ExportFactory class is itself shared and /// will still respect the CreationPolicyAttribute on a part. If the export factory /// is creating a part which is shared, it will return back the same instance of the part. /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ClassWithExportFactoryAndSharedExport() { var cc = CreateContainer(typeof(ClassWithExportFactoryShared), typeof(SharedClass)); var b1 = cc.GetExport<ClassWithExportFactoryShared>(); var b2 = cc.GetExport<ClassWithExportFactoryShared>(); var inst1 = b1.Method(); var inst2 = b2.Method(); Assert.Same(b1, b2); Assert.Same(inst1, inst2); } /// <summary> /// Class which is nonShared has an exportFactory in it for a shared part. /// Two instances of the root class are created , the part created using export factory should not be shared /// </summary> [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ClassWithNonSharedExportFactoryCreatesSharedInstances() { var cc = CreateContainer(typeof(ClassWithExportFactoryNonShared), typeof(SharedClass)); var b1 = cc.GetExport<ClassWithExportFactoryNonShared>(); var b2 = cc.GetExport<ClassWithExportFactoryNonShared>(); var inst1 = b1.Method(); var inst2 = b2.Method(); Assert.NotSame(b1, b2); Assert.Same(inst1, inst2); } [Shared, Export] public class ASharedPart { } [Fact] [ActiveIssue(24903, TargetFrameworkMonikers.NetFramework)] public void ConsistentResultsAreReturneWhenResolvingLargeNumbersOfSharedParts() { var config = new ContainerConfiguration(); // Chosen to cause overflows in SmallSparseInitOnlyArray for (var i = 0; i < 1000; ++i) config.WithPart<ASharedPart>(); Assert.NotEqual(new ASharedPart(), new ASharedPart()); var container = config.CreateContainer(); var first = container.GetExports<ASharedPart>().ToList(); var second = container.GetExports<ASharedPart>().ToList(); Assert.Equal(first, second); } } }
// // StreamTagger.cs // // Author: // Aaron Bockover <abockover@novell.com> // // Copyright (C) 2006-2008 Novell, Inc. // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.Text.RegularExpressions; using Hyena; using Banshee.IO; using Banshee.Collection; namespace Banshee.Streaming { public static class StreamTagger { // This is a short list of video types that TagLib# might not support but that // we want to make sure are recognized as videos private static readonly ExtensionSet VideoExtensions = new ExtensionSet ( "avi", "divx", "dv", "f4p", "f4v", "flv", "m4v", "mkv", "mov", "ogv", "qt", "ts"); public static TagLib.File ProcessUri (SafeUri uri) { try { TagLib.File file = Banshee.IO.DemuxVfs.OpenFile (uri.IsLocalPath ? uri.LocalPath : uri.AbsoluteUri, null, TagLib.ReadStyle.Average); if ((file.Properties.MediaTypes & TagLib.MediaTypes.Audio) == 0 && (file.Properties.MediaTypes & TagLib.MediaTypes.Video) == 0) { throw new TagLib.UnsupportedFormatException ("File does not contain video or audio"); } return file; } catch (Exception e) { Hyena.Log.DebugFormat ("Encountered a problem processing: {0}", uri.AbsoluteUri); Hyena.Log.DebugException (e); return null; } } private static string Choose (string priority, string fallback) { return Choose (priority, fallback, false); } private static string Choose (string priority, string fallback, bool flip) { return TrimZero (flip ? IsNullOrEmpty (fallback) ? priority : fallback : IsNullOrEmpty (priority) ? fallback : priority); } private static bool IsNullOrEmpty (string s) { return String.IsNullOrEmpty (s) || TrimZero (s).Length == 0; } private static string TrimZero (string s) { return s == null || s.IndexOf ('\0') == -1 ? s : s.Split ('\0')[0]; } #pragma warning disable 0169 private static int Choose (int priority, int fallback) { return Choose (priority, fallback, false); } #pragma warning restore 0169 private static int Choose (int priority, int fallback, bool flip) { return flip ? (fallback <= 0 ? priority : fallback) : (priority <= 0 ? fallback : priority); } private static void FindTrackMediaAttributes (TrackInfo track, TagLib.File file) { if ((file.Properties.MediaTypes & TagLib.MediaTypes.Audio) != 0) { track.MediaAttributes |= TrackMediaAttributes.AudioStream; } if ((file.Properties.MediaTypes & TagLib.MediaTypes.Video) != 0) { track.MediaAttributes |= TrackMediaAttributes.VideoStream; } if (file.Tag.FirstGenre == "Podcast" || file.Tag.Album == "Podcast") { track.MediaAttributes |= TrackMediaAttributes.Podcast; } // TODO: Actually figure out, if possible at the tag/file level, if // the file is actual music, podcast, audiobook, movie, tv show, etc. // For now just assume that if it's only audio and not podcast, it's // music, since that's what we've just historically assumed on any media type if (!track.HasAttribute (TrackMediaAttributes.VideoStream) && !track.HasAttribute (TrackMediaAttributes.Podcast)) { track.MediaAttributes |= TrackMediaAttributes.Music; } else { // If it was already set, unset it track.MediaAttributes &= ~TrackMediaAttributes.Music; } } public static void TrackInfoMerge (TrackInfo track, SafeUri uri) { track.Uri = uri; using (var file = StreamTagger.ProcessUri (uri)) { TrackInfoMerge (track, file); if (file == null) { track.TrackTitle = uri.AbsoluteUri; } } } public static void TrackInfoMerge (TrackInfo track, TagLib.File file) { TrackInfoMerge (track, file, false); } public static void TrackInfoMerge (TrackInfo track, TagLib.File file, bool preferTrackInfo) { TrackInfoMerge (track, file, preferTrackInfo, false); } public static void TrackInfoMerge (TrackInfo track, TagLib.File file, bool preferTrackInfo, bool import_rating_and_play_count) { // TODO support these as arrays: // Performers[] (track artists), AlbumArtists[], Composers[], Genres[] // Note: this should be kept in sync with the metadata written in SaveTrackMetadataJob.cs if (file != null) { track.Uri = new SafeUri (file.Name); track.MimeType = file.MimeType; track.Duration = file.Properties.Duration; track.BitRate = file.Properties.AudioBitrate; track.SampleRate = file.Properties.AudioSampleRate; track.BitsPerSample = file.Properties.BitsPerSample; FindTrackMediaAttributes (track, file); track.ArtistName = Choose (file.Tag.JoinedPerformers, track.ArtistName, preferTrackInfo); track.ArtistNameSort = Choose (file.Tag.JoinedPerformersSort, track.ArtistNameSort, preferTrackInfo); track.ArtistMusicBrainzId = Choose (file.Tag.MusicBrainzArtistId, track.ArtistMusicBrainzId, preferTrackInfo); track.AlbumTitle = Choose (file.Tag.Album, track.AlbumTitle, preferTrackInfo); track.AlbumTitleSort = Choose (file.Tag.AlbumSort, track.AlbumTitleSort, preferTrackInfo); track.AlbumMusicBrainzId = Choose (file.Tag.MusicBrainzReleaseId, track.AlbumMusicBrainzId, preferTrackInfo); // AlbumArtist cannot be set until the track is marked as a compilation. track.IsCompilation = preferTrackInfo ? track.IsCompilation : IsCompilation (file); track.AlbumArtist = Choose (file.Tag.FirstAlbumArtist, track.AlbumArtist, preferTrackInfo); track.AlbumArtistSort = Choose (file.Tag.FirstAlbumArtistSort, track.AlbumArtistSort, preferTrackInfo); track.TrackTitle = Choose (file.Tag.Title, track.TrackTitle, preferTrackInfo); track.TrackTitleSort = Choose (file.Tag.TitleSort, track.TrackTitleSort, preferTrackInfo); track.MusicBrainzId = Choose (file.Tag.MusicBrainzTrackId, track.MusicBrainzId, preferTrackInfo); track.Genre = Choose (file.Tag.FirstGenre, track.Genre, preferTrackInfo); track.Composer = Choose (file.Tag.FirstComposer, track.Composer, preferTrackInfo); track.Conductor = Choose (file.Tag.Conductor, track.Conductor, preferTrackInfo); track.Grouping = Choose (file.Tag.Grouping, track.Grouping, preferTrackInfo); track.Copyright = Choose (file.Tag.Copyright, track.Copyright, preferTrackInfo); track.Comment = Choose (file.Tag.Comment, track.Comment, preferTrackInfo); track.TrackNumber = Choose ((int)file.Tag.Track, track.TrackNumber, preferTrackInfo); track.TrackCount = Choose ((int)file.Tag.TrackCount, track.TrackCount, preferTrackInfo); track.DiscNumber = Choose ((int)file.Tag.Disc, track.DiscNumber, preferTrackInfo); track.DiscCount = Choose ((int)file.Tag.DiscCount, track.DiscCount, preferTrackInfo); track.Year = Choose ((int)file.Tag.Year, track.Year, preferTrackInfo); track.Bpm = Choose ((int)file.Tag.BeatsPerMinute, track.Bpm, preferTrackInfo); if (import_rating_and_play_count) { int file_rating = 0, file_playcount = 0; StreamRatingTagger.GetRatingAndPlayCount (file, ref file_rating, ref file_playcount); track.Rating = Choose (file_rating, track.Rating, preferTrackInfo); track.PlayCount = Choose (file_playcount, track.PlayCount, preferTrackInfo); } } else { track.MediaAttributes = TrackMediaAttributes.AudioStream; if (track.Uri != null && VideoExtensions.IsMatchingFile (track.Uri.AbsoluteUri)) { track.MediaAttributes |= TrackMediaAttributes.VideoStream; } } track.FileSize = Banshee.IO.File.GetSize (track.Uri); track.FileModifiedStamp = Banshee.IO.File.GetModifiedTime (track.Uri); track.LastSyncedStamp = DateTime.Now; if (String.IsNullOrEmpty (track.TrackTitle)) { try { string filename = System.Web.HttpUtility.UrlDecode (System.IO.Path.GetFileNameWithoutExtension (track.Uri.AbsoluteUri)); if (!String.IsNullOrEmpty (filename)) { track.TrackTitle = filename; } } catch {} } // TODO look for track number in the file name if not set? // TODO could also pull artist/album from folders _iff_ files two levels deep in the MusicLibrary folder // TODO these ideas could also be done in an extension that collects such hacks } private static bool IsCompilation (TagLib.File file) { try { var xiph_tag = file.GetTag(TagLib.TagTypes.Xiph, true) as TagLib.Ogg.XiphComment; if (xiph_tag != null && xiph_tag.IsCompilation) return true; } catch {} try { TagLib.Id3v2.Tag id3v2_tag = file.GetTag(TagLib.TagTypes.Id3v2, true) as TagLib.Id3v2.Tag; if (id3v2_tag != null && id3v2_tag.IsCompilation) return true; } catch {} try { TagLib.Mpeg4.AppleTag apple_tag = file.GetTag(TagLib.TagTypes.Apple,true) as TagLib.Mpeg4.AppleTag; if (apple_tag != null && apple_tag.IsCompilation) return true; } catch {} // FIXME the FirstAlbumArtist != FirstPerformer check might return true for half the // tracks on a compilation album, but false for some // TODO checked for 'Soundtrack' (and translated) in the title? if (file.Tag.Performers.Length > 0 && file.Tag.AlbumArtists.Length > 0 && (file.Tag.Performers.Length != file.Tag.AlbumArtists.Length || file.Tag.FirstAlbumArtist != file.Tag.FirstPerformer)) { return true; } return false; } private static void SaveIsCompilation (TagLib.File file, bool is_compilation) { try { var xiph_tag = file.GetTag(TagLib.TagTypes.Xiph, true) as TagLib.Ogg.XiphComment; if (xiph_tag != null) { xiph_tag.IsCompilation = is_compilation; return; } } catch {} try { TagLib.Id3v2.Tag id3v2_tag = file.GetTag(TagLib.TagTypes.Id3v2, true) as TagLib.Id3v2.Tag; if (id3v2_tag != null) { id3v2_tag.IsCompilation = is_compilation; return; } } catch {} try { TagLib.Mpeg4.AppleTag apple_tag = file.GetTag(TagLib.TagTypes.Apple,true) as TagLib.Mpeg4.AppleTag; if (apple_tag != null) { apple_tag.IsCompilation = is_compilation; return; } } catch {} } public static bool SaveToFile (TrackInfo track, bool write_metadata, bool write_rating_and_play_count) { // Note: this should be kept in sync with the metadata read in StreamTagger.cs TagLib.File file = ProcessUri (track.Uri); if (file == null) { return false; } if (write_metadata) { file.Tag.Performers = new string [] { track.ArtistName }; file.Tag.PerformersSort = new string [] { track.ArtistNameSort }; file.Tag.Album = track.AlbumTitle; file.Tag.AlbumSort = track.AlbumTitleSort; file.Tag.MusicBrainzReleaseId = track.AlbumMusicBrainzId; file.Tag.AlbumArtists = track.AlbumArtist == null ? new string [0] : new string [] {track.AlbumArtist}; file.Tag.AlbumArtistsSort = (track.AlbumArtistSort == null ? new string [0] : new string [] {track.AlbumArtistSort}); file.Tag.MusicBrainzArtistId = track.ArtistMusicBrainzId; // Bug in taglib-sharp-2.0.3.0: Crash if you send it a genre of "{ null }" // on a song with both ID3v1 and ID3v2 metadata. It's happy with "{}", though. // (see http://forum.taglib-sharp.com/viewtopic.php?f=5&t=239 ) file.Tag.Genres = (track.Genre == null) ? new string[] {} : new string [] { track.Genre }; file.Tag.Title = track.TrackTitle; file.Tag.TitleSort = track.TrackTitleSort; file.Tag.MusicBrainzTrackId = track.MusicBrainzId; file.Tag.Track = (uint)track.TrackNumber; file.Tag.TrackCount = (uint)track.TrackCount; file.Tag.Composers = new string [] { track.Composer }; file.Tag.Conductor = track.Conductor; file.Tag.Grouping = track.Grouping; file.Tag.Copyright = track.Copyright; file.Tag.Comment = track.Comment; file.Tag.Disc = (uint)track.DiscNumber; file.Tag.DiscCount = (uint)track.DiscCount; file.Tag.Year = (uint)track.Year; file.Tag.BeatsPerMinute = (uint)track.Bpm; SaveIsCompilation (file, track.IsCompilation); } if (write_rating_and_play_count) { // FIXME move StreamRatingTagger to taglib# StreamRatingTagger.StoreRatingAndPlayCount (track.Rating, track.PlayCount, file); } file.Save (); file.Dispose (); track.FileSize = Banshee.IO.File.GetSize (track.Uri); track.FileModifiedStamp = Banshee.IO.File.GetModifiedTime (track.Uri); track.LastSyncedStamp = DateTime.Now; return true; } public static void TrackInfoMerge (TrackInfo track, StreamTag tag) { try { switch (tag.Name) { case CommonTags.Artist: track.ArtistName = Choose ((string)tag.Value, track.ArtistName); break; case CommonTags.ArtistSortName: case CommonTags.MusicBrainzSortName: track.ArtistNameSort = Choose ((string)tag.Value, track.ArtistNameSort); break; case CommonTags.Title: //track.TrackTitle = Choose ((string)tag.Value, track.TrackTitle); string title = Choose ((string)tag.Value, track.TrackTitle); // Try our best to figure out common patterns in poor radio metadata. // Often only one tag is sent on track changes inside the stream, // which is title, and usually contains artist and track title, separated // with a " - " string. if (track.IsLive && title.Contains (" - ")) { string [] parts = Regex.Split (title, " - "); track.TrackTitle = parts[1].Trim (); track.ArtistName = parts[0].Trim (); // Often, the title portion contains a postfix with more information // that will confuse lookups, such as "Talk [Studio Version]". // Strip out the [] part. Match match = Regex.Match (track.TrackTitle, "^(.+)[ ]+\\[.*\\]$"); if (match.Groups.Count == 2) { track.TrackTitle = match.Groups[1].Value; } } else { track.TrackTitle = title; } break; case CommonTags.TitleSortName: track.TrackTitleSort = Choose ((string)tag.Value, track.TrackTitleSort); break; case CommonTags.Album: track.AlbumTitle = Choose ((string)tag.Value, track.AlbumTitle); break; case CommonTags.AlbumSortName: track.AlbumTitleSort = Choose ((string)tag.Value, track.AlbumTitleSort); break; case CommonTags.Disc: case CommonTags.AlbumDiscNumber: int disc = (int)tag.Value; track.DiscNumber = disc == 0 ? track.DiscNumber : disc; break; case CommonTags.AlbumDiscCount: int count = (int)tag.Value; track.DiscCount = count == 0 ? track.DiscCount : count; break; case CommonTags.Genre: track.Genre = Choose ((string)tag.Value, track.Genre); break; case CommonTags.Composer: track.Composer = Choose ((string)tag.Value, track.Composer); break; case CommonTags.Copyright: track.Copyright = Choose ((string)tag.Value, track.Copyright); break; case CommonTags.LicenseUri: track.LicenseUri = Choose ((string)tag.Value, track.LicenseUri); break; case CommonTags.Comment: track.Comment = Choose ((string)tag.Value, track.Comment); break; case CommonTags.TrackNumber: int track_number = (int)tag.Value; track.TrackNumber = track_number == 0 ? track.TrackNumber : track_number; break; case CommonTags.TrackCount: track.TrackCount = (int)tag.Value; break; case CommonTags.BeatsPerMinute: track.Bpm = (int)tag.Value; break; case CommonTags.Duration: if (tag.Value is TimeSpan) { track.Duration = (TimeSpan)tag.Value; } else { track.Duration = new TimeSpan ((uint)tag.Value * TimeSpan.TicksPerMillisecond); } break; case CommonTags.MoreInfoUri: track.MoreInfoUri = (SafeUri)tag.Value; break; /* No year tag in GST it seems case CommonTags.Year: track.Year = (uint)tag.Value; break;*/ case CommonTags.NominalBitrate: track.BitRate = (int)tag.Value; break; case CommonTags.StreamType: track.MimeType = (string)tag.Value; break; case CommonTags.VideoCodec: if (tag.Value != null) { track.MediaAttributes |= TrackMediaAttributes.VideoStream; } break; /*case CommonTags.AlbumCoverId: foreach(string ext in TrackInfo.CoverExtensions) { string path = Paths.GetCoverArtPath((string) tag.Value, "." + ext); if(System.IO.File.Exists(path)) { track.CoverArtFileName = path; break; } } break;*/ } } catch { } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Orleans.Runtime.Configuration; using Orleans.MultiCluster; namespace Orleans.Runtime { /// <summary> /// Interface for system management functions of silos, /// exposed as a grain for receiving remote requests / commands. /// </summary> public interface IManagementGrain : IGrainWithIntegerKey { /// <summary> /// Get the list of silo hosts and statuses currently known about in this cluster. /// </summary> /// <param name="onlyActive">Whether data on just current active silos should be returned, /// or by default data for all current and previous silo instances [including those in Joining or Dead status].</param> /// <returns></returns> Task<Dictionary<SiloAddress, SiloStatus>> GetHosts(bool onlyActive = false); /// <summary> /// Get the list of silo hosts and membership information currently known about in this cluster. /// </summary> /// <param name="onlyActive">Whether data on just current active silos should be returned, /// or by default data for all current and previous silo instances [including those in Joining or Dead status].</param> /// <returns></returns> Task<MembershipEntry[]> GetDetailedHosts(bool onlyActive = false); /// <summary> /// Set the current log level for system runtime components. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <param name="traceLevel">New log level to use.</param> /// <returns>Completion promise for this operation.</returns> Task SetSystemLogLevel(SiloAddress[] hostsIds, int traceLevel); /// <summary> /// Set the current log level for application grains. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <param name="traceLevel">New log level to use.</param> /// <returns>Completion promise for this operation.</returns> Task SetAppLogLevel(SiloAddress[] hostsIds, int traceLevel); /// <summary> /// Set the current log level for a particular Logger, by name (with prefix matching). /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <param name="logName">Name of the Logger (with prefix matching) to change.</param> /// <param name="traceLevel">New log level to use.</param> /// <returns>Completion promise for this operation.</returns> Task SetLogLevel(SiloAddress[] hostsIds, string logName, int traceLevel); /// <summary> /// Perform a run of the .NET garbage collector in the specified silos. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <returns>Completion promise for this operation.</returns> Task ForceGarbageCollection(SiloAddress[] hostsIds); /// <summary>Perform a run of the Orleans activation collecter in the specified silos.</summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <param name="ageLimit">Maximum idle time of activations to be collected.</param> /// <returns>Completion promise for this operation.</returns> Task ForceActivationCollection(SiloAddress[] hostsIds, TimeSpan ageLimit); Task ForceActivationCollection(TimeSpan ageLimit); /// <summary>Perform a run of the silo statistics collector in the specified silos.</summary> /// <param name="siloAddresses">List of silos this command is to be sent to.</param> /// <returns>Completion promise for this operation.</returns> Task ForceRuntimeStatisticsCollection(SiloAddress[] siloAddresses); /// <summary> /// Return the most recent silo runtime statistics information for the specified silos. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <returns>Completion promise for this operation.</returns> Task<SiloRuntimeStatistics[]> GetRuntimeStatistics(SiloAddress[] hostsIds); /// <summary> /// Return the most recent grain statistics information, amalgomated across silos. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <returns>Completion promise for this operation.</returns> Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(SiloAddress[] hostsIds); /// <summary> /// Return the most recent grain statistics information, amalgomated across all silos. /// </summary> /// <returns>Completion promise for this operation.</returns> Task<SimpleGrainStatistic[]> GetSimpleGrainStatistics(); /// <summary> /// Returns the most recent detailed grain statistics information, amalgomated across silos for the specified types. /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <param name="types">Array of grain types to filter the results with</param> /// <returns></returns> Task<DetailedGrainStatistic[]> GetDetailedGrainStatistics(string[] types = null,SiloAddress[] hostsIds=null); Task<int> GetGrainActivationCount(GrainReference grainReference); /// <summary> /// Return the total count of all current grain activations across all silos. /// </summary> /// <returns>Completion promise for this operation.</returns> /// Task<int> GetTotalActivationCount(); /// <summary> /// Execute a control command on the specified providers on all silos in the cluster. /// Commands are sent to all known providers on each silo which match both the <c>providerTypeFullName</c> AND <c>providerName</c> parameters. /// </summary> /// <remarks> /// Providers must implement the <c>Orleans.Providers.IControllable</c> /// interface in order to receive these control channel commands. /// </remarks> /// <param name="providerTypeFullName">Class full name for the provider type to send this command to.</param> /// <param name="providerName">Provider name to send this command to.</param> /// <param name="command">An id / serial number of this command. /// This is an opaque value to the Orleans runtime - the control protocol semantics are decided between the sender and provider.</param> /// <param name="arg">An opaque command argument. /// This is an opaque value to the Orleans runtime - the control protocol semantics are decided between the sender and provider.</param> /// <returns>Completion promise for this operation.</returns> Task<object[]> SendControlCommandToProvider(string providerTypeFullName, string providerName, int command, object arg = null); /// <summary> /// Update the configuration information dynamically. Only a subset of configuration information /// can be updated - will throw an error (and make no config changes) if you specify attributes /// or elements that cannot be changed. The configuration format is XML, in the same format /// as the OrleansConfiguration.xml file. The allowed elements and attributes are: /// <pre> /// &lt;OrleansConfiguration&gt; /// &lt;Globals&gt; /// &lt;Messaging ResponseTimeout=&quot;?&quot;/&gt; /// &lt;Caching CacheSize=&quot;?&quot;/&gt; /// &lt;Activation CollectionInterval=&quot;?&quot; CollectionAmount=&quot;?&quot; CollectionTotalMemoryLimit=&quot;?&quot; CollectionActivationLimit=&quot;?&quot;/&gt; /// &lt;Liveness ProbeTimeout=&quot;?&quot; TableRefreshTimeout=&quot;?&quot; NumMissedProbesLimit=&quot;?&quot;/&gt; /// &lt;/Globals&gt; /// &lt;Defaults&gt; /// &lt;LoadShedding Enabled=&quot;?&quot; LoadLimit=&quot;?&quot;/&gt; /// &lt;Tracing DefaultTraceLevel=&quot;?&quot; PropagateActivityId=&quot;?&quot;&gt; /// &lt;TraceLevelOverride LogPrefix=&quot;?&quot; TraceLevel=&quot;?&quot;/&gt; /// &lt;/Tracing&gt; /// &lt;/Defaults&gt; /// &lt;/OrleansConfiguration&gt; /// </pre> /// </summary> /// <param name="hostIds">Silos to update, or null for all silos</param> /// <param name="configuration">XML elements and attributes to update</param> /// <param name="tracing">Tracing level settings</param> /// <returns></returns> Task UpdateConfiguration(SiloAddress[] hostIds, Dictionary<string, string> configuration, Dictionary<string, string> tracing); /// <summary> /// Update the stream providers dynamically. The stream providers in the listed silos will be /// updated based on the differences between its loaded stream providers and the list of providers /// in the streamProviderConfigurations: If a provider in the configuration object already exists /// in the silo, it will be kept as is; if a provider in the configuration object does not exist /// in the silo, it will be loaded and started; if a provider that exists in silo but is not in /// the configuration object, it will be stopped and removed from the silo. /// </summary> /// <param name="hostIds">Silos to update, or null for all silos</param> /// <param name="streamProviderConfigurations">stream provider configurations that carries target stream providers</param> /// <returns></returns> Task UpdateStreamProviders(SiloAddress[] hostIds, IDictionary<string, ProviderCategoryConfiguration> streamProviderConfigurations); /// <summary> /// Returns an array of all the active grain types in the system /// </summary> /// <param name="hostsIds">List of silos this command is to be sent to.</param> /// <returns></returns> Task<string[]> GetActiveGrainTypes(SiloAddress[] hostsIds=null); #region MultiCluster Management /// <summary> /// Get the current list of multicluster gateways. /// </summary> /// <returns>A list of the currently known gateways</returns> Task<List<IMultiClusterGatewayInfo>> GetMultiClusterGateways(); /// <summary> /// Get the current multicluster configuration. /// </summary> /// <returns>The current multicluster configuration, or null if there is none</returns> Task<MultiClusterConfiguration> GetMultiClusterConfiguration(); /// <summary> /// Contact all silos in all clusters and return silos that do not have the latest multi-cluster configuration. /// If some clusters and/or silos cannot be reached, an exception is thrown. /// </summary> /// <returns>A list of silo addresses of silos that do not have the latest configuration</returns> Task<List<SiloAddress>> FindLaggingSilos(); /// <summary> /// Configure the active multi-cluster, by injecting a multicluster configuration. /// </summary> /// <param name="clusters">the clusters that should be part of the active configuration</param> /// <param name="comment">a comment to store alongside the configuration</param> /// <param name="checkForLaggingSilosFirst">if true, checks that all clusters are reachable and up-to-date before injecting the new configuration</param> /// <returns> The task completes once information has propagated to the gossip channels</returns> Task<MultiClusterConfiguration> InjectMultiClusterConfiguration(IEnumerable<string> clusters, string comment = "", bool checkForLaggingSilosFirst = true); #endregion } }
/********************************************************************++ Copyright (c) Microsoft Corporation. All rights reserved. --********************************************************************/ using System.IO; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.Management.Automation.Internal; namespace System.Management.Automation { /// <summary> /// /// Class HelpFileHelpProvider implement the help provider for help.txt kinds of /// help contents. /// /// Help File help information are stored in '.help.txt' files. These files are /// located in the Monad / CustomShell Path as well as in the Application Base /// of PSSnapIns /// /// </summary> internal class HelpFileHelpProvider : HelpProviderWithCache { /// <summary> /// Constructor for HelpProvider /// </summary> internal HelpFileHelpProvider(HelpSystem helpSystem) : base(helpSystem) { } #region Common Properties /// <summary> /// Name of the provider /// </summary> /// <value>Name of the provider</value> internal override string Name { get { return "HelpFile Help Provider"; } } /// <summary> /// Help category of the provider /// </summary> /// <value>Help category of the provider</value> internal override HelpCategory HelpCategory { get { return HelpCategory.HelpFile; } } #endregion #region Help Provider Interface internal override IEnumerable<HelpInfo> ExactMatchHelp(HelpRequest helpRequest) { int countHelpInfosFound = 0; string helpFileName = helpRequest.Target + ".help.txt"; Collection<string> filesMatched = MUIFileSearcher.SearchFiles(helpFileName, GetExtendedSearchPaths()); Diagnostics.Assert(filesMatched != null, "Files collection should not be null."); var matchedFilesToRemove = FilterToLatestModuleVersion(filesMatched); foreach (string file in filesMatched) { if (matchedFilesToRemove.Contains(file)) continue; // Check whether the file is already loaded if (!_helpFiles.ContainsKey(file)) { try { LoadHelpFile(file); } catch (IOException ioException) { ReportHelpFileError(ioException, helpRequest.Target, file); } catch (System.Security.SecurityException securityException) { ReportHelpFileError(securityException, helpRequest.Target, file); } } HelpInfo helpInfo = GetCache(file); if (helpInfo != null) { countHelpInfosFound++; yield return helpInfo; if ((countHelpInfosFound >= helpRequest.MaxResults) && (helpRequest.MaxResults > 0)) yield break; } } } private Collection<string> FilterToLatestModuleVersion(Collection<string> filesMatched) { Collection<string> matchedFilesToRemove = new Collection<string>(); if (filesMatched.Count > 1) { //Dictionary<<ModuleName,fileName>, <Version, helpFileFullName>> Dictionary<Tuple<string, string>, Tuple<string, Version>> modulesAndVersion = new Dictionary<Tuple<string, string>, Tuple<string, Version>>(); HashSet<string> filesProcessed = new HashSet<string>(); var allPSModulePaths = ModuleIntrinsics.GetModulePath(false, this.HelpSystem.ExecutionContext); foreach (string fileFullName in filesMatched) { // Use the filename as a check if we need to process further. // Single module can have multiple .help.txt files. var fileName = Path.GetFileName(fileFullName); foreach (string psModulePath in allPSModulePaths) { Version moduleVersionFromPath = null; string moduleName = null; GetModuleNameAndVersion(psModulePath, fileFullName, out moduleName, out moduleVersionFromPath); //Skip modules whose root we cannot determine or which do not have versions. if (moduleVersionFromPath != null && moduleName != null) { Tuple<string, Version> moduleVersion = null; Tuple<string, string> key = new Tuple<string, string>(moduleName, fileName); if (modulesAndVersion.TryGetValue(key, out moduleVersion)) { //Consider for further processing only if the help file name is same. if (filesProcessed.Contains(fileName)) { if (moduleVersionFromPath > moduleVersion.Item2) { modulesAndVersion[key] = new Tuple<string, Version>(fileFullName, moduleVersionFromPath); //Remove the old file since we found a newer version. matchedFilesToRemove.Add(moduleVersion.Item1); } else { //Remove the new file as higher version item is already in dictionary. matchedFilesToRemove.Add(fileFullName); } } } else { //Add the module to the dictionary as it was not processes earlier. modulesAndVersion.Add(new Tuple<string, string>(moduleName, fileName), new Tuple<string, Version>(fileFullName, moduleVersionFromPath)); } } } filesProcessed.Add(fileName); } } return matchedFilesToRemove; } internal override IEnumerable<HelpInfo> SearchHelp(HelpRequest helpRequest, bool searchOnlyContent) { string target = helpRequest.Target; string pattern = target; int countOfHelpInfoObjectsFound = 0; // this will be used only when searchOnlyContent == true WildcardPattern wildCardPattern = null; if ((!searchOnlyContent) && (!WildcardPattern.ContainsWildcardCharacters(target))) { // Search all the about conceptual topics. This pattern // makes about topics discoverable without actually // using the word "about_" as in "get-help while". pattern = "*" + pattern + "*"; } if (searchOnlyContent) { string searchTarget = helpRequest.Target; if (!WildcardPattern.ContainsWildcardCharacters(helpRequest.Target)) { searchTarget = "*" + searchTarget + "*"; } wildCardPattern = WildcardPattern.Get(searchTarget, WildcardOptions.Compiled | WildcardOptions.IgnoreCase); // search all about_* topics pattern = "*"; } pattern += ".help.txt"; Collection<String> files = MUIFileSearcher.SearchFiles(pattern, GetExtendedSearchPaths()); var matchedFilesToRemove = FilterToLatestModuleVersion(files); if (files == null) yield break; foreach (string file in files) { if (matchedFilesToRemove.Contains(file)) continue; // Check whether the file is already loaded if (!_helpFiles.ContainsKey(file)) { try { LoadHelpFile(file); } catch (IOException ioException) { ReportHelpFileError(ioException, helpRequest.Target, file); } catch (System.Security.SecurityException securityException) { ReportHelpFileError(securityException, helpRequest.Target, file); } } HelpFileHelpInfo helpInfo = GetCache(file) as HelpFileHelpInfo; if (helpInfo != null) { if (searchOnlyContent) { if (!helpInfo.MatchPatternInContent(wildCardPattern)) { continue; } } countOfHelpInfoObjectsFound++; yield return helpInfo; if (countOfHelpInfoObjectsFound >= helpRequest.MaxResults && helpRequest.MaxResults > 0) yield break; } } } private void GetModuleNameAndVersion(string psmodulePathRoot, string filePath, out string moduleName, out Version moduleVersion) { moduleVersion = null; moduleName = null; if (filePath.StartsWith(psmodulePathRoot, StringComparison.OrdinalIgnoreCase)) { var moduleRootSubPath = filePath.Remove(0, psmodulePathRoot.Length).TrimStart(Utils.Separators.Directory); var pathParts = moduleRootSubPath.Split(Utils.Separators.Directory, StringSplitOptions.RemoveEmptyEntries); moduleName = pathParts[0]; var potentialVersion = pathParts[1]; Version result; if (Version.TryParse(potentialVersion, out result)) { moduleVersion = result; } } } /// <summary> /// Load help file based on the file path. /// </summary> /// <param name="path">file path to load help from</param> /// <returns>Help info object loaded from the file</returns> private HelpInfo LoadHelpFile(string path) { string fileName = Path.GetFileName(path); //Bug906435: Get-help for special devices throws an exception //There might be situations where path does not end with .help.txt extension //The assumption that path ends with .help.txt is broken under special //conditions when user uses "get-help" with device names like "prn","com1" etc. //First check whether path ends with .help.txt. // If path does not end with ".help.txt" return. if (!path.EndsWith(".help.txt", StringComparison.OrdinalIgnoreCase)) return null; string name = fileName.Substring(0, fileName.Length - 9 /* ".help.txt".Length */); if (String.IsNullOrEmpty(name)) return null; HelpInfo helpInfo = GetCache(path); if (helpInfo != null) return helpInfo; string helpText = null; using (TextReader tr = new StreamReader(new FileStream(path, FileMode.Open, FileAccess.Read, FileShare.Read))) { helpText = tr.ReadToEnd(); } // Add this file into _helpFiles hashtable to prevent it to be loaded again. _helpFiles[path] = 0; helpInfo = HelpFileHelpInfo.GetHelpInfo(name, helpText, path); AddCache(path, helpInfo); return helpInfo; } /// <summary> /// Gets the extended search paths for about_topics help. To be able to get about_topics help from unloaded modules, /// we will add $pshome and the folders under PS module paths to the collection of paths to search. /// </summary> /// <returns>a collection of string representing locations</returns> internal Collection<string> GetExtendedSearchPaths() { Collection<String> searchPaths = GetSearchPaths(); // Add $pshome at the top of the list String defaultShellSearchPath = GetDefaultShellSearchPath(); int index = searchPaths.IndexOf(defaultShellSearchPath); if (index != 0) { if (index > 0) { searchPaths.RemoveAt(index); } searchPaths.Insert(0, defaultShellSearchPath); } // Add modules that are not loaded. Since using 'get-module -listavailable' is very expensive, // we load all the directories (which are not empty) under the module path. foreach (string psModulePath in ModuleIntrinsics.GetModulePath(false, this.HelpSystem.ExecutionContext)) { if (Directory.Exists(psModulePath)) { try { // Get all the directories under the module path // * and SearchOption.AllDirectories gets all the version directories. string[] directories = Directory.GetDirectories(psModulePath, "*", SearchOption.AllDirectories); var possibleModuleDirectories = directories.Where(directory => ModuleUtils.IsPossibleModuleDirectory(directory)); foreach (string directory in possibleModuleDirectories) { // Add only directories that are not empty if (Directory.EnumerateFiles(directory).Any()) { if (!searchPaths.Contains(directory)) { searchPaths.Add(directory); } } } } // Absorb any exception related to enumerating directories catch (System.ArgumentException) { } catch (System.IO.IOException) { } catch (System.UnauthorizedAccessException) { } catch (System.Security.SecurityException) { } } } return searchPaths; } /// <summary> /// This will reset the help cache. Normally this corresponds to a /// help culture change. /// </summary> internal override void Reset() { base.Reset(); _helpFiles.Clear(); } #endregion #region Private Data /// <summary> /// This is a hashtable to track which help files are loaded already. /// /// This will avoid one help file getting loaded again and again. /// </summary> private Hashtable _helpFiles = new Hashtable(); #endregion } }
// ReSharper disable InconsistentNaming namespace MicroMapper { using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Configuration; using Impl; using Internal; using Mappers; public class ConfigurationStore : IConfigurationProvider, IConfiguration { private static readonly IDictionaryFactory DictionaryFactory = PlatformAdapter.Resolve<IDictionaryFactory>(); private readonly ITypeMapFactory _typeMapFactory; internal const string DefaultProfileName = ""; private readonly Internal.IDictionary<TypePair, TypeMap> _userDefinedTypeMaps = DictionaryFactory.CreateDictionary<TypePair, TypeMap>(); private readonly Internal.IDictionary<TypePair, TypeMap> _typeMapPlanCache = DictionaryFactory.CreateDictionary<TypePair, TypeMap>(); private readonly Internal.IDictionary<TypePair, CreateTypeMapExpression> _typeMapExpressionCache = DictionaryFactory.CreateDictionary<TypePair, CreateTypeMapExpression>(); private readonly Internal.IDictionary<string, ProfileConfiguration> _formatterProfiles = DictionaryFactory.CreateDictionary<string, ProfileConfiguration>(); private Func<Type, object> _serviceCtor = ObjectCreator.CreateObject; private readonly List<string> _globalIgnore; /// <summary> /// Gets the MapperContext. /// </summary> private IMapperContext MapperContext { get; } /// <summary> /// Gets the ObjectMappers. /// </summary> public IObjectMapperCollection ObjectMappers { get; } public ConfigurationStore(IMapperContext mapperContext, ITypeMapFactory typeMapFactory, IObjectMapperCollection objectMappers) { MapperContext = mapperContext; _typeMapFactory = typeMapFactory; ObjectMappers = objectMappers; _globalIgnore = new List<string>(); } public event EventHandler<TypeMapCreatedEventArgs> TypeMapCreated; public Func<Type, object> ServiceCtor => _serviceCtor; public void ForAllMaps(Action<TypeMap, IMappingExpression> configuration) { ForAllMaps(DefaultProfileName, configuration); } internal void ForAllMaps(string profileName, Action<TypeMap, IMappingExpression> configuration) { foreach (var typeMap in _userDefinedTypeMaps.Values.Where(tm => tm.Profile == profileName)) { configuration(typeMap, CreateMappingExpression(typeMap, typeMap.DestinationType)); } } public Func<PropertyInfo, bool> ShouldMapProperty { get { return GetProfile(DefaultProfileName).ShouldMapProperty; } set { GetProfile(DefaultProfileName).ShouldMapProperty = value; } } public Func<FieldInfo, bool> ShouldMapField { get { return GetProfile(DefaultProfileName).ShouldMapField; } set { GetProfile(DefaultProfileName).ShouldMapField = value; } } public bool AllowNullDestinationValues { get { return GetProfile(DefaultProfileName).AllowNullDestinationValues; } set { GetProfile(DefaultProfileName).AllowNullDestinationValues = value; } } public bool AllowNullCollections { get { return GetProfile(DefaultProfileName).AllowNullCollections; } set { GetProfile(DefaultProfileName).AllowNullCollections = value; } } public void IncludeSourceExtensionMethods(Assembly assembly) { GetProfile(DefaultProfileName).IncludeSourceExtensionMethods(assembly); } public INamingConvention SourceMemberNamingConvention { get { return GetProfile(DefaultProfileName).SourceMemberNamingConvention; } set { GetProfile(DefaultProfileName).SourceMemberNamingConvention = value; } } public INamingConvention DestinationMemberNamingConvention { get { return GetProfile(DefaultProfileName).DestinationMemberNamingConvention; } set { GetProfile(DefaultProfileName).DestinationMemberNamingConvention = value; } } public IEnumerable<string> Prefixes => GetProfile(DefaultProfileName).Prefixes; public IEnumerable<string> Postfixes => GetProfile(DefaultProfileName).Postfixes; public IEnumerable<string> DestinationPrefixes => GetProfile(DefaultProfileName).DestinationPrefixes; public IEnumerable<string> DestinationPostfixes => GetProfile(DefaultProfileName).DestinationPostfixes; public IEnumerable<MemberNameReplacer> MemberNameReplacers => GetProfile(DefaultProfileName).MemberNameReplacers ; public IEnumerable<AliasedMember> Aliases => GetProfile(DefaultProfileName).Aliases; public bool ConstructorMappingEnabled => GetProfile(DefaultProfileName).ConstructorMappingEnabled; public bool DataReaderMapperYieldReturnEnabled => GetProfile(DefaultProfileName).DataReaderMapperYieldReturnEnabled; public IEnumerable<MethodInfo> SourceExtensionMethods => GetProfile(DefaultProfileName).SourceExtensionMethods; bool IProfileConfiguration.MapNullSourceValuesAsNull => AllowNullDestinationValues; bool IProfileConfiguration.MapNullSourceCollectionsAsNull => AllowNullCollections; public IProfileExpression CreateProfile(string profileName) { var profileExpression = new Profile(profileName); profileExpression.Initialize(this); return profileExpression; } public void CreateProfile(string profileName, Action<IProfileExpression> profileConfiguration) { var profileExpression = new Profile(profileName); profileExpression.Initialize(this); profileConfiguration(profileExpression); } public void AddProfile(Profile profile) { profile.Initialize(this); profile.Configure(); } public void AddProfile<TProfile>() where TProfile : Profile, new() { AddProfile(new TProfile()); } public void ConstructServicesUsing(Func<Type, object> constructor) { _serviceCtor = constructor; } public void DisableConstructorMapping() { GetProfile(DefaultProfileName).ConstructorMappingEnabled = false; } public void EnableYieldReturnForDataReaderMapper() { GetProfile(DefaultProfileName).DataReaderMapperYieldReturnEnabled = true; } public void Seal() { foreach (var typeMap in _userDefinedTypeMaps.Values) { typeMap.Seal(); var typePair = new TypePair(typeMap.SourceType, typeMap.DestinationType); _typeMapPlanCache.AddOrUpdate(typePair, typeMap, (_, _2) => typeMap); if (typeMap.DestinationTypeOverride != null) { var includedDerivedType = new TypePair(typeMap.SourceType, typeMap.DestinationTypeOverride); var derivedMap = FindTypeMapFor(includedDerivedType); if (derivedMap != null) { _typeMapPlanCache.AddOrUpdate(typePair, derivedMap, (_, _2) => derivedMap); } } foreach (var derivedMap in GetDerivedTypeMaps(typeMap)) { _typeMapPlanCache.AddOrUpdate(new TypePair(derivedMap.SourceType, typeMap.DestinationType), derivedMap, (_, _2) => derivedMap); } } } private IEnumerable<TypeMap> GetDerivedTypeMaps(TypeMap typeMap) { if (typeMap == null) yield break; foreach (var derivedMap in typeMap.IncludedDerivedTypes.Select(FindTypeMapFor)) { if (derivedMap != null) yield return derivedMap; foreach (var derivedTypeMap in GetDerivedTypeMaps(derivedMap)) { yield return derivedTypeMap; } } } public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>() { return CreateMap<TSource, TDestination>(DefaultProfileName); } public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>(MemberList memberList) { return CreateMap<TSource, TDestination>(DefaultProfileName, memberList); } public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>(string profileName) { return CreateMap<TSource, TDestination>(profileName, MemberList.Destination); } public IMappingExpression<TSource, TDestination> CreateMap<TSource, TDestination>(string profileName, MemberList memberList) { TypeMap typeMap = CreateTypeMap(typeof (TSource), typeof (TDestination), profileName, memberList); return CreateMappingExpression<TSource, TDestination>(typeMap); } public IMappingExpression CreateMap(Type sourceType, Type destinationType) { return CreateMap(sourceType, destinationType, MemberList.Destination); } public IMappingExpression CreateMap(Type sourceType, Type destinationType, MemberList memberList) { return CreateMap(sourceType, destinationType, memberList, DefaultProfileName); } public IMappingExpression CreateMap(Type sourceType, Type destinationType, MemberList memberList, string profileName) { if (sourceType.IsGenericTypeDefinition() && destinationType.IsGenericTypeDefinition()) { var typePair = new TypePair(sourceType, destinationType); var expression = _typeMapExpressionCache.GetOrAdd(typePair, tp => new CreateTypeMapExpression(tp, memberList, profileName)); return expression; } var typeMap = CreateTypeMap(sourceType, destinationType, profileName, memberList); return CreateMappingExpression(typeMap, destinationType); } public void ClearPrefixes() { GetProfile(DefaultProfileName).ClearPrefixes(); } public void RecognizePrefixes(params string[] prefixes) { GetProfile(DefaultProfileName).RecognizePrefixes(prefixes); } public void RecognizePostfixes(params string[] postfixes) { GetProfile(DefaultProfileName).RecognizePostfixes(postfixes); } public void RecognizeAlias(string original, string alias) { GetProfile(DefaultProfileName).RecognizeAlias(original, alias); } public void ReplaceMemberName(string original, string newValue) { GetProfile(DefaultProfileName).ReplaceMemberName(original, newValue); } public void RecognizeDestinationPrefixes(params string[] prefixes) { GetProfile(DefaultProfileName).RecognizeDestinationPrefixes(prefixes); } public void RecognizeDestinationPostfixes(params string[] postfixes) { GetProfile(DefaultProfileName).RecognizeDestinationPostfixes(postfixes); } public TypeMap CreateTypeMap(Type source, Type destination) { return CreateTypeMap(source, destination, DefaultProfileName, MemberList.Destination); } public TypeMap CreateTypeMap(Type source, Type destination, string profileName, MemberList memberList) { var typePair = new TypePair(source, destination); var typeMap = _userDefinedTypeMaps.GetOrAdd(typePair, tp => { var profileConfiguration = GetProfile(profileName); var tm = _typeMapFactory.CreateTypeMap(source, destination, profileConfiguration, memberList); tm.Profile = profileName; tm.IgnorePropertiesStartingWith = _globalIgnore; IncludeBaseMappings(source, destination, tm); // keep the cache in sync TypeMap _; _typeMapPlanCache.TryRemove(tp, out _); OnTypeMapCreated(tm); return tm; }); return typeMap; } private void IncludeBaseMappings(Type source, Type destination, TypeMap typeMap) { foreach ( var inheritedTypeMap in _userDefinedTypeMaps.Values.Where(t => t.TypeHasBeenIncluded(source, destination))) { typeMap.ApplyInheritedMap(inheritedTypeMap); } } public TypeMap[] GetAllTypeMaps() { return _userDefinedTypeMaps.Values.ToArray(); } public TypeMap FindTypeMapFor(Type sourceType, Type destinationType) { var typePair = new TypePair(sourceType, destinationType); return FindTypeMapFor(typePair); } public TypeMap FindTypeMapFor(TypePair typePair) { TypeMap typeMap; _userDefinedTypeMaps.TryGetValue(typePair, out typeMap); return typeMap; } public TypeMap ResolveTypeMap(Type sourceType, Type destinationType) { var typePair = new TypePair(sourceType, destinationType); return ResolveTypeMap(typePair); } public TypeMap ResolveTypeMap(TypePair typePair) { var typeMap = _typeMapPlanCache.GetOrAdd(typePair, _ => GetRelatedTypePairs(_) .Select(tp => FindTypeMapFor(tp) ?? _typeMapPlanCache.GetOrDefault(tp)) .FirstOrDefault(tm => tm != null)); return typeMap; } public TypeMap ResolveTypeMap(object source, object destination, Type sourceType, Type destinationType) { return ResolveTypeMap(source?.GetType() ?? sourceType, destination?.GetType() ?? destinationType); } public TypeMap ResolveTypeMap(ResolutionResult resolutionResult, Type destinationType) { return ResolveTypeMap(resolutionResult.Value, null, resolutionResult.Type, destinationType) ?? ResolveTypeMap(resolutionResult.Value, null, resolutionResult.MemberType, destinationType); } public TypeMap FindClosedGenericTypeMapFor(ResolutionContext context) { var closedGenericTypePair = new TypePair(context.SourceType, context.DestinationType); var sourceGenericDefinition = context.SourceType.GetGenericTypeDefinition(); var destGenericDefinition = context.DestinationType.GetGenericTypeDefinition(); var genericTypePair = new TypePair(sourceGenericDefinition, destGenericDefinition); CreateTypeMapExpression genericTypeMapExpression; if (!_typeMapExpressionCache.TryGetValue(genericTypePair, out genericTypeMapExpression)) { throw new MicroMapperMappingException(context, "Missing type map configuration or unsupported mapping."); } var typeMap = CreateTypeMap(closedGenericTypePair.SourceType, closedGenericTypePair.DestinationType, genericTypeMapExpression.ProfileName, genericTypeMapExpression.MemberList); var mappingExpression = CreateMappingExpression(typeMap, closedGenericTypePair.DestinationType); genericTypeMapExpression.Accept(mappingExpression); return typeMap; } public bool HasOpenGenericTypeMapDefined(ResolutionContext context) { var sourceGenericDefinition = context.SourceType.GetGenericTypeDefinition(); var destGenericDefinition = context.DestinationType.GetGenericTypeDefinition(); var genericTypePair = new TypePair(sourceGenericDefinition, destGenericDefinition); return _typeMapExpressionCache.ContainsKey(genericTypePair); } private IEnumerable<TypePair> GetRelatedTypePairs(TypePair root) { var includeOverrideTypePairs = GetAllTypeMaps() .Where( tm => tm.HasDerivedTypesToInclude() && tm.SourceType.IsAssignableFrom(root.SourceType) && (tm.DestinationTypeOverride ?? tm.DestinationType) != root.DestinationType && tm.DestinationType.IsAssignableFrom(root.DestinationType)) .Select( tm => new TypePair(tm.SourceType, tm.DestinationTypeOverride ?? tm.GetDerivedTypeFor(root.SourceType))).ToList(); var subTypePairs = from sourceType in GetAllTypes(root.SourceType) from destinationType in GetAllTypes(root.DestinationType) select new TypePair(sourceType, destinationType); return includeOverrideTypePairs.Concat(subTypePairs); } private IEnumerable<Type> GetAllTypes(Type type) { yield return type; if (type.IsValueType() && !type.IsNullableType()) yield return typeof (Nullable<>).MakeGenericType(type); Type baseType = type.BaseType(); while (baseType != null) { yield return baseType; baseType = baseType.BaseType(); } foreach (var interfaceType in type.GetInterfaces()) { yield return interfaceType; } } public IProfileConfiguration GetProfileConfiguration(string profileName) { return GetProfile(profileName); } public void AssertConfigurationIsValid(TypeMap typeMap) { AssertConfigurationIsValid(Enumerable.Repeat(typeMap, 1)); } public void AssertConfigurationIsValid(string profileName) { AssertConfigurationIsValid(_userDefinedTypeMaps.Values.Where(typeMap => typeMap.Profile == profileName)); } public void AssertConfigurationIsValid<TProfile>() where TProfile : Profile, new() { AssertConfigurationIsValid(new TProfile().ProfileName); } public void AssertConfigurationIsValid() { AssertConfigurationIsValid(_userDefinedTypeMaps.Values); } ////TODO: this was unnecessary in the MapperContext work //public IObjectMapper[] GetMappers() //{ // return _mappers.ToArray(); //} private IMappingExpression<TSource, TDestination> CreateMappingExpression<TSource, TDestination>(TypeMap typeMap) { var mappingExp = new MappingExpression<TSource, TDestination>(typeMap, _serviceCtor, this); var type = (typeMap.ConfiguredMemberList == MemberList.Destination) ? typeof (TDestination) : typeof (TSource); return Ignore(mappingExp, type); } private IMappingExpression<TSource, TDestination> Ignore<TSource, TDestination>( IMappingExpression<TSource, TDestination> mappingExp, Type destinationType) { var destInfo = new TypeInfo(destinationType, ShouldMapProperty, ShouldMapField); foreach (var destProperty in destInfo.PublicWriteAccessors) { var attrs = destProperty.GetCustomAttributes(true); if (attrs.Any(x => x is IgnoreMapAttribute)) { mappingExp = mappingExp.ForMember(destProperty.Name, y => y.Ignore()); } if (_globalIgnore.Contains(destProperty.Name)) { mappingExp = mappingExp.ForMember(destProperty.Name, y => y.Ignore()); } } return mappingExp; } private IMappingExpression CreateMappingExpression(TypeMap typeMap, Type destinationType) { var mappingExp = new MappingExpression(typeMap, _serviceCtor, this); return (IMappingExpression) Ignore(mappingExp, destinationType); } private void AssertConfigurationIsValid(IEnumerable<TypeMap> typeMaps) { Seal(); var maps = typeMaps as TypeMap[] ?? typeMaps.ToArray(); var badTypeMaps = (from typeMap in maps where ShouldCheckMap(typeMap) let unmappedPropertyNames = typeMap.GetUnmappedPropertyNames() where unmappedPropertyNames.Length > 0 select new MicroMapperConfigurationException.TypeMapConfigErrors(typeMap, unmappedPropertyNames) ).ToArray(); if (badTypeMaps.Any()) { throw new MicroMapperConfigurationException(badTypeMaps); } var typeMapsChecked = new List<TypeMap>(); var configExceptions = new List<Exception>(); foreach (var typeMap in maps) { try { DryRunTypeMap(typeMapsChecked, new ResolutionContext(typeMap, null, typeMap.SourceType, typeMap.DestinationType, new MappingOperationOptions(), MapperContext)); } catch (Exception e) { configExceptions.Add(e); } } if (configExceptions.Count > 1) { throw new AggregateException(configExceptions); } if (configExceptions.Count > 0) { throw configExceptions[0]; } } private static bool ShouldCheckMap(TypeMap typeMap) { return (typeMap.CustomMapper == null && typeMap.CustomProjection == null && typeMap.DestinationTypeOverride == null) && !FeatureDetector.IsIDataRecordType(typeMap.SourceType); } private void DryRunTypeMap(ICollection<TypeMap> typeMapsChecked, ResolutionContext context) { if (context.TypeMap != null) { typeMapsChecked.Add(context.TypeMap); } var mapperToUse = ObjectMappers.FirstOrDefault(mapper => mapper.IsMatch(context)); if (mapperToUse == null && context.SourceType.IsNullableType()) { var nullableContext = context.CreateValueContext(null, Nullable.GetUnderlyingType(context.SourceType)); mapperToUse = ObjectMappers.FirstOrDefault(mapper => mapper.IsMatch(nullableContext)); } if (mapperToUse == null) { throw new MicroMapperConfigurationException(context); } if (mapperToUse is TypeMapMapper) { // ReSharper disable once PossibleNullReferenceException foreach (var propertyMap in context.TypeMap.GetPropertyMaps()) { if (!propertyMap.IsIgnored()) { var lastResolver = propertyMap.GetSourceValueResolvers().OfType<IMemberResolver>().LastOrDefault(); if (lastResolver != null) { var sourceType = lastResolver.MemberType; var destinationType = propertyMap.DestinationProperty.MemberType; var memberTypeMap = ((IConfigurationProvider) this).ResolveTypeMap(sourceType, destinationType); if (typeMapsChecked.Any(typeMap => Equals(typeMap, memberTypeMap))) continue; var memberContext = context.CreateMemberContext(memberTypeMap, null, null, sourceType, propertyMap); DryRunTypeMap(typeMapsChecked, memberContext); } } } } else if (mapperToUse is ArrayMapper || mapperToUse is EnumerableMapper || mapperToUse is CollectionMapper) { var sourceElementType = TypeHelper.GetElementType(context.SourceType); var destElementType = TypeHelper.GetElementType(context.DestinationType); var itemTypeMap = ((IConfigurationProvider) this).ResolveTypeMap(sourceElementType, destElementType); if (typeMapsChecked.Any(typeMap => Equals(typeMap, itemTypeMap))) return; var memberContext = context.CreateElementContext(itemTypeMap, null, sourceElementType, destElementType, 0); // ReSharper disable once TailRecursiveCall DryRunTypeMap(typeMapsChecked, memberContext); } } protected void OnTypeMapCreated(TypeMap typeMap) { TypeMapCreated?.Invoke(this, new TypeMapCreatedEventArgs(typeMap)); } internal ProfileConfiguration GetProfile(string profileName) { var expr = _formatterProfiles.GetOrAdd(profileName, name => new ProfileConfiguration()); return expr; } public void AddGlobalIgnore(string startingwith) { _globalIgnore.Add(startingwith); } } }
using System; using Assets.Sources.Scripts.UI.Common; using UnityEngine; namespace Memoria.Assets { public class DialogBoxRenderer { public static Boolean ProcessMemoriaTag(Char[] toCharArray, ref Int32 index, BetterList<Color> colors, ref Boolean highShadow, ref Boolean center, ref Boolean justified, ref Int32 ff9Signal, ref Vector3 extraOffset, ref Single tabX, ref Dialog.DialogImage insertImage) { Int32 num = index; Int32 left = toCharArray.Length - index; FFIXTextTag tag = FFIXTextTag.TryRead(toCharArray, ref num, ref left); if (tag == null) return false; switch (tag.Code) { case FFIXTextTagCode.Justified: justified = true; break; case FFIXTextTagCode.Center: center = true; break; case FFIXTextTagCode.Signal: ff9Signal = 10 + tag.Param[0]; break; case FFIXTextTagCode.IncreaseSignal: ff9Signal = 2; break; case FFIXTextTagCode.IncreaseSignalEx: ff9Signal = 2; break; case FFIXTextTagCode.DialogF: extraOffset.x += (tag.Param[0] >= FieldMap.HalfFieldWidth) ? 0f : (tag.Param[0] * UIManager.ResourceXMultipier); break; case FFIXTextTagCode.DialogY: extraOffset.y -= tag.Param[0] * UIManager.ResourceYMultipier; break; case FFIXTextTagCode.DialogX: if (tag.Param[0] == 224) tag.Param[0] = 0; tabX = tag.Param[0] * UIManager.ResourceYMultipier; break; case FFIXTextTagCode.Up: OnButton(out insertImage, index, false, "DBTN", "UP"); break; case FFIXTextTagCode.Down: OnButton(out insertImage, index, false, "DBTN", "DOWN"); break; case FFIXTextTagCode.Left: OnButton(out insertImage, index, false, "DBTN", "LEFT"); break; case FFIXTextTagCode.Right: OnButton(out insertImage, index, false, "DBTN", "RIGHT"); break; case FFIXTextTagCode.Circle: OnButton(out insertImage, index, false, "DBTN", "CIRCLE"); break; case FFIXTextTagCode.Cross: OnButton(out insertImage, index, false, "DBTN", "CROSS"); break; case FFIXTextTagCode.Triangle: OnButton(out insertImage, index, false, "DBTN", "TRIANGLE"); break; case FFIXTextTagCode.Square: OnButton(out insertImage, index, false, "DBTN", "SQUARE"); break; case FFIXTextTagCode.R1: OnButton(out insertImage, index, false, "DBTN", "R1"); break; case FFIXTextTagCode.R2: OnButton(out insertImage, index, false, "DBTN", "R2"); break; case FFIXTextTagCode.L1: OnButton(out insertImage, index, false, "DBTN", "L1"); break; case FFIXTextTagCode.L2: OnButton(out insertImage, index, false, "DBTN", "L2"); break; case FFIXTextTagCode.Select: OnButton(out insertImage, index, false, "DBTN", "SELECT"); break; case FFIXTextTagCode.Start: OnButton(out insertImage, index, false, "DBTN", "START"); break; case FFIXTextTagCode.Pad: OnButton(out insertImage, index, false, "DBTN", "PAD"); break; case FFIXTextTagCode.UpEx: OnButton(out insertImage, index, true, "CBTN", "UP"); break; case FFIXTextTagCode.DownEx: OnButton(out insertImage, index, true, "CBTN", "DOWN"); break; case FFIXTextTagCode.LeftEx: OnButton(out insertImage, index, true, "CBTN", "LEFT"); break; case FFIXTextTagCode.RightEx: OnButton(out insertImage, index, true, "CBTN", "RIGHT"); break; case FFIXTextTagCode.CircleEx: OnButton(out insertImage, index, true, "CBTN", "CIRCLE"); break; case FFIXTextTagCode.CrossEx: OnButton(out insertImage, index, true, "CBTN", "CROSS"); break; case FFIXTextTagCode.TriangleEx: OnButton(out insertImage, index, true, "CBTN", "TRIANGLE"); break; case FFIXTextTagCode.SquareEx: OnButton(out insertImage, index, true, "CBTN", "SQUARE"); break; case FFIXTextTagCode.R1Ex: OnButton(out insertImage, index, true, "CBTN", "R1"); break; case FFIXTextTagCode.R2Ex: OnButton(out insertImage, index, true, "CBTN", "R2"); break; case FFIXTextTagCode.L1Ex: OnButton(out insertImage, index, true, "CBTN", "L1"); break; case FFIXTextTagCode.L2Ex: OnButton(out insertImage, index, true, "CBTN", "L2"); break; case FFIXTextTagCode.SelectEx: OnButton(out insertImage, index, true, "CBTN", "SELECT"); break; case FFIXTextTagCode.StartEx: OnButton(out insertImage, index, true, "CBTN", "START"); break; case FFIXTextTagCode.PadEx: OnButton(out insertImage, index, true, "CBTN", "PAD"); break; case FFIXTextTagCode.Icon: OnIcon(index, out insertImage, tag.Param[0]); break; case FFIXTextTagCode.IconEx: OnIconEx(index, out insertImage); break; case FFIXTextTagCode.Mobile: OnMobileIcon(index, ref insertImage, tag.Param[0]); break; case FFIXTextTagCode.Tab: extraOffset.x += (18 - 4f) * UIManager.ResourceXMultipier; break; case FFIXTextTagCode.White: OnColor(colors, "C8C8C8"); highShadow = true; break; case FFIXTextTagCode.Pink: OnColor(colors, "B880E0"); highShadow = true; break; case FFIXTextTagCode.Cyan: OnColor(colors, "68C0D8"); highShadow = true; break; case FFIXTextTagCode.Brown: OnColor(colors, "D06050"); highShadow = true; break; case FFIXTextTagCode.Yellow: OnColor(colors, "C8B040"); highShadow = true; break; case FFIXTextTagCode.Green: OnColor(colors, "78C840"); highShadow = true; break; case FFIXTextTagCode.Grey: OnColor(colors, "909090"); highShadow = true; break; case FFIXTextTagCode.DialogSize: case FFIXTextTagCode.Choice: case FFIXTextTagCode.Time: case FFIXTextTagCode.Flash: case FFIXTextTagCode.NoAnimation: case FFIXTextTagCode.Instantly: case FFIXTextTagCode.Speed: case FFIXTextTagCode.Zidane: case FFIXTextTagCode.Vivi: case FFIXTextTagCode.Dagger: case FFIXTextTagCode.Steiner: case FFIXTextTagCode.Fraya: case FFIXTextTagCode.Quina: case FFIXTextTagCode.Eiko: case FFIXTextTagCode.Amarant: case FFIXTextTagCode.Party: case FFIXTextTagCode.NoFocus: case FFIXTextTagCode.End: case FFIXTextTagCode.Text: case FFIXTextTagCode.Item: case FFIXTextTagCode.Variable: case FFIXTextTagCode.Wait: case FFIXTextTagCode.PreChoose: case FFIXTextTagCode.PreChooseMask: case FFIXTextTagCode.Position: case FFIXTextTagCode.Offset: case FFIXTextTagCode.LowerRight: case FFIXTextTagCode.LowerLeft: case FFIXTextTagCode.UpperRight: case FFIXTextTagCode.UpperLeft: case FFIXTextTagCode.LowerCenter: case FFIXTextTagCode.UpperCenter: case FFIXTextTagCode.LowerRightForce: case FFIXTextTagCode.LowerLeftForce: case FFIXTextTagCode.UpperRightForce: case FFIXTextTagCode.UpperLeftForce: case FFIXTextTagCode.DialogPosition: case FFIXTextTagCode.Table: case FFIXTextTagCode.Widths: case FFIXTextTagCode.NewPage: index = num; return true; default: return false; } index = num; return true; } private static void OnColor(BetterList<Color> colors, String colorText) { Color color = NGUIText.ParseColor24(colorText, 0); if (colors != null) { color.a = colors[colors.size - 1].a; if (NGUIText.premultiply && color.a != 1f) { color = Color.Lerp(NGUIText.mInvisible, color, color.a); } colors.Add(color); } } private static void PhraseRenderOpcodeSymbol(Char[] text, Int32 index, ref Int32 closingBracket, String tag, ref Boolean highShadow, ref Boolean center, ref Int32 ff9Signal, ref Vector3 extraOffset, ref Single tabX, ref Dialog.DialogImage insertImage) { if (tag == NGUIText.Center) { closingBracket = Array.IndexOf(text, ']', index + 4); center = true; } else if (tag == NGUIText.Shadow) { closingBracket = Array.IndexOf(text, ']', index + 4); highShadow = true; } else if (tag == NGUIText.NoShadow) { closingBracket = Array.IndexOf(text, ']', index + 4); highShadow = false; } else if (tag == NGUIText.Signal) { Int32 oneParameterFromTag = NGUIText.GetOneParameterFromTag(text, index, ref closingBracket); ff9Signal = 10 + oneParameterFromTag; } else if (tag == NGUIText.IncreaseSignal) { closingBracket = Array.IndexOf(text, ']', index + 4); ff9Signal = 2; } else if (tag == NGUIText.MessageFeed) { Single[] allParameters = NGUIText.GetAllParameters(text, index, ref closingBracket); extraOffset.x += ((allParameters[0] >= FieldMap.HalfFieldWidth) ? 0f : (allParameters[0] * UIManager.ResourceXMultipier)); } else if (tag == NGUIText.YSubOffset) { Single[] allParameters2 = NGUIText.GetAllParameters(text, index, ref closingBracket); extraOffset.y += allParameters2[0] * UIManager.ResourceYMultipier; } else if (tag == NGUIText.YAddOffset) { Single[] allParameters3 = NGUIText.GetAllParameters(text, index, ref closingBracket); extraOffset.y -= allParameters3[0] * UIManager.ResourceYMultipier; } else if (tag == NGUIText.MessageTab) { Single[] allParameters4 = NGUIText.GetAllParameters(text, index, ref closingBracket); if (allParameters4[0] == 224f) { allParameters4[0] = 0f; } tabX = allParameters4[0] * UIManager.ResourceYMultipier; } else if (tag == NGUIText.CustomButtonIcon || tag == NGUIText.ButtonIcon || tag == NGUIText.JoyStickButtonIcon || tag == NGUIText.KeyboardButtonIcon) { closingBracket = Array.IndexOf(text, ']', index + 4); String parameterStr = new String(text, index + 6, closingBracket - index - 6); Boolean checkConfig = tag == NGUIText.CustomButtonIcon || tag == NGUIText.JoyStickButtonIcon; OnButton(out insertImage, index, checkConfig, tag, parameterStr); } else if (tag == NGUIText.IconVar) { Int32 oneParameterFromTag2 = NGUIText.GetOneParameterFromTag(text, index, ref closingBracket); OnIcon(index, out insertImage, oneParameterFromTag2); } else if (tag == NGUIText.NewIcon) { Int32 oneParameterFromTag3 = NGUIText.GetOneParameterFromTag(text, index, ref closingBracket); OnIconEx(index, out insertImage); } else if (tag == NGUIText.MobileIcon) { Int32 oneParameterFromTag4 = NGUIText.GetOneParameterFromTag(text, index, ref closingBracket); OnMobileIcon(index, ref insertImage, oneParameterFromTag4); } else if (tag == NGUIText.TextOffset) { Single[] allParameters5 = NGUIText.GetAllParameters(text, index, ref closingBracket); extraOffset.x += (allParameters5[0] - 4f) * UIManager.ResourceXMultipier; extraOffset.y -= allParameters5[1] * UIManager.ResourceYMultipier; } else { closingBracket = Array.IndexOf(text, ']', index + 4); } } private static void OnMobileIcon(Int32 index, ref Dialog.DialogImage insertImage, Int32 oneParameterFromTag4) { if (FF9StateSystem.MobilePlatform) { insertImage = NGUIText.CreateIconImage(oneParameterFromTag4); insertImage.TextPosition = index; } } private static void OnIconEx(Int32 index, out Dialog.DialogImage insertImage) { insertImage = NGUIText.CreateIconImage(FF9UIDataTool.NewIconId); insertImage.TextPosition = index; } private static void OnIcon(Int32 index, out Dialog.DialogImage insertImage, Int32 oneParameterFromTag2) { insertImage = NGUIText.CreateIconImage(oneParameterFromTag2); insertImage.TextPosition = index; } private static void OnButton(out Dialog.DialogImage insertImage, Int32 index, Boolean checkConfig, String tag, String parameterStr) { insertImage = NGUIText.CreateButtonImage(parameterStr, checkConfig, tag); insertImage.TextPosition = index; } public static Boolean ProcessOriginalTag(Char[] text, ref Int32 index, ref Boolean highShadow, ref Boolean center, ref Int32 ff9Signal, ref Vector3 extraOffset, ref Single tabX, ref Dialog.DialogImage insertImage) { if (index + 6 > text.Length || text[index] != '[') return false; Int32 num = index; String a = new String(text, index, 5); String[] renderOpcodeSymbols = NGUIText.RenderOpcodeSymbols; for (Int32 i = 0; i < (Int32)renderOpcodeSymbols.Length; i++) { String text2 = renderOpcodeSymbols[i]; if (a == "[" + text2) { PhraseRenderOpcodeSymbol(text, index, ref num, text2, ref highShadow, ref center, ref ff9Signal, ref extraOffset, ref tabX, ref insertImage); break; } } if (num == index) { return false; } if (num != -1) { index = num + 1; return true; } index = text.Length; return true; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the Apache 2.0 License. // See the LICENSE file in the project root for more information. using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Text; using IronPython.Runtime.Operations; using Microsoft.Scripting; using Microsoft.Scripting.Runtime; using System.Numerics; namespace IronPython.Runtime { /// <summary> /// StringFormatter provides Python's % style string formatting services. /// </summary> internal class StringFormatter { const int UnspecifiedPrecision = -1; // Use the default precision private readonly CodeContext/*!*/ _context; private readonly bool _isUnicodeString; // true if the LHS is Unicode and we should call __unicode__ for formatting objects on the RHS private object _data; private int _dataIndex; private string _str; private int _index; private char _curCh; // The options for formatting the current formatting specifier in the format string internal FormatSettings _opts; // Should ddd.0 be displayed as "ddd" or "ddd.0". "'%g' % ddd.0" needs "ddd", but str(ddd.0) needs "ddd.0" internal bool _TrailingZeroAfterWholeFloat = false; private StringBuilder _buf; // This is a ThreadStatic since so that formatting operations on one thread do not interfere with other threads [ThreadStatic] private static NumberFormatInfo NumberFormatInfoForThreadLower; [ThreadStatic] private static NumberFormatInfo NumberFormatInfoForThreadUpper; internal static NumberFormatInfo nfil { get { if (NumberFormatInfoForThreadLower == null) { NumberFormatInfo numberFormatInfo = ((CultureInfo)CultureInfo.InvariantCulture.Clone()).NumberFormat; // The CLI formats as "Infinity", but CPython formats differently numberFormatInfo.PositiveInfinitySymbol = "inf"; numberFormatInfo.NegativeInfinitySymbol = "-inf"; numberFormatInfo.NaNSymbol = "nan"; NumberFormatInfoForThreadLower = numberFormatInfo; } return NumberFormatInfoForThreadLower; } } internal static NumberFormatInfo nfiu { get { if (NumberFormatInfoForThreadUpper == null) { NumberFormatInfo numberFormatInfo = ((CultureInfo)CultureInfo.InvariantCulture.Clone()).NumberFormat; // The CLI formats as "Infinity", but CPython formats differently numberFormatInfo.PositiveInfinitySymbol = "INF"; numberFormatInfo.NegativeInfinitySymbol = "-INF"; numberFormatInfo.NaNSymbol = "NAN"; NumberFormatInfoForThreadUpper = numberFormatInfo; } return NumberFormatInfoForThreadUpper; } } private NumberFormatInfo _nfi; #region Constructors public StringFormatter(CodeContext/*!*/ context, string str, object data) : this(context, str, data, false) { } public StringFormatter(CodeContext/*!*/ context, string str, object data, bool isUnicode) { _str = str; _data = data; _context = context; _isUnicodeString = isUnicode; _nfi = nfil; } #endregion #region Public API Surface public string Format() { _index = 0; _buf = new StringBuilder(_str.Length * 2); int modIndex; while ((modIndex = _str.IndexOf('%', _index)) != -1) { _buf.Append(_str, _index, modIndex - _index); _index = modIndex + 1; DoFormatCode(); } _buf.Append(_str, _index, _str.Length - _index); CheckDataUsed(); return _buf.ToString(); } #endregion #region Private APIs private void DoFormatCode() { // we already pulled the first % if (_index == _str.Length) throw PythonOps.ValueError("incomplete format, expected format character at index {0}", _index); // Index is placed right after the %. Debug.Assert(_str[_index - 1] == '%'); _curCh = _str[_index++]; if (_curCh == '%') { // Escaped '%' character using "%%". Just print it and we are done _buf.Append('%'); return; } string key = ReadMappingKey(); _opts = new FormatSettings(); ReadConversionFlags(); ReadMinimumFieldWidth(); ReadPrecision(); ReadLengthModifier(); // use the key (or lack thereof) to get the value object value; if (key == null) { value = GetData(_dataIndex++); } else { value = GetKey(key); } _opts.Value = value; WriteConversion(); } /// <summary> /// Read a possible mapping key for %(key)s. /// </summary> /// <returns>The key name enclosed between the '%(key)s', /// or null if there are no paranthesis such as '%s'.</returns> private string ReadMappingKey() { // Caller has set _curCh to the character past the %, and // _index to 2 characters past the original '%'. Debug.Assert(_curCh == _str[_index - 1]); Debug.Assert(_str[_index - 2] == '%'); if (_curCh != '(') { // No parenthesized key. return null; } // CPython supports nested parenthesis (See "S3.6.2:String Formatting Operations"). // Keywords inbetween %(...)s can contain parenthesis. // // For example, here are the keys returned for various format strings: // %(key)s - return 'key' // %((key))s - return '(key)' // %()s - return '' // %((((key))))s - return '(((key)))' // %((%)s)s - return '(%)s' // %((%s))s - return (%s) // %(a(b)c)s - return a(b)c // %((a)s)s - return (a)s // %(((a)s))s - return ((a)s) // Use a counter rule. int nested = 1; // already passed the 1st '(' int start = _index; // character index after 1st opening '(' int end = start; while (end < _str.Length) { if (_str[end] == '(') { nested++; } else if (_str[end] == ')') { nested--; } if (nested == 0) { // Found final matching closing parent string key = _str.Substring(_index, end - start); // Update fields _index = end + 1; if (_index == _str.Length) { // This error could happen with a format string like '%((key))' throw PythonOps.ValueError("incomplete format"); } _curCh = _str[_index++]; return key; } end++; } // Error: missing closing ')'. // This could happen with '%((key)s' throw PythonOps.ValueError("incomplete format key"); } private void ReadConversionFlags() { bool fFoundConversion; do { fFoundConversion = true; switch (_curCh) { case '#': _opts.AltForm = true; break; case '-': _opts.LeftAdj = true; _opts.ZeroPad = false; break; case '0': if (!_opts.LeftAdj) _opts.ZeroPad = true; break; case '+': _opts.SignChar = true; _opts.Space = false; break; case ' ': if (!_opts.SignChar) _opts.Space = true; break; default: fFoundConversion = false; break; } if (fFoundConversion) _curCh = _str[_index++]; } while (fFoundConversion); } private int ReadNumberOrStar() { return ReadNumberOrStar(0); } private int ReadNumberOrStar(int noValSpecified) { int res = noValSpecified; if (_curCh == '*') { if (!(_data is PythonTuple)) { throw PythonOps.TypeError("* requires a tuple for values"); } _curCh = _str[_index++]; res = _context.LanguageContext.ConvertToInt32(GetData(_dataIndex++)); } else { if (Char.IsDigit(_curCh)) { res = 0; while (Char.IsDigit(_curCh) && _index < this._str.Length) { res = res * 10 + ((int)(_curCh - '0')); _curCh = _str[_index++]; } } } return res; } private void ReadMinimumFieldWidth() { int fieldWidth = ReadNumberOrStar();; if (fieldWidth < 0) { _opts.FieldWidth = fieldWidth * -1; _opts.LeftAdj = true; } else { _opts.FieldWidth = fieldWidth; } if (_opts.FieldWidth == Int32.MaxValue) { throw PythonOps.MemoryError("not enough memory for field width"); } } private void ReadPrecision() { if (_curCh == '.') { _curCh = _str[_index++]; // possibility: "8.f", "8.0f", or "8.2f" _opts.Precision = ReadNumberOrStar(); if (_opts.Precision > 116) throw PythonOps.OverflowError("formatted integer is too long (precision too large?)"); } else { _opts.Precision = UnspecifiedPrecision; } } private void ReadLengthModifier() { switch (_curCh) { // ignored, not necessary for Python case 'h': case 'l': case 'L': _curCh = _str[_index++]; break; } } private void WriteConversion() { // conversion type (required) switch (_curCh) { // signed integer decimal case 'd': case 'i': AppendInt(); return; // unsigned octal case 'o': AppendOctal(); return; // unsigned decimal case 'u': AppendInt(); return; // unsigned hexadecimal case 'x': AppendHex(_curCh); return; case 'X': AppendHex(_curCh); return; // floating point exponential format case 'e': // floating point decimal case 'f': // Same as "e" if exponent is less than -4 or more than precision, "f" otherwise. case 'g': AppendFloat(_curCh); return; // same as 3 above but uppercase case 'E': case 'F': case 'G': _nfi = nfiu; AppendFloat(_curCh); _nfi = nfil; return; // single character (int or single char str) case 'c': AppendChar(); return; // string (repr() version) case 'r': AppendRepr(); return; // string (str() version) case 's': AppendString(); return; default: if (_curCh > 0xff) throw PythonOps.ValueError("unsupported format character '{0}' (0x{1:X}) at index {2}", '?', (int)_curCh, _index - 1); else throw PythonOps.ValueError("unsupported format character '{0}' (0x{1:X}) at index {2}", _curCh, (int)_curCh, _index - 1); } } private object GetData(int index) { if (_data is PythonTuple dt) { if (index < dt.__len__()) { return dt[index]; } } else { if (index == 0) { return _data; } } throw PythonOps.TypeError("not enough arguments for format string"); } private object GetKey(string key) { if (!(_data is IDictionary<object, object> map)) { if (!(_data is PythonDictionary dict)) { if (PythonOps.IsMappingType(DefaultContext.Default, _data) == ScriptingRuntimeHelpers.True) { return PythonOps.GetIndex(_context, _data, key); } throw PythonOps.TypeError("format requires a mapping"); } object res; if (dict.TryGetValue(key, out res)) return res; } else { object res; if (map.TryGetValue(key, out res)) { return res; } } throw PythonOps.KeyError(key); } private object GetIntegerValue(out bool fPos) { object val; int intVal; if (_context.LanguageContext.TryConvertToInt32(_opts.Value, out intVal)) { val = intVal; fPos = intVal >= 0; } else { BigInteger bigInt; if (Converter.TryConvertToBigInteger(_opts.Value, out bigInt)) { val = bigInt; fPos = bigInt >= BigInteger.Zero; } else { throw PythonOps.TypeError("int argument required"); } } return val; } private void AppendChar() { char val = Converter.ExplicitConvertToChar(_opts.Value); if (_opts.FieldWidth > 1) { if (!_opts.LeftAdj) { _buf.Append(' ', _opts.FieldWidth - 1); } _buf.Append(val); if (_opts.LeftAdj) { _buf.Append(' ', _opts.FieldWidth - 1); } } else { _buf.Append(val); } } private void CheckDataUsed() { if (PythonOps.IsMappingType(DefaultContext.Default, _data) == ScriptingRuntimeHelpers.False) { if ((!(_data is PythonTuple) && _dataIndex != 1) || (_data is PythonTuple && _dataIndex != ((PythonTuple)_data).__len__())) { throw PythonOps.TypeError("not all arguments converted during string formatting"); } } } private void AppendInt() { bool fPos; object val = GetIntegerValue(out fPos); if (_opts.LeftAdj) { AppendLeftAdj(val, fPos, 'D'); } else if (_opts.Precision > 0) { // in this case the precision means // the minimum number of characters _opts.FieldWidth = (_opts.Space || _opts.SignChar) ? _opts.Precision + 1 : _opts.Precision; AppendZeroPad(val, fPos, 'D'); } else if (_opts.ZeroPad) { AppendZeroPad(val, fPos, 'D'); } else { AppendNumeric(val, fPos, 'D'); } } private static readonly char[] zero = new char[] { '0' }; // Return the new type char to use private char AdjustForG(char type, double v) { if (type != 'G' && type != 'g') return type; if (Double.IsNaN(v) || Double.IsInfinity(v)) return type; double absV = Math.Abs(v); if (_opts.Precision == 0) { _opts.Precision = 1; } if ((v != 0.0) && // 0.0 should not be displayed as scientific notation absV < 1e-4 || // Values less than 0.0001 will need scientific notation absV >= Math.Pow(10, _opts.Precision)) { // Values bigger than 1e<precision> will need scientific notation type = (type == 'G') ? 'E' : 'e'; // For e/E formatting, precision means the number of digits after the decimal point. // One digit is displayed before the decimal point. int fractionDigitsRequired = (_opts.Precision - 1); string expForm = absV.ToString("E" + fractionDigitsRequired, CultureInfo.InvariantCulture); string mantissa = expForm.Substring(0, expForm.IndexOf('E')).TrimEnd(zero); if (mantissa.Length == 1) { _opts.Precision = 0; } else { // We do -2 to ignore the digit before the decimal point and the decimal point itself Debug.Assert(mantissa[1] == '.'); _opts.Precision = mantissa.Length - 2; } } else { // "0.000ddddd" is allowed when the precision is 5. The 3 leading zeros are not counted int numberDecimalDigits = _opts.Precision; if (absV < 1e-3) numberDecimalDigits += 3; else if (absV < 1e-2) numberDecimalDigits += 2; else if (absV < 1e-1) numberDecimalDigits += 1; string fixedPointForm = absV.ToString("F" + numberDecimalDigits, CultureInfo.InvariantCulture).TrimEnd(zero); bool convertType = true; if (numberDecimalDigits > 15) { // System.Double(0.33333333333333331).ToString("F17") == "0.33333333333333300" string fixedPointFormG = absV.ToString("G" + numberDecimalDigits, CultureInfo.InvariantCulture).TrimEnd(zero); if (fixedPointFormG.Length > fixedPointForm.Length) { fixedPointForm = fixedPointFormG; convertType = false; } } if (convertType) { type = (type == 'G') ? 'F' : 'f'; // For f/F formatting, precision means the number of digits after the decimal point. string fraction = fixedPointForm.Substring(fixedPointForm.IndexOf('.') + 1); if (absV < 1.0) { _opts.Precision = fraction.Length; } else { int digitsBeforeDecimalPoint = 1 + (int)Math.Log10(absV); _opts.Precision = Math.Min(_opts.Precision - digitsBeforeDecimalPoint, fraction.Length); } } } return type; } private void AppendFloat(char type) { double v; if (!Converter.TryConvertToDouble(_opts.Value, out v)) throw PythonOps.TypeError("float argument required"); // scientific exponential format Debug.Assert(type == 'E' || type == 'e' || // floating point decimal type == 'F' || type == 'f' || // Same as "e" if exponent is less than -4 or more than precision, "f" otherwise. type == 'G' || type == 'g'); bool forceDot = false; // update our precision first... if (_opts.Precision != UnspecifiedPrecision) { if (_opts.Precision == 0 && _opts.AltForm) forceDot = true; if (_opts.Precision > 50) _opts.Precision = 50; } else { // alternate form (#) specified, set precision to zero... if (_opts.AltForm) { _opts.Precision = 0; forceDot = true; } else _opts.Precision = 6; } type = AdjustForG(type, v); _nfi.NumberDecimalDigits = _opts.Precision; // then append if (_opts.LeftAdj) { AppendLeftAdj(v, DoubleOps.Sign(v) >= 0, type); } else if (_opts.ZeroPad) { AppendZeroPadFloat(v, type); } else { AppendNumeric(v, DoubleOps.Sign(v) >= 0, type); } if (DoubleOps.Sign(v) < 0 && v > -1 && _buf[0] != '-') { FixupFloatMinus(); } if (forceDot) { FixupAltFormDot(v); } } private void FixupAltFormDot(double v) { if (!double.IsInfinity(v) && !double.IsNaN(v)) { _buf.Append('.'); } if (_opts.FieldWidth != 0) { // try and remove the extra character we're adding. for (int i = 0; i < _buf.Length; i++) { if (_buf[i] == ' ' || _buf[i] == '0') { _buf.Remove(i, 1); break; } else if (_buf[i] != '-' && _buf[i] != '+') { break; } } } } private void FixupFloatMinus() { // Python always appends a - even if precision is 0 and the value would appear to be zero. bool fNeedMinus = true; for (int i = 0; i < _buf.Length; i++) { if (_buf[i] != '.' && _buf[i] != '0' && _buf[i] != ' ') { fNeedMinus = false; break; } } if (fNeedMinus) { if (_opts.FieldWidth != 0) { // trim us back down to the correct field width... if (_buf[_buf.Length - 1] == ' ') { _buf.Insert(0, "-"); _buf.Remove(_buf.Length - 1, 1); } else { int index = 0; while (_buf[index] == ' ') index++; if (index > 0) index--; _buf[index] = '-'; } } else { _buf.Insert(0, "-"); } } } private void AppendZeroPad(object val, bool fPos, char format) { if (fPos && (_opts.SignChar || _opts.Space)) { // produce [' '|'+']0000digits // first get 0 padded number to field width string res = String.Format(_nfi, "{0:" + format + _opts.FieldWidth.ToString() + "}", val); char signOrSpace = _opts.SignChar ? '+' : ' '; // then if we ended up with a leading zero replace it, otherwise // append the space / + to the front. if (res[0] == '0' && res.Length > 1) { res = signOrSpace + res.Substring(1); } else { res = signOrSpace + res; } _buf.Append(res); } else { string res = String.Format(_nfi, "{0:" + format + _opts.FieldWidth.ToString() + "}", val); // Difference: // System.String.Format("{0:D3}", -1) '-001' // "%03d" % -1 '-01' if (res[0] == '-') { // negative _buf.Append("-"); if (res[1] != '0') { _buf.Append(res.Substring(1)); } else { _buf.Append(res.Substring(2)); } } else { // positive _buf.Append(res); } } } private void AppendZeroPadFloat(double val, char format) { if (val >= 0) { StringBuilder res = new StringBuilder(val.ToString(format.ToString(), _nfi)); if (res.Length < _opts.FieldWidth) { res.Insert(0, new string('0', _opts.FieldWidth - res.Length)); } if (_opts.SignChar || _opts.Space) { char signOrSpace = _opts.SignChar ? '+' : ' '; // then if we ended up with a leading zero replace it, otherwise // append the space / + to the front. if (res[0] == '0' && res[1] != '.') { res[0] = signOrSpace; } else { res.Insert(0, signOrSpace.ToString()); } } _buf.Append(res); } else { StringBuilder res = new StringBuilder(val.ToString(format.ToString(), _nfi)); if (res.Length < _opts.FieldWidth) { res.Insert(1, new string('0', _opts.FieldWidth - res.Length)); } _buf.Append(res); } } private void AppendNumeric(object val, bool fPos, char format) { if (format == 'e' || format == 'E') { AppendNumericExp(val, fPos, format); } else { // f, F, g, D AppendNumericDecimal(val, fPos, format); } } private void AppendNumericExp(object val, bool fPos, char format) { Debug.Assert(_opts.Precision != UnspecifiedPrecision); var forceMinus = false; double doubleVal = (double)val; if (IsNegativeZero(doubleVal)) { forceMinus = true; val = 0.0; } if (fPos && (_opts.SignChar || _opts.Space)) { string strval = (_opts.SignChar ? "+" : " ") + String.Format(_nfi, "{0:" + format + _opts.Precision + "}", val); strval = adjustExponent(strval); if (strval.Length < _opts.FieldWidth) { _buf.Append(' ', _opts.FieldWidth - strval.Length); } if (forceMinus) { _buf.Append('-'); } _buf.Append(strval); } else if (_opts.Precision < 100) { //CLR formatting has a maximum precision of 100. string num = String.Format(_nfi, "{0," + _opts.FieldWidth + ":" + format + _opts.Precision + "}", val); num = adjustExponent(num); if (num.Length < _opts.FieldWidth) { _buf.Append(' ', _opts.FieldWidth - num.Length); } if (forceMinus) _buf.Append('-'); _buf.Append(num); } else { AppendNumericCommon(val, format); } } private void AppendNumericDecimal(object val, bool fPos, char format) { if (fPos && (_opts.SignChar || _opts.Space)) { string strval = (_opts.SignChar ? "+" : " ") + String.Format(_nfi, "{0:" + format + "}", val); if (strval.Length < _opts.FieldWidth) { _buf.Append(' ', _opts.FieldWidth - strval.Length); } _buf.Append(strval); } else if (_opts.Precision == UnspecifiedPrecision) { _buf.AppendFormat(_nfi, "{0," + _opts.FieldWidth + ":" + format + "}", val); } else if (_opts.Precision < 100) { //CLR formatting has a maximum precision of 100. _buf.Append(String.Format(_nfi, "{0," + _opts.FieldWidth + ":" + format + _opts.Precision + "}", val)); } else { AppendNumericCommon(val, format); } // If AdjustForG() sets opts.Precision == 0, it means that no significant digits should be displayed after // the decimal point. ie. 123.4 should be displayed as "123", not "123.4". However, we might still need a // decorative ".0". ie. to display "123.0" if (_TrailingZeroAfterWholeFloat && (format == 'f' || format == 'F') && _opts.Precision == 0) _buf.Append(".0"); } private void AppendNumericCommon(object val, char format) { StringBuilder res = new StringBuilder(); res.AppendFormat("{0:" + format + "}", val); if (res.Length < _opts.Precision) { res.Insert(0, new String('0', _opts.Precision - res.Length)); } if (res.Length < _opts.FieldWidth) { res.Insert(0, new String(' ', _opts.FieldWidth - res.Length)); } _buf.Append(res.ToString()); } // A strange string formatting bug requires that we use Standard Numeric Format and // not Custom Numeric Format. Standard Numeric Format produces always a 3 digit exponent // which needs to be taken care off. // Example: 9.3126672485384569e+23, precision=16 // format string "e16" ==> "9.3126672485384569e+023", but we want "e+23", not "e+023" // format string "0.0000000000000000e+00" ==> "9.3126672485384600e+23", which is a precision error // so, we have to format with "e16" and strip the zero manually private string adjustExponent(string val) { if (val[val.Length - 3] == '0') { return val.Substring(0, val.Length - 3) + val.Substring(val.Length - 2, 2); } else { return val; } } private void AppendLeftAdj(object val, bool fPos, char type) { var str = (type == 'e' || type == 'E') ? adjustExponent(String.Format(_nfi, "{0:" + type + _opts.Precision + "}", val)): String.Format(_nfi, "{0:" + type + "}", val); if (fPos) { if (_opts.SignChar) str = '+' + str; else if (_opts.Space) str = ' ' + str; } _buf.Append(str); if (str.Length < _opts.FieldWidth) _buf.Append(' ', _opts.FieldWidth - str.Length); } private static bool NeedsAltForm(char format, char last) { if (format == 'X' || format == 'x') return true; if (last == '0') return false; return true; } private static string GetAltFormPrefixForRadix(char format, int radix) { switch (radix) { case 8: return "0"; case 16: return format + "0"; } return ""; } /// <summary> /// AppendBase appends an integer at the specified radix doing all the /// special forms for Python. We have a copy and paste version of this /// for BigInteger below that should be kept in sync. /// </summary> private void AppendBase(char format, int radix) { bool fPos; object intVal = GetIntegerValue(out fPos); if (intVal is BigInteger) { AppendBaseBigInt((BigInteger)intVal, format, radix); return; } int origVal = (int)intVal; int val = origVal; if (val < 0) { val *= -1; // if negative number, the leading space has no impact _opts.Space = false; } // we build up the number backwards inside a string builder, // and after we've finished building this up we append the // string to our output buffer backwards. // convert value to string StringBuilder str = new StringBuilder(); if (val == 0) str.Append('0'); while (val != 0) { int digit = val % radix; if (digit < 10) str.Append((char)((digit) + '0')); else if (Char.IsLower(format)) str.Append((char)((digit - 10) + 'a')); else str.Append((char)((digit - 10) + 'A')); val /= radix; } // pad out for additional precision if (str.Length < _opts.Precision) { int len = _opts.Precision - str.Length; str.Append('0', len); } // pad result to minimum field width if (_opts.FieldWidth != 0) { int signLen = (origVal < 0 || _opts.SignChar) ? 1 : 0; int spaceLen = _opts.Space ? 1 : 0; int len = _opts.FieldWidth - (str.Length + signLen + spaceLen); if (len > 0) { // we account for the size of the alternate form, if we'll end up adding it. if (_opts.AltForm && NeedsAltForm(format, (!_opts.LeftAdj && _opts.ZeroPad) ? '0' : str[str.Length - 1])) { len -= GetAltFormPrefixForRadix(format, radix).Length; } if (len > 0) { // and finally append the right form if (_opts.LeftAdj) { str.Insert(0, " ", len); } else { if (_opts.ZeroPad) { str.Append('0', len); } else { _buf.Append(' ', len); } } } } } // append the alternate form if (_opts.AltForm && NeedsAltForm(format, str[str.Length - 1])) str.Append(GetAltFormPrefixForRadix(format, radix)); // add any sign if necessary if (origVal < 0) { _buf.Append('-'); } else if (_opts.SignChar) { _buf.Append('+'); } else if (_opts.Space) { _buf.Append(' '); } // append the final value for (int i = str.Length - 1; i >= 0; i--) { _buf.Append(str[i]); } } /// <summary> /// BigInteger version of AppendBase. Should be kept in sync w/ AppendBase /// </summary> private void AppendBaseBigInt(BigInteger origVal, char format, int radix) { BigInteger val = origVal; if (val < 0) val *= -1; // convert value to octal StringBuilder str = new StringBuilder(); // use .NETs faster conversion if we can if (radix == 16) { AppendNumberReversed(str, Char.IsLower(format) ? val.ToString("x") : val.ToString("X")); } else if (radix == 10) { AppendNumberReversed(str, val.ToString()); } else { if (val == 0) str.Append('0'); while (val != 0) { int digit = (int)(val % radix); if (digit < 10) str.Append((char)((digit) + '0')); else if (Char.IsLower(format)) str.Append((char)((digit - 10) + 'a')); else str.Append((char)((digit - 10) + 'A')); val /= radix; } } // pad out for additional precision if (str.Length < _opts.Precision) { int len = _opts.Precision - str.Length; str.Append('0', len); } // pad result to minimum field width if (_opts.FieldWidth != 0) { int signLen = (origVal < 0 || _opts.SignChar) ? 1 : 0; int len = _opts.FieldWidth - (str.Length + signLen); if (len > 0) { // we account for the size of the alternate form, if we'll end up adding it. if (_opts.AltForm && NeedsAltForm(format, (!_opts.LeftAdj && _opts.ZeroPad) ? '0' : str[str.Length - 1])) { len -= GetAltFormPrefixForRadix(format, radix).Length; } if (len > 0) { // and finally append the right form if (_opts.LeftAdj) { str.Insert(0, " ", len); } else { if (_opts.ZeroPad) { str.Append('0', len); } else { _buf.Append(' ', len); } } } } } // append the alternate form if (_opts.AltForm && NeedsAltForm(format, str[str.Length - 1])) str.Append(GetAltFormPrefixForRadix(format, radix)); // add any sign if necessary if (origVal < 0) { _buf.Append('-'); } else if (_opts.SignChar) { _buf.Append('+'); } else if (_opts.Space) { _buf.Append(' '); } // append the final value for (int i = str.Length - 1; i >= 0; i--) { _buf.Append(str[i]); } } private static void AppendNumberReversed(StringBuilder str, string res) { int start = 0; while (start < (res.Length - 1) && res[start] == '0') { start++; } for (int i = res.Length - 1; i >= start; i--) { str.Append(res[i]); } } private void AppendHex(char format) { AppendBase(format, 16); } private void AppendOctal() { AppendBase('o', 8); } private void AppendString() { string s; if (!_isUnicodeString) { s = PythonOps.ToString(_context, _opts.Value); } else { object o = StringOps.FastNewUnicode(_context, _opts.Value); s = o as string; if (s == null) { s = ((Extensible<string>)o).Value; } } if (s == null) s = "None"; AppendString(s); } private void AppendRepr() { AppendString(PythonOps.Repr(_context, _opts.Value)); } private void AppendString(string s) { if (_opts.Precision != UnspecifiedPrecision && s.Length > _opts.Precision) s = s.Substring(0, _opts.Precision); if (!_opts.LeftAdj && _opts.FieldWidth > s.Length) { _buf.Append(' ', _opts.FieldWidth - s.Length); } _buf.Append(s); if (_opts.LeftAdj && _opts.FieldWidth > s.Length) { _buf.Append(' ', _opts.FieldWidth - s.Length); } } private static readonly long NegativeZeroBits = BitConverter.DoubleToInt64Bits(-0.0); internal static bool IsNegativeZero(double x) { // -0.0 == 0.0 is True, so detecting -0.0 uses memory representation return BitConverter.DoubleToInt64Bits(x) == NegativeZeroBits; } #endregion #region Private data structures // The conversion specifier format is as follows: // % (mappingKey) conversionFlags fieldWidth . precision lengthModifier conversionType // where: // mappingKey - value to be formatted // conversionFlags - # 0 - + <space> // lengthModifier - h, l, and L. Ignored by Python // conversionType - d i o u x X e E f F g G c r s % // Ex: // %(varName)#4o - Display "varName" as octal and prepend with leading 0 if necessary, for a total of atleast 4 characters [Flags] internal enum FormatOptions { ZeroPad = 0x01, // Use zero-padding to fit FieldWidth LeftAdj = 0x02, // Use left-adjustment to fit FieldWidth. Overrides ZeroPad AltForm = 0x04, // Add a leading 0 if necessary for octal, or add a leading 0x or 0X for hex Space = 0x08, // Leave a white-space SignChar = 0x10 // Force usage of a sign char even if the value is positive } internal struct FormatSettings { #region FormatOptions property accessors public bool ZeroPad { get { return ((Options & FormatOptions.ZeroPad) != 0); } set { if (value) { Options |= FormatOptions.ZeroPad; } else { Options &= (~FormatOptions.ZeroPad); } } } public bool LeftAdj { get { return ((Options & FormatOptions.LeftAdj) != 0); } set { if (value) { Options |= FormatOptions.LeftAdj; } else { Options &= (~FormatOptions.LeftAdj); } } } public bool AltForm { get { return ((Options & FormatOptions.AltForm) != 0); } set { if (value) { Options |= FormatOptions.AltForm; } else { Options &= (~FormatOptions.AltForm); } } } public bool Space { get { return ((Options & FormatOptions.Space) != 0); } set { if (value) { Options |= FormatOptions.Space; } else { Options &= (~FormatOptions.Space); } } } public bool SignChar { get { return ((Options & FormatOptions.SignChar) != 0); } set { if (value) { Options |= FormatOptions.SignChar; } else { Options &= (~FormatOptions.SignChar); } } } #endregion internal FormatOptions Options; // Minimum number of characters that the entire formatted string should occupy. // Smaller results will be left-padded with white-space or zeros depending on Options internal int FieldWidth; // Number of significant digits to display, before and after the decimal point. // For floats (except G/g format specification), it gets adjusted to the number of // digits to display after the decimal point since that is the value required by // the .NET string formatting. // For clarity, we should break this up into the two values - the precision specified by the // format string, and the value to be passed in to StringBuilder.AppendFormat internal int Precision; internal object Value; } #endregion } }
// 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 gcrv = Google.Cloud.Retail.V2; using sys = System; namespace Google.Cloud.Retail.V2 { /// <summary>Resource name for the <c>Catalog</c> resource.</summary> public sealed partial class CatalogName : gax::IResourceName, sys::IEquatable<CatalogName> { /// <summary>The possible contents of <see cref="CatalogName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>projects/{project}/locations/{location}/catalogs/{catalog}</c>. /// </summary> ProjectLocationCatalog = 1, } private static gax::PathTemplate s_projectLocationCatalog = new gax::PathTemplate("projects/{project}/locations/{location}/catalogs/{catalog}"); /// <summary>Creates a <see cref="CatalogName"/> 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="CatalogName"/> containing the provided <paramref name="unparsedResourceName"/>. /// </returns> public static CatalogName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new CatalogName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="CatalogName"/> with the pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="CatalogName"/> constructed from the provided ids.</returns> public static CatalogName FromProjectLocationCatalog(string projectId, string locationId, string catalogId) => new CatalogName(ResourceNameType.ProjectLocationCatalog, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), catalogId: gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="CatalogName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CatalogName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}</c>. /// </returns> public static string Format(string projectId, string locationId, string catalogId) => FormatProjectLocationCatalog(projectId, locationId, catalogId); /// <summary> /// Formats the IDs into the string representation of this <see cref="CatalogName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}</c>. /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="CatalogName"/> with pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}</c>. /// </returns> public static string FormatProjectLocationCatalog(string projectId, string locationId, string catalogId) => s_projectLocationCatalog.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId))); /// <summary>Parses the given resource name string into a new <see cref="CatalogName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/catalogs/{catalog}</c></description></item> /// </list> /// </remarks> /// <param name="catalogName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="CatalogName"/> if successful.</returns> public static CatalogName Parse(string catalogName) => Parse(catalogName, false); /// <summary> /// Parses the given resource name string into a new <see cref="CatalogName"/> 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>projects/{project}/locations/{location}/catalogs/{catalog}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="catalogName">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="CatalogName"/> if successful.</returns> public static CatalogName Parse(string catalogName, bool allowUnparsed) => TryParse(catalogName, allowUnparsed, out CatalogName 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="CatalogName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>projects/{project}/locations/{location}/catalogs/{catalog}</c></description></item> /// </list> /// </remarks> /// <param name="catalogName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="CatalogName"/>, 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 catalogName, out CatalogName result) => TryParse(catalogName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="CatalogName"/> 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>projects/{project}/locations/{location}/catalogs/{catalog}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="catalogName">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="CatalogName"/>, 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 catalogName, bool allowUnparsed, out CatalogName result) { gax::GaxPreconditions.CheckNotNull(catalogName, nameof(catalogName)); gax::TemplatedResourceName resourceName; if (s_projectLocationCatalog.TryParseName(catalogName, out resourceName)) { result = FromProjectLocationCatalog(resourceName[0], resourceName[1], resourceName[2]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(catalogName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private CatalogName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string catalogId = null, string locationId = null, string projectId = null) { Type = type; UnparsedResource = unparsedResourceName; CatalogId = catalogId; LocationId = locationId; ProjectId = projectId; } /// <summary> /// Constructs a new instance of a <see cref="CatalogName"/> class from the component parts of pattern /// <c>projects/{project}/locations/{location}/catalogs/{catalog}</c> /// </summary> /// <param name="projectId">The <c>Project</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="locationId">The <c>Location</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="catalogId">The <c>Catalog</c> ID. Must not be <c>null</c> or empty.</param> public CatalogName(string projectId, string locationId, string catalogId) : this(ResourceNameType.ProjectLocationCatalog, projectId: gax::GaxPreconditions.CheckNotNullOrEmpty(projectId, nameof(projectId)), locationId: gax::GaxPreconditions.CheckNotNullOrEmpty(locationId, nameof(locationId)), catalogId: gax::GaxPreconditions.CheckNotNullOrEmpty(catalogId, nameof(catalogId))) { } /// <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>Catalog</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CatalogId { get; } /// <summary> /// The <c>Location</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string LocationId { get; } /// <summary> /// The <c>Project</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string ProjectId { 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.ProjectLocationCatalog: return s_projectLocationCatalog.Expand(ProjectId, LocationId, CatalogId); 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 CatalogName); /// <inheritdoc/> public bool Equals(CatalogName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(CatalogName a, CatalogName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(CatalogName a, CatalogName b) => !(a == b); } public partial class Catalog { /// <summary> /// <see cref="gcrv::CatalogName"/>-typed view over the <see cref="Name"/> resource name property. /// </summary> public gcrv::CatalogName CatalogName { get => string.IsNullOrEmpty(Name) ? null : gcrv::CatalogName.Parse(Name, allowUnparsed: true); set => Name = value?.ToString() ?? ""; } } }
/* * Copyright (c) InWorldz Halcyon Developers * Copyright (c) Contributors, http://opensimulator.org/ * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSim Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Reflection; using System.Text.RegularExpressions; using System.Threading; using log4net; using OpenMetaverse; using OpenSim.Framework; using OpenSim.Region.Framework.Scenes.Serialization; namespace OpenSim.Region.Framework.Scenes { /// <summary> /// Gather uuids for a given entity. /// </summary> /// /// This does a deep inspection of the entity to retrieve all the assets it uses (whether as textures, as scripts /// contained in inventory, as scripts contained in objects contained in another object's inventory, etc. Assets /// are only retrieved when they are necessary to carry out the inspection (i.e. a serialized object needs to be /// retrieved to work out which assets it references). public class UuidGatherer { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); /// <summary> /// Asset cache used for gathering assets /// </summary> protected IAssetCache m_assetCache; /// <summary> /// Used as a temporary store of an asset which represents an object. This can be a null if no appropriate /// asset was found by the asset service. /// </summary> protected AssetBase m_requestedObjectAsset; /// <summary> /// Signal whether we are currently waiting for the asset service to deliver an asset. /// </summary> protected bool m_waitingForObjectAsset; // Needed for decoding Thoosa-serialized scene objects. private IInventoryObjectSerializer m_inventorySerializer = null; public UuidGatherer(IAssetCache assetCache) { m_assetCache = assetCache; ISerializationEngine engine; if (ProviderRegistry.Instance.TryGet<ISerializationEngine>(out engine)) { m_inventorySerializer = engine.InventoryObjectSerializer; } } /// <summary> /// Gather all the asset uuids associated with the asset referenced by a given uuid /// </summary> /// /// This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// /// <param name="assetUuid">The uuid of the asset for which to gather referenced assets</param> /// <param name="assetType">The type of the asset for the uuid given</param> /// <param name="assetUuids">The assets gathered</param> public void GatherAssetUuids(UUID assetUuid, AssetType assetType, IDictionary<UUID, int> assetUuids) { assetUuids[assetUuid] = 1; if (AssetType.Bodypart == assetType || AssetType.Clothing == assetType) { GetWearableAssetUuids(assetUuid, assetUuids); } else if (AssetType.LSLText == assetType) { GetScriptAssetUuids(assetUuid, assetUuids); } else if (AssetType.Object == assetType) { GetSceneObjectAssetUuids(assetUuid, assetUuids); } } /// <summary> /// Gather all the asset uuids associated with a given object. /// </summary> /// /// This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// /// <param name="sceneObject">The scene object for which to gather assets</param> /// <param name="assetUuids">The assets gathered</param> public void GatherAssetUuids(SceneObjectGroup sceneObject, IDictionary<UUID, int> assetUuids) { // m_log.DebugFormat( // "[ASSET GATHERER]: Getting assets for object {0}, {1}", sceneObject.Name, sceneObject.UUID); foreach (SceneObjectPart part in sceneObject.GetParts()) { //m_log.DebugFormat( // "[ARCHIVER]: Getting part {0}, {1} for object {2}", part.Name, part.UUID, sceneObject.UUID); try { Primitive.TextureEntry textureEntry = part.Shape.Textures; // Get the prim's default texture. This will be used for faces which don't have their own texture assetUuids[textureEntry.DefaultTexture.TextureID] = 1; // XXX: Not a great way to iterate through face textures, but there's no // other method available to tell how many faces there actually are //int i = 0; foreach (Primitive.TextureEntryFace texture in textureEntry.FaceTextures) { if (texture != null) { //m_log.DebugFormat("[ARCHIVER]: Got face {0}", i++); assetUuids[texture.TextureID] = 1; } } // If the prim is a sculpt then preserve this information too if (part.Shape.SculptTexture != UUID.Zero) assetUuids[part.Shape.SculptTexture] = 1; // scan through the rendermaterials of this part for any textures used as materials if (part.Shape.RenderMaterials != null) { lock (part.Shape.RenderMaterials) { List<RenderMaterial> mats = part.Shape.RenderMaterials.GetMaterials(); foreach(var entry in mats) { if (entry.NormalID != UUID.Zero) assetUuids[entry.NormalID] = 1; if (entry.SpecularID != UUID.Zero) assetUuids[entry.SpecularID] = 1; } } } TaskInventoryDictionary taskDictionary = (TaskInventoryDictionary)part.TaskInventory.Clone(); // Now analyze this prim's inventory items to preserve all the uuids that they reference foreach (TaskInventoryItem tii in taskDictionary.Values) { //m_log.DebugFormat("[ARCHIVER]: Analysing item asset type {0}", tii.Type); if ((tii.AssetID != UUID.Zero) && (!assetUuids.ContainsKey(tii.AssetID))) GatherAssetUuids(tii.AssetID, (AssetType)tii.Type, assetUuids); } } catch (Exception e) { m_log.ErrorFormat("[ASSET GATHERER]: Failed to get part - {0}", e); } } } /// <summary> /// The callback made when we request the asset for an object from the asset service. /// </summary> protected void AssetRequestCallback(UUID assetID, AssetBase asset) { lock (this) { m_requestedObjectAsset = asset; m_waitingForObjectAsset = false; Monitor.Pulse(this); } } /// <summary> /// Get an asset synchronously, potentially using an asynchronous callback. If the /// asynchronous callback is used, we will wait for it to complete. /// </summary> /// <param name="uuid"></param> /// <returns></returns> protected AssetBase GetAsset(UUID uuid) { m_waitingForObjectAsset = true; m_assetCache.GetAsset(uuid, AssetRequestCallback, AssetRequestInfo.InternalRequest()); // The asset cache callback can either // // 1. Complete on the same thread (if the asset is already in the cache) or // 2. Come in via a different thread (if we need to go fetch it). // // The code below handles both these alternatives. lock (this) { if (m_waitingForObjectAsset) { Monitor.Wait(this); m_waitingForObjectAsset = false; } } return m_requestedObjectAsset; } /// <summary> /// Record the asset uuids embedded within the given script. /// </summary> /// <param name="scriptUuid"></param> /// <param name="assetUuids">Dictionary in which to record the references</param> protected void GetScriptAssetUuids(UUID scriptUuid, IDictionary<UUID, int> assetUuids) { AssetBase scriptAsset = GetAsset(scriptUuid); if (null != scriptAsset) { string script = Utils.BytesToString(scriptAsset.Data); //m_log.DebugFormat("[ARCHIVER]: Script {0}", script); MatchCollection uuidMatches = Util.UUIDPattern.Matches(script); //m_log.DebugFormat("[ARCHIVER]: Found {0} matches in script", uuidMatches.Count); foreach (Match uuidMatch in uuidMatches) { UUID uuid = new UUID(uuidMatch.Value); //m_log.DebugFormat("[ARCHIVER]: Recording {0} in script", uuid); assetUuids[uuid] = 1; } } } /// <summary> /// Record the uuids referenced by the given wearable asset /// </summary> /// <param name="wearableAssetUuid"></param> /// <param name="assetUuids">Dictionary in which to record the references</param> protected void GetWearableAssetUuids(UUID wearableAssetUuid, IDictionary<UUID, int> assetUuids) { AssetBase assetBase = GetAsset(wearableAssetUuid); //m_log.Debug(new System.Text.ASCIIEncoding().GetString(bodypartAsset.Data)); OpenMetaverse.Assets.AssetWearable wearableAsset = new OpenMetaverse.Assets.AssetBodypart(wearableAssetUuid, assetBase.Data); wearableAsset.Decode(); //m_log.DebugFormat( // "[ARCHIVER]: Wearable asset {0} references {1} assets", wearableAssetUuid, wearableAsset.Textures.Count); foreach (UUID uuid in wearableAsset.Textures.Values) { //m_log.DebugFormat("[ARCHIVER]: Got bodypart uuid {0}", uuid); assetUuids[uuid] = 1; } } /// <summary> /// Get all the asset uuids associated with a given object. This includes both those directly associated with /// it (e.g. face textures) and recursively, those of items within it's inventory (e.g. objects contained /// within this object). /// </summary> /// <param name="sceneObject"></param> /// <param name="assetUuids"></param> protected void GetSceneObjectAssetUuids(UUID sceneObjectUuid, IDictionary<UUID, int> assetUuids) { AssetBase objectAsset = GetAsset(sceneObjectUuid); if (null != objectAsset) { SceneObjectGroup sog; if (m_inventorySerializer.IsValidCoalesced(objectAsset.Data)) { m_log.WarnFormat("[ARCHIVER]: UUID gatherer encountered a coalesced object, asset ID {0} - skipped.", objectAsset.FullID); return; } if (m_inventorySerializer.IsValidGroup(objectAsset.Data)) { sog = m_inventorySerializer.DeserializeGroupFromInventoryBytes(objectAsset.Data); } else { string xml = Utils.BytesToString(objectAsset.Data); sog = SceneObjectSerializer.FromOriginalXmlFormat(xml); if (sog == null) { // in some case it may have been saved as XML2 sog = SceneObjectSerializer.FromXml2Format(xml); if (sog != null) m_log.InfoFormat("[ARCHIVER]: Was able to recover asset {0} as XML2 format.", objectAsset.FullID); } } if (sog != null) GatherAssetUuids(sog, assetUuids); } } } }
using ClosedXML.Excel; using System; using System.Collections.Generic; namespace ClosedXML.Examples { public class PivotTables : IXLExample { private class Pastry { public Pastry(string name, int? code, int numberOfOrders, double quality, string month, DateTime? bakeDate) { Name = name; Code = code; NumberOfOrders = numberOfOrders; Quality = quality; Month = month; BakeDate = bakeDate; } public string Name { get; set; } public int? Code { get; } public int NumberOfOrders { get; set; } public double Quality { get; set; } public string Month { get; set; } public DateTime? BakeDate { get; set; } } public void Create(String filePath) { var pastries = new List<Pastry> { new Pastry("Croissant", 101, 150, 60.2, "Apr", new DateTime(2016, 04, 21)), new Pastry("Croissant", 101, 250, 50.42, "May", new DateTime(2016, 05, 03)), new Pastry("Croissant", 101, 134, 22.12, "Jun", new DateTime(2016, 06, 24)), new Pastry("Doughnut", 102, 250, 89.99, "Apr", new DateTime(2017, 04, 23)), new Pastry("Doughnut", 102, 225, 70, "May", new DateTime(2016, 05, 24)), new Pastry("Doughnut", 102, 210, 75.33, "Jun", new DateTime(2016, 06, 02)), new Pastry("Bearclaw", 103, 134, 10.24, "Apr", new DateTime(2016, 04, 27)), new Pastry("Bearclaw", 103, 184, 33.33, "May", new DateTime(2016, 05, 20)), new Pastry("Bearclaw", 103, 124, 25, "Jun", new DateTime(2017, 06, 05)), new Pastry("Danish", 104, 394, -20.24, "Apr", new DateTime(2017, 04, 24)), new Pastry("Danish", 104, 190, 60, "May", new DateTime(2017, 05, 08)), new Pastry("Danish", 104, 221, 24.76, "Jun", new DateTime(2016, 06, 21)), // Deliberately add different casings of same string to ensure pivot table doesn't duplicate it. new Pastry("Scone", 105, 135, 0, "Apr", new DateTime(2017, 04, 22)), new Pastry("SconE", 105, 122, 5.19, "May", new DateTime(2017, 05, 03)), new Pastry("SCONE", 105, 243, 44.2, "Jun", new DateTime(2017, 06, 14)), // For ContainsBlank and integer rows/columns test new Pastry("Scone", null, 255, 18.4, null, null), }; using (var wb = new XLWorkbook()) { var ws = wb.Worksheets.Add("PastrySalesData"); // Insert our list of pastry data into the "PastrySalesData" sheet at cell 1,1 var table = ws.Cell(1, 1).InsertTable(pastries, "PastrySalesData", true); ws.Columns().AdjustToContents(); IXLWorksheet ptSheet; IXLPivotTable pt; #region Pivots for (int i = 1; i <= 3; i++) { // Add a new sheet for our pivot table ptSheet = wb.Worksheets.Add("pvt" + i); // Create the pivot table, using the data from the "PastrySalesData" table pt = ptSheet.PivotTables.Add("pvt", ptSheet.Cell(1, 1), table.AsRange()); // The rows in our pivot table will be the names of the pastries if (i == 2) pt.RowLabels.Add(XLConstants.PivotTable.ValuesSentinalLabel); pt.RowLabels.Add("Name"); // The columns will be the months pt.ColumnLabels.Add("Month"); if (i == 3) pt.ColumnLabels.Add(XLConstants.PivotTable.ValuesSentinalLabel); // The values in our table will come from the "NumberOfOrders" field // The default calculation setting is a total of each row/column pt.Values.Add("NumberOfOrders", "NumberOfOrdersPercentageOfBearclaw") .ShowAsPercentageFrom("Name").And("Bearclaw") .NumberFormat.Format = "0%"; if (i > 1) { pt.Values.Add("Quality", "Sum of Quality") .NumberFormat.SetFormat("#,##0.00"); } if (i > 2) { pt.Values.Add("NumberOfOrders", "Sum of NumberOfOrders"); } ptSheet.Columns().AdjustToContents(); } #endregion Pivots #region Different kind of pivot ptSheet = wb.Worksheets.Add("pvtNoColumnLabels"); pt = ptSheet.PivotTables.Add("pvtNoColumnLabels", ptSheet.Cell(1, 1), table.AsRange()); pt.RowLabels.Add("Name"); pt.RowLabels.Add("Month"); pt.Values.Add("NumberOfOrders").SetSummaryFormula(XLPivotSummary.Sum); pt.Values.Add("Quality").SetSummaryFormula(XLPivotSummary.Sum); pt.SetRowHeaderCaption("Pastry name"); #endregion Different kind of pivot #region Pivot table with collapsed fields ptSheet = wb.Worksheets.Add("pvtCollapsedFields"); pt = ptSheet.PivotTables.Add("pvtCollapsedFields", ptSheet.Cell(1, 1), table.AsRange()); pt.RowLabels.Add("Name").SetCollapsed(); pt.RowLabels.Add("Month").SetCollapsed(); pt.Values.Add("NumberOfOrders").SetSummaryFormula(XLPivotSummary.Sum); pt.Values.Add("Quality").SetSummaryFormula(XLPivotSummary.Sum); #endregion Pivot table with collapsed fields #region Pivot table with a field both as a value and as a row/column/filter label ptSheet = wb.Worksheets.Add("pvtFieldAsValueAndLabel"); pt = ptSheet.PivotTables.Add("pvtFieldAsValueAndLabel", ptSheet.Cell(1, 1), table.AsRange()); pt.RowLabels.Add("Name"); pt.RowLabels.Add("Month"); pt.Values.Add("Name").SetSummaryFormula(XLPivotSummary.Count);//.NumberFormat.Format = "#0.00"; #endregion Pivot table with a field both as a value and as a row/column/filter label #region Pivot table with subtotals disabled ptSheet = wb.Worksheets.Add("pvtHideSubTotals"); // Create the pivot table, using the data from the "PastrySalesData" table pt = ptSheet.PivotTables.Add("pvtHidesubTotals", ptSheet.Cell(1, 1), table.AsRange()); // The rows in our pivot table will be the names of the pastries pt.RowLabels.Add(XLConstants.PivotTable.ValuesSentinalLabel); // The columns will be the months pt.ColumnLabels.Add("Month"); pt.ColumnLabels.Add("Name"); // The values in our table will come from the "NumberOfOrders" field // The default calculation setting is a total of each row/column pt.Values.Add("NumberOfOrders", "NumberOfOrdersPercentageOfBearclaw") .ShowAsPercentageFrom("Name").And("Bearclaw") .NumberFormat.Format = "0%"; pt.Values.Add("Quality", "Sum of Quality") .NumberFormat.SetFormat("#,##0.00"); pt.Subtotals = XLPivotSubtotals.DoNotShow; pt.SetColumnHeaderCaption("Measures"); ptSheet.Columns().AdjustToContents(); #endregion Pivot table with subtotals disabled #region Pivot Table with filter ptSheet = wb.Worksheets.Add("pvtFilter"); pt = table.CreatePivotTable(ptSheet.FirstCell(), "pvtFilter"); pt.RowLabels.Add("Month"); pt.Values.Add("NumberOfOrders").SetSummaryFormula(XLPivotSummary.Sum); pt.ReportFilters.Add("Name") .AddSelectedValue("Scone") .AddSelectedValue("Doughnut"); pt.ReportFilters.Add("Quality") .AddSelectedValue(5.19); pt.ReportFilters.Add("BakeDate") .AddSelectedValue(new DateTime(2017, 05, 03)); #endregion Pivot Table with filter #region Pivot table sorting ptSheet = wb.Worksheets.Add("pvtSort"); pt = ptSheet.PivotTables.Add("pvtSort", ptSheet.Cell(1, 1), table.AsRange()); pt.RowLabels.Add("Name").SetSort(XLPivotSortType.Ascending); pt.RowLabels.Add("Month").SetSort(XLPivotSortType.Descending); pt.Values.Add("NumberOfOrders").SetSummaryFormula(XLPivotSummary.Sum); pt.Values.Add("Quality").SetSummaryFormula(XLPivotSummary.Sum); pt.SetRowHeaderCaption("Pastry name"); #endregion Different kind of pivot #region Pivot Table with integer rows ptSheet = wb.Worksheets.Add("pvtInteger"); pt = ptSheet.PivotTables.Add("pvtInteger", ptSheet.Cell(1, 1), table); pt.RowLabels.Add("Name"); pt.RowLabels.Add("Code"); pt.RowLabels.Add("BakeDate"); pt.ColumnLabels.Add("Month"); pt.Values.Add("NumberOfOrders").SetSummaryFormula(XLPivotSummary.Sum); pt.Values.Add("Quality").SetSummaryFormula(XLPivotSummary.Sum); #endregion Pivot Table with filter wb.SaveAs(filePath); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Concurrent; using System.Collections.Generic; using System.Collections.ObjectModel; using Xunit; namespace System.Linq.Parallel.Tests { [OuterLoop] public partial class ParallelQueryCombinationTests { private const int DefaultStart = 8; private const int DefaultSize = 16; private const int CountFactor = 8; private const int GroupFactor = 8; private static IEnumerable<LabeledOperation> UnorderedRangeSources() { // The difference between this and the existing sources is more control is needed over the range creation. // Specifically, start/count won't be known until the nesting level is resolved at runtime. yield return Label("ParallelEnumerable.Range", (start, count, ignore) => ParallelEnumerable.Range(start, count)); yield return Label("Enumerable.Range", (start, count, ignore) => Enumerable.Range(start, count).AsParallel()); yield return Label("Array", (start, count, ignore) => UnorderedSources.GetRangeArray(start, count).AsParallel()); yield return Label("Partitioner", (start, count, ignore) => Partitioner.Create(UnorderedSources.GetRangeArray(start, count)).AsParallel()); yield return Label("List", (start, count, ignore) => UnorderedSources.GetRangeArray(start, count).ToList().AsParallel()); yield return Label("ReadOnlyCollection", (start, count, ignore) => new ReadOnlyCollection<int>(UnorderedSources.GetRangeArray(start, count).ToList()).AsParallel()); } private static IEnumerable<LabeledOperation> RangeSources() { foreach (LabeledOperation source in UnorderedRangeSources()) { foreach (LabeledOperation ordering in new[] { AsOrdered }.Concat(OrderOperators())) { yield return source.Append(ordering); } } } private static IEnumerable<LabeledOperation> OrderOperators() { yield return Label("OrderBy", (start, count, source) => source(start, count).OrderBy(x => -x, ReverseComparer.Instance)); yield return Label("OrderByDescending", (start, count, source) => source(start, count).OrderByDescending(x => x, ReverseComparer.Instance)); yield return Label("ThenBy", (start, count, source) => source(start, count).OrderBy(x => 0).ThenBy(x => -x, ReverseComparer.Instance)); yield return Label("ThenByDescending", (start, count, source) => source(start, count).OrderBy(x => 0).ThenByDescending(x => x, ReverseComparer.Instance)); } public static IEnumerable<object[]> OrderFailingOperators() { LabeledOperation source = UnorderedRangeSources().First(); foreach (LabeledOperation operation in new[] { Label("OrderBy", (start, count, s) => s(start, count).OrderBy<int, int>(x => {throw new DeliberateTestException(); })), Label("OrderBy-Comparer", (start, count, s) => s(start, count).OrderBy(x => x, new FailingComparer())), Label("OrderByDescending", (start, count, s) => s(start, count).OrderByDescending<int, int>(x => {throw new DeliberateTestException(); })), Label("OrderByDescending-Comparer", (start, count, s) => s(start, count).OrderByDescending(x => x, new FailingComparer())), Label("ThenBy", (start, count, s) => s(start, count).OrderBy(x => 0).ThenBy<int, int>(x => {throw new DeliberateTestException(); })), Label("ThenBy-Comparer", (start, count, s) => s(start, count).OrderBy(x => 0).ThenBy(x => x, new FailingComparer())), Label("ThenByDescending", (start, count, s) => s(start, count).OrderBy(x => 0).ThenByDescending<int, int>(x => {throw new DeliberateTestException(); })), Label("ThenByDescending-Comparer", (start, count, s) => s(start, count).OrderBy(x => 0).ThenByDescending(x => x, new FailingComparer())), }) { yield return new object[] { source, operation }; } foreach (LabeledOperation operation in OrderOperators()) { yield return new object[] { Failing, operation }; } } public static IEnumerable<object[]> OrderCancelingOperators() { foreach (var operation in new Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("OrderBy-Comparer", (source, cancel) => source.OrderBy(x => x, new CancelingComparer(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("OrderByDescending-Comparer", (source, cancel) => source.OrderByDescending(x => x, new CancelingComparer(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("ThenBy-Comparer", (source, cancel) => source.OrderBy(x => 0).ThenBy(x => x, new CancelingComparer(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("ThenByDescending-Comparer", (source, cancel) => source.OrderBy(x => 0).ThenByDescending(x => x, new CancelingComparer(cancel))), }) { yield return new object[] { operation }; } } private static IEnumerable<LabeledOperation> UnaryOperations() { yield return Label("Cast", (start, count, source) => source(start, count).Cast<int>()); yield return Label("DefaultIfEmpty", (start, count, source) => source(start, count).DefaultIfEmpty()); yield return Label("Distinct", (start, count, source) => source(start * 2, count * 2).Select(x => x / 2).Distinct(new ModularCongruenceComparer(count))); yield return Label("OfType", (start, count, source) => source(start, count).OfType<int>()); yield return Label("Reverse", (start, count, source) => source(start, count).Select(x => (start + count - 1) - (x - start)).Reverse()); yield return Label("GroupBy", (start, count, source) => source(start, count * CountFactor).GroupBy(x => (x - start) % count, new ModularCongruenceComparer(count)).Select(g => g.Key + start)); yield return Label("GroupBy-ElementSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => x % count, y => y + 1, new ModularCongruenceComparer(count)).Select(g => g.Min() - 1)); yield return Label("GroupBy-ResultSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => (x - start) % count, (key, g) => key + start, new ModularCongruenceComparer(count))); yield return Label("GroupBy-ElementSelector-ResultSelector", (start, count, source) => source(start, count * CountFactor).GroupBy(x => x % count, y => y + 1, (key, g) => g.Min() - 1, new ModularCongruenceComparer(count))); yield return Label("Select", (start, count, source) => source(start - count, count).Select(x => x + count)); yield return Label("Select-Index", (start, count, source) => source(start - count, count).Select((x, index) => x + count)); yield return Label("SelectMany", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany(x => Enumerable.Range(start + x * CountFactor, Math.Min(CountFactor, count - x * CountFactor)))); yield return Label("SelectMany-Index", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany((x, index) => Enumerable.Range(start + x * CountFactor, Math.Min(CountFactor, count - x * CountFactor)))); yield return Label("SelectMany-ResultSelector", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany(x => Enumerable.Range(0, Math.Min(CountFactor, count - x * CountFactor)), (group, element) => start + group * CountFactor + element)); yield return Label("SelectMany-Index-ResultSelector", (start, count, source) => source(0, (count - 1) / CountFactor + 1).SelectMany((x, index) => Enumerable.Range(0, Math.Min(CountFactor, count - x * CountFactor)), (group, element) => start + group * CountFactor + element)); yield return Label("Where", (start, count, source) => source(start - count / 2, count * 2).Where(x => x >= start && x < start + count)); yield return Label("Where-Index", (start, count, source) => source(start - count / 2, count * 2).Where((x, index) => x >= start && x < start + count)); } public static IEnumerable<object[]> UnaryUnorderedOperators() { foreach (LabeledOperation source in UnorderedRangeSources()) { foreach (LabeledOperation operation in UnaryOperations()) { yield return new object[] { source, operation }; } } } private static IEnumerable<LabeledOperation> SkipTakeOperations() { // Take/Skip-based operations require ordered input, or will disobey // the [start, start + count) convention expected in tests. yield return Label("Skip", (start, count, source) => source(start - count, count * 2).Skip(count)); yield return Label("SkipWhile", (start, count, source) => source(start - count, count * 2).SkipWhile(x => x < start)); yield return Label("SkipWhile-Index", (start, count, source) => source(start - count, count * 2).SkipWhile((x, index) => x < start)); yield return Label("Take", (start, count, source) => source(start, count * 2).Take(count)); yield return Label("TakeWhile", (start, count, source) => source(start, count * 2).TakeWhile(x => x < start + count)); yield return Label("TakeWhile-Index", (start, count, source) => source(start, count * 2).TakeWhile((x, index) => x < start + count)); } public static IEnumerable<object[]> SkipTakeOperators() { foreach (LabeledOperation source in RangeSources()) { foreach (LabeledOperation operation in SkipTakeOperations()) { yield return new object[] { source, operation }; } } } public static IEnumerable<object[]> UnaryOperators() { // Apply an ordered source to each operation foreach (LabeledOperation source in RangeSources()) { foreach (LabeledOperation operation in UnaryOperations()) { yield return new object[] { source, operation }; } } // Apply ordering to the output of each operation foreach (LabeledOperation source in UnorderedRangeSources()) { foreach (LabeledOperation operation in UnaryOperations()) { foreach (LabeledOperation ordering in OrderOperators()) { yield return new object[] { source, operation.Append(ordering) }; } } } foreach (object[] parms in SkipTakeOperators()) { yield return parms; } } public static IEnumerable<object[]> UnaryFailingOperators() { foreach (LabeledOperation operation in new[] { Label("Distinct", (start, count, s) => s(start, count).Distinct(new FailingEqualityComparer<int>())), Label("GroupBy", (start, count, s) => s(start, count).GroupBy<int, int>(x => {throw new DeliberateTestException(); }).Select(g => g.Key)), Label("GroupBy-Comparer", (start, count, s) => s(start, count).GroupBy(x => x, new FailingEqualityComparer<int>()).Select(g => g.Key)), Label("GroupBy-ElementSelector", (start, count, s) => s(start, count).GroupBy<int, int, int>(x => x, x => { throw new DeliberateTestException(); }).Select(g => g.Key)), Label("GroupBy-ResultSelector", (start, count, s) => s(start, count).GroupBy<int, int, int, int>(x => x, x => x, (x, g) => { throw new DeliberateTestException(); })), Label("Select", (start, count, s) => s(start, count).Select<int, int>(x => {throw new DeliberateTestException(); })), Label("Select-Index", (start, count, s) => s(start, count).Select<int, int>((x, index) => {throw new DeliberateTestException(); })), Label("SelectMany", (start, count, s) => s(start, count).SelectMany<int, int>(x => {throw new DeliberateTestException(); })), Label("SelectMany-Index", (start, count, s) => s(start, count).SelectMany<int, int>((x, index) => {throw new DeliberateTestException(); })), Label("SelectMany-ResultSelector", (start, count, s) => s(start, count).SelectMany<int, int, int>(x => Enumerable.Range(x, 2), (group, elem) => { throw new DeliberateTestException(); })), Label("SelectMany-Index-ResultSelector", (start, count, s) => s(start, count).SelectMany<int, int, int>((x, index) => Enumerable.Range(x, 2), (group, elem) => { throw new DeliberateTestException(); })), Label("SkipWhile", (start, count, s) => s(start, count).SkipWhile(x => {throw new DeliberateTestException(); })), Label("SkipWhile-Index", (start, count, s) => s(start, count).SkipWhile((x, index) => {throw new DeliberateTestException(); })), Label("TakeWhile", (start, count, s) => s(start, count).TakeWhile(x => {throw new DeliberateTestException(); })), Label("TakeWhile-Index", (start, count, s) => s(start, count).SkipWhile((x, index) => {throw new DeliberateTestException(); })), Label("Where", (start, count, s) => s(start, count).Where(x => {throw new DeliberateTestException(); })), Label("Where-Index", (start, count, s) => s(start, count).Where((x, index) => {throw new DeliberateTestException(); })), }) { foreach (LabeledOperation source in UnorderedRangeSources()) { yield return new object[] { source, operation }; } } foreach (LabeledOperation operation in UnaryOperations().Concat(SkipTakeOperations())) { yield return new object[] { Failing, operation }; } } public static IEnumerable<object[]> UnaryCancelingOperators() { foreach (var operation in new Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Distinct", (source,cancel) => source.Distinct(new CancelingEqualityComparer<int>(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("GroupBy-Comparer", (source,cancel) => source.GroupBy(x => x, new CancelingEqualityComparer<int>(cancel)).Select(g => g.Key)), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany", (source,cancel) => source.SelectMany(x => { cancel(); return new[] { x }; })), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany-Index", (source,cancel) => source.SelectMany((x, index) => { cancel(); return new[] { x }; })), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany-ResultSelector", (source,cancel) => source.SelectMany(x => new [] { x }, (group, elem) => { cancel(); return elem; })), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SelectMany-Index-ResultSelector", (source,cancel) => source.SelectMany((x, index) => new [] { x }, (group, elem) => { cancel(); return elem; })), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SkipWhile", (source,cancel) => source.SkipWhile(x => { cancel(); return true; })), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("SkipWhile-Index", (source,cancel) => source.SkipWhile((x, index) => { cancel(); return true; })), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("TakeWhile", (source,cancel) => source.TakeWhile(x => { cancel(); return true; })), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("TakeWhile-Index", (source,cancel) => source.TakeWhile((x, index) => { cancel(); return true; })), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Where", (source,cancel) => source.Where(x => { cancel(); return true; })), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Where-Index", (source,cancel) => source.Where((x, index) => { cancel(); return true; })), }) { yield return new object[] { operation }; } } private static IEnumerable<LabeledOperation> BinaryOperations(LabeledOperation otherSource) { String label = otherSource.ToString(); Operation other = otherSource.Item; yield return Label("Concat-Right:" + label, (start, count, source) => source(start, count / 2).Concat(other(start + count / 2, count / 2 + count % 2))); yield return Label("Concat-Left:" + label, (start, count, source) => other(start, count / 2).Concat(source(start + count / 2, count / 2 + count % 2))); // Comparator needs to cover _source_ size, as which of two "equal" items is returned is undefined for unordered collections. yield return Label("Except-Right:" + label, (start, count, source) => source(start, count + count / 2).Except(other(start + count, count), new ModularCongruenceComparer(count * 2))); yield return Label("Except-Left:" + label, (start, count, source) => other(start, count + count / 2).Except(source(start + count, count), new ModularCongruenceComparer(count * 2))); yield return Label("GroupJoin-Right:" + label, (start, count, source) => source(start, count).GroupJoin(other(start, count * CountFactor), x => x, y => y % count, (x, g) => g.Min(), new ModularCongruenceComparer(count))); yield return Label("GroupJoin-Left:" + label, (start, count, source) => other(start, count).GroupJoin(source(start, count * CountFactor), x => x, y => y % count, (x, g) => g.Min(), new ModularCongruenceComparer(count))); // Comparator needs to cover _source_ size, as which of two "equal" items is returned is undefined. yield return Label("Intersect-Right:" + label, (start, count, source) => source(start, count + count / 2).Intersect(other(start - count / 2, count + count / 2), new ModularCongruenceComparer(count * 2))); yield return Label("Intersect-Left:" + label, (start, count, source) => other(start, count + count / 2).Intersect(source(start - count / 2, count + count / 2), new ModularCongruenceComparer(count * 2))); yield return Label("Join-Right:" + label, (start, count, source) => source(0, count).Join(other(start, count), x => x, y => y - start, (x, y) => x + start, new ModularCongruenceComparer(count))); yield return Label("Join-Left:" + label, (start, count, source) => other(0, count).Join(source(start, count), x => x, y => y - start, (x, y) => x + start, new ModularCongruenceComparer(count))); yield return Label("Union-Right:" + label, (start, count, source) => source(start, count * 3 / 4).Union(other(start + count / 2, count / 2 + count % 2), new ModularCongruenceComparer(count))); yield return Label("Union-Left:" + label, (start, count, source) => other(start, count * 3 / 4).Union(source(start + count / 2, count / 2 + count % 2), new ModularCongruenceComparer(count))); // When both sources are unordered any element can be matched to any other, so a different check is required. yield return Label("Zip-Unordered-Right:" + label, (start, count, source) => source(0, count).Zip(other(start * 2, count), (x, y) => x + start)); yield return Label("Zip-Unordered-Left:" + label, (start, count, source) => other(start * 2, count).Zip(source(0, count), (x, y) => y + start)); } public static IEnumerable<object[]> BinaryUnorderedOperators() { LabeledOperation otherSource = UnorderedRangeSources().First(); foreach (LabeledOperation source in UnorderedRangeSources()) { // Operations having multiple paths to check. foreach (LabeledOperation operation in BinaryOperations(otherSource)) { yield return new object[] { source, operation }; } } } public static IEnumerable<object[]> BinaryOperators() { LabeledOperation unordered = UnorderedRangeSources().First(); foreach (LabeledOperation source in RangeSources()) { // Each binary can work differently, depending on which of the two source queries (or both) is ordered. // For most, only the ordering of the first query is important foreach (LabeledOperation operation in BinaryOperations(unordered).Where(op => !(op.ToString().StartsWith("Union") || op.ToString().StartsWith("Zip")) && op.ToString().Contains("Right"))) { yield return new object[] { source, operation }; } // Concat currently doesn't play nice if only the right query is ordered via OrderBy et al. Issue #1332 // For Concat, since either one can be ordered the other side has to be tested //foreach (var operation in BinaryOperations().Where(op => op.ToString().Contains("Concat") && op.ToString().Contains("Left"))) //{ // yield return new object[] { source, operation }; //} // Zip is the same as Concat, but has a special check for matching indices (as compared to unordered) foreach (LabeledOperation operation in Zip_Ordered_Operation(unordered)) { yield return new object[] { source, operation }; } // Union is an odd duck that (currently) orders only the portion that came from an ordered source. foreach (LabeledOperation operation in BinaryOperations(RangeSources().First()).Where(op => op.ToString().StartsWith("Union"))) { yield return new object[] { source, operation }; } } // Ordering the output should always be safe foreach (object[] parameters in BinaryUnorderedOperators()) { foreach (LabeledOperation ordering in OrderOperators()) { yield return new[] { parameters[0], ((LabeledOperation)parameters[1]).Append(ordering) }; } } } public static IEnumerable<object[]> BinaryFailingOperators() { LabeledOperation failing = Label("Failing", (start, count, s) => s(start, count).Select<int, int>(x => { throw new DeliberateTestException(); })); LabeledOperation source = UnorderedRangeSources().First(); foreach (LabeledOperation operation in BinaryOperations(UnorderedRangeSources().First())) { foreach (LabeledOperation other in UnorderedRangeSources()) { yield return new object[] { other.Append(failing), operation }; } yield return new object[] { Failing, operation }; } foreach (LabeledOperation operation in new[] { Label("Except-Fail", (start, count, s) => s(start, count).Except(source.Item(start, count), new FailingEqualityComparer<int>())), Label("GroupJoin-Fail", (start, count, s) => s(start, count).GroupJoin(source.Item(start, count), x => x, y => y, (x, g) => x, new FailingEqualityComparer<int>())), Label("Intersect-Fail", (start, count, s) => s(start, count).Intersect(source.Item(start, count), new FailingEqualityComparer<int>())), Label("Join-Fail", (start, count, s) => s(start, count).Join(source.Item(start, count), x => x, y => y, (x, y) => x, new FailingEqualityComparer<int>())), Label("Union-Fail", (start, count, s) => s(start, count).Union(source.Item(start, count), new FailingEqualityComparer<int>())), Label("Zip-Fail", (start, count, s) => s(start, count).Zip<int, int, int>(source.Item(start, count), (x, y) => { throw new DeliberateTestException(); })), }) { yield return new object[] { source, operation }; } } public static IEnumerable<object[]> BinaryCancelingOperators() { foreach (var operation in new Labeled<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>[] { Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Except", (source, cancel) => source.Except(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer<int>(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Except-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Except(source, new CancelingEqualityComparer<int>(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("GroupJoin", (source, cancel) => source.GroupJoin(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), x => x, y => y, (x, g) => x, new CancelingEqualityComparer<int>(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("GroupJoin-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).GroupJoin(source, x => x, y => y, (x, g) => x, new CancelingEqualityComparer<int>(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Intersect", (source, cancel) => source.Intersect(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer<int>(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Intersect-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Intersect(source, new CancelingEqualityComparer<int>(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Join", (source, cancel) => source.Join(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), x => x, y => y, (x, y) => x, new CancelingEqualityComparer<int>(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Join-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Join(source, x => x, y => y, (x, y) => x, new CancelingEqualityComparer<int>(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Union", (source, cancel) => source.Union(ParallelEnumerable.Range(DefaultStart, EventualCancellationSize), new CancelingEqualityComparer<int>(cancel))), Labeled.Label<Func<ParallelQuery<int>, Action, ParallelQuery<int>>>("Union-Right", (source, cancel) => ParallelEnumerable.Range(DefaultStart, EventualCancellationSize).Union(source, new CancelingEqualityComparer<int>(cancel))), }) { yield return new object[] { operation }; } } #region operators private static LabeledOperation Failing = Label("ThrowOnFirstEnumeration", (start, count, source) => Enumerables<int>.ThrowOnEnumeration().AsParallel()); private static LabeledOperation AsOrdered = Label("AsOrdered", (start, count, source) => source(start, count).AsOrdered()); // There are two implementations here to help check that the 1st element is matched to the 1st element. private static Func<LabeledOperation, IEnumerable<LabeledOperation>> Zip_Ordered_Operation = sOther => new[] { Label("Zip-Ordered-Right:" + sOther.ToString(), (start, count, source) => source(0, count).Zip(sOther.Item(start * 2, count), (x, y) => (x + y) / 2)), Label("Zip-Ordered-Left:" + sOther.ToString(), (start, count, source) => sOther.Item(start * 2, count).Zip(source(0, count), (x, y) => (x + y) / 2)) }; #endregion operators } }
// // ImageReader.cs // // Author: // Jb Evain (jbevain@gmail.com) // // Copyright (c) 2008 - 2010 Jb Evain // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System; using System.IO; using Mono.Cecil.Metadata; using RVA = System.UInt32; namespace Mono.Cecil.PE { sealed class ImageReader : BinaryStreamReader { readonly Image image; DataDirectory cli; DataDirectory metadata; public ImageReader (Stream stream) : base (stream) { image = new Image (); image.FileName = stream.GetFullyQualifiedName (); } void MoveTo (DataDirectory directory) { BaseStream.Position = image.ResolveVirtualAddress (directory.VirtualAddress); } void MoveTo (uint position) { BaseStream.Position = position; } void ReadImage () { if (BaseStream.Length < 128) throw new BadImageFormatException (); // - DOSHeader // PE 2 // Start 58 // Lfanew 4 // End 64 if (ReadUInt16 () != 0x5a4d) throw new BadImageFormatException (); Advance (58); MoveTo (ReadUInt32 ()); if (ReadUInt32 () != 0x00004550) throw new BadImageFormatException (); // - PEFileHeader // Machine 2 image.Architecture = ReadArchitecture (); // NumberOfSections 2 ushort sections = ReadUInt16 (); // TimeDateStamp 4 // PointerToSymbolTable 4 // NumberOfSymbols 4 // OptionalHeaderSize 2 Advance (14); // Characteristics 2 ushort characteristics = ReadUInt16 (); ushort subsystem; ReadOptionalHeaders (out subsystem); ReadSections (sections); ReadCLIHeader (); ReadMetadata (); image.Kind = GetModuleKind (characteristics, subsystem); } TargetArchitecture ReadArchitecture () { var machine = ReadUInt16 (); switch (machine) { case 0x014c: return TargetArchitecture.I386; case 0x8664: return TargetArchitecture.AMD64; case 0x0200: return TargetArchitecture.IA64; } throw new NotSupportedException (); } static ModuleKind GetModuleKind (ushort characteristics, ushort subsystem) { if ((characteristics & 0x2000) != 0) // ImageCharacteristics.Dll return ModuleKind.Dll; if (subsystem == 0x2 || subsystem == 0x9) // SubSystem.WindowsGui || SubSystem.WindowsCeGui return ModuleKind.Windows; return ModuleKind.Console; } void ReadOptionalHeaders (out ushort subsystem) { // - PEOptionalHeader // - StandardFieldsHeader // Magic 2 bool pe64 = ReadUInt16 () == 0x20b; // pe32 || pe64 // LMajor 1 // LMinor 1 // CodeSize 4 // InitializedDataSize 4 // UninitializedDataSize4 // EntryPointRVA 4 // BaseOfCode 4 // BaseOfData 4 || 0 // - NTSpecificFieldsHeader // ImageBase 4 || 8 // SectionAlignment 4 // FileAlignement 4 // OSMajor 2 // OSMinor 2 // UserMajor 2 // UserMinor 2 // SubSysMajor 2 // SubSysMinor 2 // Reserved 4 // ImageSize 4 // HeaderSize 4 // FileChecksum 4 Advance (66); // SubSystem 2 subsystem = ReadUInt16 (); // DLLFlags 2 // StackReserveSize 4 || 8 // StackCommitSize 4 || 8 // HeapReserveSize 4 || 8 // HeapCommitSize 4 || 8 // LoaderFlags 4 // NumberOfDataDir 4 // - DataDirectoriesHeader // ExportTable 8 // ImportTable 8 // ResourceTable 8 // ExceptionTable 8 // CertificateTable 8 // BaseRelocationTable 8 Advance (pe64 ? 90 : 74); // Debug 8 image.Debug = ReadDataDirectory (); // Copyright 8 // GlobalPtr 8 // TLSTable 8 // LoadConfigTable 8 // BoundImport 8 // IAT 8 // DelayImportDescriptor8 Advance (56); // CLIHeader 8 cli = ReadDataDirectory (); if (cli.IsZero) throw new BadImageFormatException (); // Reserved 8 Advance (8); } string ReadAlignedString (int length) { int read = 0; var buffer = new char [length]; while (read < length) { var current = ReadByte (); if (current == 0) break; buffer [read++] = (char) current; } Advance (-1 + ((read + 4) & ~3) - read); return new string (buffer, 0, read); } string ReadZeroTerminatedString (int length) { int read = 0; var buffer = new char [length]; var bytes = ReadBytes (length); while (read < length) { var current = bytes [read]; if (current == 0) break; buffer [read++] = (char) current; } return new string (buffer, 0, read); } void ReadSections (ushort count) { var sections = new Section [count]; for (int i = 0; i < count; i++) { var section = new Section (); // Name section.Name = ReadZeroTerminatedString (8); // VirtualSize 4 Advance (4); // VirtualAddress 4 section.VirtualAddress = ReadUInt32 (); // SizeOfRawData 4 section.SizeOfRawData = ReadUInt32 (); // PointerToRawData 4 section.PointerToRawData = ReadUInt32 (); // PointerToRelocations 4 // PointerToLineNumbers 4 // NumberOfRelocations 2 // NumberOfLineNumbers 2 // Characteristics 4 Advance (16); sections [i] = section; if (section.Name == ".reloc") continue; ReadSectionData (section); } image.Sections = sections; } void ReadSectionData (Section section) { var position = BaseStream.Position; MoveTo (section.PointerToRawData); var length = (int) section.SizeOfRawData; var data = new byte [length]; int offset = 0, read; while ((read = Read (data, offset, length - offset)) > 0) offset += read; section.Data = data; BaseStream.Position = position; } void ReadCLIHeader () { MoveTo (cli); // - CLIHeader // Cb 4 // MajorRuntimeVersion 2 // MinorRuntimeVersion 2 Advance (8); // Metadata 8 metadata = ReadDataDirectory (); // Flags 4 image.Attributes = (ModuleAttributes) ReadUInt32 (); // EntryPointToken 4 image.EntryPointToken = ReadUInt32 (); // Resources 8 image.Resources = ReadDataDirectory (); // StrongNameSignature 8 // CodeManagerTable 8 // VTableFixups 8 // ExportAddressTableJumps 8 // ManagedNativeHeader 8 } void ReadMetadata () { MoveTo (metadata); if (ReadUInt32 () != 0x424a5342) throw new BadImageFormatException (); // MajorVersion 2 // MinorVersion 2 // Reserved 4 Advance (8); var version = ReadZeroTerminatedString (ReadInt32 ()); image.Runtime = version.ParseRuntime (); // Flags 2 Advance (2); var streams = ReadUInt16 (); var section = image.GetSectionAtVirtualAddress (metadata.VirtualAddress); if (section == null) throw new BadImageFormatException (); image.MetadataSection = section; for (int i = 0; i < streams; i++) ReadMetadataStream (section); if (image.TableHeap != null) ReadTableHeap (); } void ReadMetadataStream (Section section) { // Offset 4 uint start = metadata.VirtualAddress - section.VirtualAddress + ReadUInt32 (); // relative to the section start // Size 4 uint size = ReadUInt32 (); var name = ReadAlignedString (16); switch (name) { case "#~": case "#-": image.TableHeap = new TableHeap (section, start, size); break; case "#Strings": image.StringHeap = new StringHeap (section, start, size); break; case "#Blob": image.BlobHeap = new BlobHeap (section, start, size); break; case "#GUID": image.GuidHeap = new GuidHeap (section, start, size); break; case "#US": image.UserStringHeap = new UserStringHeap (section, start, size); break; } } void ReadTableHeap () { var heap = image.TableHeap; uint start = heap.Section.PointerToRawData; MoveTo (heap.Offset + start); // Reserved 4 // MajorVersion 1 // MinorVersion 1 Advance (6); // HeapSizes 1 var sizes = ReadByte (); // Reserved2 1 Advance (1); // Valid 8 heap.Valid = ReadInt64 (); // Sorted 8 heap.Sorted = ReadInt64 (); for (int i = 0; i < TableHeap.TableIdentifiers.Length; i++) { var table = TableHeap.TableIdentifiers [i]; if (!heap.HasTable (table)) continue; heap.Tables [(int) table].Length = ReadUInt32 (); } SetIndexSize (image.StringHeap, sizes, 0x1); SetIndexSize (image.GuidHeap, sizes, 0x2); SetIndexSize (image.BlobHeap, sizes, 0x4); ComputeTableInformations (); } static void SetIndexSize (Heap heap, uint sizes, byte flag) { if (heap == null) return; heap.IndexSize = (sizes & flag) > 0 ? 4 : 2; } int GetTableIndexSize (Table table) { return image.GetTableIndexSize (table); } int GetCodedIndexSize (CodedIndex index) { return image.GetCodedIndexSize (index); } void ComputeTableInformations () { uint offset = (uint) BaseStream.Position - image.MetadataSection.PointerToRawData; // header int stridx_size = image.StringHeap.IndexSize; int blobidx_size = image.BlobHeap != null ? image.BlobHeap.IndexSize : 2; var heap = image.TableHeap; var tables = heap.Tables; for (int i = 0; i < TableHeap.TableIdentifiers.Length; i++) { var table = TableHeap.TableIdentifiers [i]; if (!heap.HasTable (table)) continue; int size; switch (table) { case Table.Module: size = 2 // Generation + stridx_size // Name + (image.GuidHeap.IndexSize * 3); // Mvid, EncId, EncBaseId break; case Table.TypeRef: size = GetCodedIndexSize (CodedIndex.ResolutionScope) // ResolutionScope + (stridx_size * 2); // Name, Namespace break; case Table.TypeDef: size = 4 // Flags + (stridx_size * 2) // Name, Namespace + GetCodedIndexSize (CodedIndex.TypeDefOrRef) // BaseType + GetTableIndexSize (Table.Field) // FieldList + GetTableIndexSize (Table.Method); // MethodList break; case Table.FieldPtr: size = GetTableIndexSize (Table.Field); // Field break; case Table.Field: size = 2 // Flags + stridx_size // Name + blobidx_size; // Signature break; case Table.MethodPtr: size = GetTableIndexSize (Table.Method); // Method break; case Table.Method: size = 8 // Rva 4, ImplFlags 2, Flags 2 + stridx_size // Name + blobidx_size // Signature + GetTableIndexSize (Table.Param); // ParamList break; case Table.ParamPtr: size = GetTableIndexSize (Table.Param); // Param break; case Table.Param: size = 4 // Flags 2, Sequence 2 + stridx_size; // Name break; case Table.InterfaceImpl: size = GetTableIndexSize (Table.TypeDef) // Class + GetCodedIndexSize (CodedIndex.TypeDefOrRef); // Interface break; case Table.MemberRef: size = GetCodedIndexSize (CodedIndex.MemberRefParent) // Class + stridx_size // Name + blobidx_size; // Signature break; case Table.Constant: size = 2 // Type + GetCodedIndexSize (CodedIndex.HasConstant) // Parent + blobidx_size; // Value break; case Table.CustomAttribute: size = GetCodedIndexSize (CodedIndex.HasCustomAttribute) // Parent + GetCodedIndexSize (CodedIndex.CustomAttributeType) // Type + blobidx_size; // Value break; case Table.FieldMarshal: size = GetCodedIndexSize (CodedIndex.HasFieldMarshal) // Parent + blobidx_size; // NativeType break; case Table.DeclSecurity: size = 2 // Action + GetCodedIndexSize (CodedIndex.HasDeclSecurity) // Parent + blobidx_size; // PermissionSet break; case Table.ClassLayout: size = 6 // PackingSize 2, ClassSize 4 + GetTableIndexSize (Table.TypeDef); // Parent break; case Table.FieldLayout: size = 4 // Offset + GetTableIndexSize (Table.Field); // Field break; case Table.StandAloneSig: size = blobidx_size; // Signature break; case Table.EventMap: size = GetTableIndexSize (Table.TypeDef) // Parent + GetTableIndexSize (Table.Event); // EventList break; case Table.EventPtr: size = GetTableIndexSize (Table.Event); // Event break; case Table.Event: size = 2 // Flags + stridx_size // Name + GetCodedIndexSize (CodedIndex.TypeDefOrRef); // EventType break; case Table.PropertyMap: size = GetTableIndexSize (Table.TypeDef) // Parent + GetTableIndexSize (Table.Property); // PropertyList break; case Table.PropertyPtr: size = GetTableIndexSize (Table.Property); // Property break; case Table.Property: size = 2 // Flags + stridx_size // Name + blobidx_size; // Type break; case Table.MethodSemantics: size = 2 // Semantics + GetTableIndexSize (Table.Method) // Method + GetCodedIndexSize (CodedIndex.HasSemantics); // Association break; case Table.MethodImpl: size = GetTableIndexSize (Table.TypeDef) // Class + GetCodedIndexSize (CodedIndex.MethodDefOrRef) // MethodBody + GetCodedIndexSize (CodedIndex.MethodDefOrRef); // MethodDeclaration break; case Table.ModuleRef: size = stridx_size; // Name break; case Table.TypeSpec: size = blobidx_size; // Signature break; case Table.ImplMap: size = 2 // MappingFlags + GetCodedIndexSize (CodedIndex.MemberForwarded) // MemberForwarded + stridx_size // ImportName + GetTableIndexSize (Table.ModuleRef); // ImportScope break; case Table.FieldRVA: size = 4 // RVA + GetTableIndexSize (Table.Field); // Field break; case Table.Assembly: size = 16 // HashAlgId 4, Version 4 * 2, Flags 4 + blobidx_size // PublicKey + (stridx_size * 2); // Name, Culture break; case Table.AssemblyProcessor: size = 4; // Processor break; case Table.AssemblyOS: size = 12; // Platform 4, Version 2 * 4 break; case Table.AssemblyRef: size = 12 // Version 2 * 4 + Flags 4 + (blobidx_size * 2) // PublicKeyOrToken, HashValue + (stridx_size * 2); // Name, Culture break; case Table.AssemblyRefProcessor: size = 4 // Processor + GetTableIndexSize (Table.AssemblyRef); // AssemblyRef break; case Table.AssemblyRefOS: size = 12 // Platform 4, Version 2 * 4 + GetTableIndexSize (Table.AssemblyRef); // AssemblyRef break; case Table.File: size = 4 // Flags + stridx_size // Name + blobidx_size; // HashValue break; case Table.ExportedType: size = 8 // Flags 4, TypeDefId 4 + (stridx_size * 2) // Name, Namespace + GetCodedIndexSize (CodedIndex.Implementation); // Implementation break; case Table.ManifestResource: size = 8 // Offset, Flags + stridx_size // Name + GetCodedIndexSize (CodedIndex.Implementation); // Implementation break; case Table.NestedClass: size = GetTableIndexSize (Table.TypeDef) // NestedClass + GetTableIndexSize (Table.TypeDef); // EnclosingClass break; case Table.GenericParam: size = 4 // Number, Flags + GetCodedIndexSize (CodedIndex.TypeOrMethodDef) // Owner + stridx_size; // Name break; case Table.MethodSpec: size = GetCodedIndexSize (CodedIndex.MethodDefOrRef) // Method + blobidx_size; // Instantiation break; case Table.GenericParamConstraint: size = GetTableIndexSize (Table.GenericParam) // Owner + GetCodedIndexSize (CodedIndex.TypeDefOrRef); // Constraint break; default: throw new NotSupportedException (); } int index = (int) table; tables [index].RowSize = (uint) size; tables [index].Offset = offset; offset += (uint) size * tables [index].Length; } } public static Image ReadImageFrom (Stream stream) { try { var reader = new ImageReader (stream); reader.ReadImage (); return reader.image; } catch (EndOfStreamException e) { throw new BadImageFormatException (stream.GetFullyQualifiedName (), e); } } } }
using System; using System.Collections.Generic; using Xunit; using NReco.Data; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; namespace NReco.Data.Tests { public class RecordSetTests { public static RecordSet generateRecordSet() { var testRS = new RecordSet(new[] { new RecordSet.Column("id", typeof(int)), new RecordSet.Column("name", typeof(string)), new RecordSet.Column("amount", typeof(decimal)), new RecordSet.Column("added_date", typeof(DateTime)) }); for (int i = 0; i<100; i++) { testRS.Add(new object[] { i, "Name"+i.ToString(), i%20, new DateTime(2000, 1, 1).AddMonths(i) }); } return testRS; } [Fact] public void CrudOperations() { var rs = new RecordSet( new[] { new RecordSet.Column("id", typeof(int)), new RecordSet.Column("name", typeof(string)), new RecordSet.Column("age", typeof(int)) } ); // columns collection Assert.Equal(3, rs.Columns.Count); Assert.Equal(1, rs.Columns.GetOrdinal("name")); Assert.Equal("age", rs.Columns[2].Name); Assert.Equal("name", rs.Columns["name"].Name); Assert.Throws<ArgumentException>( () => { rs.Add( new object[2]); }); Assert.Throws<ArgumentException>( () => { rs.Add( new object[4]); }); Action<int,string,int> addRow = (id, name, age) => { var r = rs.Add(); r["id"] = id; r["name"] = name; r["age"] = age; }; addRow(1, "John", 25); addRow(2, "Mary", 28); addRow(3, "Ray", 32); Assert.Equal(3, rs.Count); Assert.Equal( RecordSet.RowState.Added, rs[0].State & RecordSet.RowState.Added ); rs.AcceptChanges(); Assert.Equal(3, rs.Count); Assert.Equal( RecordSet.RowState.Unchanged, rs[0].State ); rs[2].Delete(); Assert.Equal( RecordSet.RowState.Deleted, rs[2].State); rs.AcceptChanges(); Assert.Equal(2, rs.Count); // add values array rs.Add(new object[] {4, "Adam", 45}); Assert.Equal(3, rs.Count); // add dictionary rs.Add(new Dictionary<string,object>() { {"name", "Gomer"} }); Assert.Equal(4, rs.Count); // typed accessor Assert.Equal( "Gomer", rs[3].Field<string>("name") ); Assert.Equal( null, rs[3].Field<int?>("age") ); Assert.Equal( 45, rs[2].Field<int?>("age") ); rs[0]["name"] = "Bart"; Assert.Equal( RecordSet.RowState.Modified, rs[0].State & RecordSet.RowState.Modified ); rs[0].AcceptChanges(); Assert.Equal( RecordSet.RowState.Unchanged, rs[0].State ); Assert.Equal( "Bart", rs[0]["name"] ); Assert.Throws<ArgumentException>( () => { var t = rs[0]["test"]; }); } [Fact] public void RecordSetReader() { var testRS = generateRecordSet(); var rdr = new RecordSetReader(testRS); Assert.True( rdr.HasRows ); Assert.Throws<InvalidOperationException>( () => { var o = rdr[0]; }); Assert.True( rdr.Read() ); Assert.Equal( 4, rdr.FieldCount ); Assert.Equal("id", rdr.GetName(0)); Assert.Equal(2, rdr.GetOrdinal("amount")); Assert.Equal("added_date", rdr.GetName(3)); Assert.Throws<IndexOutOfRangeException>( () => { var o = rdr.GetName(4); }); Assert.Equal(0, rdr.GetInt32(0) ); Assert.Equal(0, rdr[0]); Assert.Equal("Name0", rdr[1]); Assert.Equal(0, rdr[2]); Assert.Equal(1, rdr.GetDateTime(3).Month); int cnt = 1; while (rdr.Read()) { Assert.Equal(cnt, rdr[0] ); cnt++; } Assert.Throws<InvalidOperationException>( () => { var o = rdr[0]; }); rdr.Dispose(); Assert.Throws<InvalidOperationException>( () => { var o = rdr.FieldCount; }); Assert.Throws<InvalidOperationException>( () => { var o = rdr.GetOrdinal("id"); }); Assert.Equal(100, cnt); // read RS from RecordSetReader var testRSCopy = RecordSet.FromReader( new RecordSetReader(testRS) ); Assert.Equal( testRS.Count, testRSCopy.Count ); Assert.Equal( testRS.Columns.Count, testRSCopy.Columns.Count ); var testRSCopyOneRec = RecordSet.FromReader(new RecordSetReader(testRS), 1); Assert.Equal(1, testRSCopyOneRec.Count); // read into initialized RecordSet var newRS = new RecordSet( new[] { new RecordSet.Column("id", typeof(int)), new RecordSet.Column("name", typeof(string)) } ); newRS.Load( new RecordSetReader(testRS) ); Assert.Equal(testRS.Count, newRS.Count); Assert.Equal("Name99", newRS[99].Field<string>("name")); } [Fact] public void RecordSet_FromModel() { var rs1 = RecordSet.FromModel<PersonModel>(); Assert.Equal( 5, rs1.Columns.Count ); Assert.Equal( 1, rs1.PrimaryKey.Length ); Assert.Equal("id", rs1.PrimaryKey[0].Name ); Assert.True(rs1.PrimaryKey[0].AutoIncrement ); Assert.True(rs1.PrimaryKey[0].ReadOnly ); Assert.Equal("first_name", rs1.Columns[1].Name ); var rs2 = RecordSet.FromModel( new PersonModel() { Id = 9, FirstName = "John" }, RecordSet.RowState.Modified ); Assert.Equal(1, rs2.Count); Assert.Equal(9, rs2[0].Field<int>("id") ); Assert.Equal("John", rs2[0].Field<string>("first_name") ); Assert.Equal(RecordSet.RowState.Modified, rs2[0].State ); } [Table("persons")] public class PersonModel { [DatabaseGenerated(DatabaseGeneratedOption.Identity)] [Key] [Column("id")] public int? Id { get; set; } [Column("first_name")] public string FirstName { get; set; } [Column("last_name")] public string LastName { get; set; } [Column("birthday")] public DateTime? BirthDay { get; set; } // not annotated field public bool Active; [NotMapped] public string Name { get { return $"{FirstName} {LastName}"; } } } } }
/* Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the MIT License. See License.txt in the project root for license information. */ namespace Adxstudio.Xrm.Search.Store.Encryption { using System; using System.Linq; /// <summary> /// The buffered page reader writer. /// </summary> public abstract class BufferedPageReaderWriter : IBufferedPageReader, IBufferedPageWriter { /// <summary> /// The buffer pointer. /// </summary> protected int bufferPointer; /// <summary> /// The file pointer. /// </summary> protected long filePointer; /// <summary> /// The file size. /// </summary> protected long fileSize; /// <summary> /// The page buffer. /// </summary> protected byte[] pageBuffer; /// <summary> /// The page is changed. /// </summary> protected bool pageIsChanged; /// <summary> /// The page number. /// </summary> protected long pageNumber; /// <summary> /// Gets the length. /// </summary> public abstract long Length { get; } /// <summary> /// Gets the page size. /// </summary> public abstract int PageSize { get; } /// <summary> /// Clones the object. /// </summary> /// <returns>copy of instance</returns> public abstract object Clone(); /// <summary> /// Gets the length. /// </summary> long IBufferedPageReader.Length { get { return this.Length; } } /// <summary> /// Gets the position. /// </summary> long IBufferedPageReader.Position { get { return this.filePointer; } } /// <summary> /// Gets the length. /// </summary> long IBufferedPageWriter.Length { get { return this.Length; } } /// <summary> /// Gets the position. /// </summary> long IBufferedPageWriter.Position { get { return this.filePointer; } } /// <summary> /// The dispose. /// </summary> public virtual void Dispose() { this.Flush(); } /// <summary> /// The flush. /// </summary> public void Flush() { this.WriteCurrentPage(); } /// <summary> /// The read byte. /// </summary> /// <returns> /// The <see cref="byte"/>. /// </returns> public byte ReadByte() { if (this.bufferPointer == this.PageSize) { this.pageNumber++; this.bufferPointer = 0; this.ReadCurrentPage(); } var @byte = this.pageBuffer[this.bufferPointer++]; this.filePointer++; return @byte; } /// <summary> /// The read bytes. /// </summary> /// <param name="destination"> /// The destination. /// </param> /// <param name="offset"> /// The offset. /// </param> /// <param name="length"> /// The length. /// </param> public void ReadBytes(byte[] destination, int offset, int length) { // TODO: Optimize with Buffer.BlockCopy for (var i = 0; i < length; i++) { var @byte = this.ReadByte(); destination[offset + i] = @byte; } } /// <summary> /// The read page. /// </summary> /// <param name="pageNumber"> /// The page number. /// </param> /// <param name="destination"> /// The destination. /// </param> public abstract void ReadPage(long pageNumber, byte[] destination); /// <summary> /// The write byte. /// </summary> /// <param name="byte"> /// The byte. /// </param> public void WriteByte(byte @byte) { if (this.bufferPointer == this.PageSize) { this.WriteCurrentPage(); this.bufferPointer = 0; this.pageNumber++; this.ReadCurrentPage(); } this.pageBuffer[this.bufferPointer++] = @byte; this.pageIsChanged = true; this.filePointer++; if (this.filePointer > this.fileSize) { this.fileSize = this.filePointer; } } /// <summary> /// The write bytes. /// </summary> /// <param name="source"> /// The source. /// </param> /// <param name="offset"> /// The offset. /// </param> /// <param name="length"> /// The length. /// </param> public void WriteBytes(byte[] source, int offset, int length) { var range = source.Skip(offset).Take(length).ToArray(); foreach (byte @byte in range) { this.WriteByte(@byte); } } /// <summary> /// The write page. /// </summary> /// <param name="pageNumber"> /// The page number. /// </param> /// <param name="source"> /// The source. /// </param> public abstract void WritePage(long pageNumber, byte[] source); /// <summary> /// The seek. /// </summary> /// <param name="position"> /// The position. /// </param> void IBufferedPageReader.Seek(long position) { this.Seek(position); } /// <summary> /// The seek. /// </summary> /// <param name="position"> /// The position. /// </param> void IBufferedPageWriter.Seek(long position) { this.Seek(position); } /// <summary> /// The initialize. /// </summary> protected void Initialize() { this.pageBuffer = new byte[this.PageSize]; this.pageNumber = -1; this.Seek(0); } /// <summary> /// The read current page. /// </summary> /// <exception cref="InvalidOperationException"> /// Invalid Operation Exception /// </exception> protected void ReadCurrentPage() { if (this.pageIsChanged) { throw new InvalidOperationException("Save page before read"); } if (this.pageNumber * this.PageSize >= this.Length) { // There are no more data. Fill next page with zeros Array.Clear(this.pageBuffer, 0, this.PageSize); } else { this.ReadPage(this.pageNumber, this.pageBuffer); } this.pageIsChanged = false; } /// <summary> /// The seek. /// </summary> /// <param name="position"> /// The position. /// </param> protected void Seek(long position) { this.Flush(); var pageNumber = (int)Math.Floor((double)position / this.PageSize); this.filePointer = position; this.bufferPointer = (int)(position - (pageNumber * this.PageSize)); if (pageNumber == this.pageNumber) { return; } this.pageNumber = pageNumber; this.ReadCurrentPage(); } /// <summary> /// The write current page. /// </summary> protected void WriteCurrentPage() { if (!this.pageIsChanged) { return; } this.WritePage(this.pageNumber, this.pageBuffer); this.pageIsChanged = false; } } }
#region license // Copyright (c) 2004, Rodrigo B. de Oliveira (rbo@acm.org) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Rodrigo B. de Oliveira nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using Boo.Lang.Compiler.Ast; using Boo.Lang.Compiler.Services; using Boo.Lang.Compiler.TypeSystem.Builders; using Boo.Lang.Compiler.TypeSystem.Internal; using Boo.Lang.Environments; using Attribute = Boo.Lang.Compiler.Ast.Attribute; namespace Boo.Lang.Compiler.TypeSystem { public class BooCodeBuilder : ICodeBuilder { private readonly EnvironmentProvision<TypeSystemServices> _tss = new EnvironmentProvision<TypeSystemServices>(); private readonly EnvironmentProvision<InternalTypeSystemProvider> _internalTypeSystemProvider = new EnvironmentProvision<InternalTypeSystemProvider>(); private readonly DynamicVariable<ITypeReferenceFactory> _typeReferenceFactory; public BooCodeBuilder() { _typeReferenceFactory = new DynamicVariable<ITypeReferenceFactory>(new StandardTypeReferenceFactory(this)); } public TypeSystemServices TypeSystemServices { get { return _tss; } } public int GetFirstParameterIndex(TypeMember member) { return member.IsStatic ? 0 : 1; } public Statement CreateFieldAssignment(Field node, Expression initializer) { var fieldEntity = (InternalField)TypeSystem.TypeSystemServices.GetEntity(node); return CreateFieldAssignment(node.LexicalInfo, fieldEntity, initializer); } public Statement CreateFieldAssignment(LexicalInfo lexicalInfo, IField fieldEntity, Expression initializer) { return new ExpressionStatement(lexicalInfo, CreateFieldAssignmentExpression(fieldEntity, initializer)); } public Expression CreateFieldAssignmentExpression(IField fieldEntity, Expression initializer) { return CreateAssignment(initializer.LexicalInfo, CreateReference(fieldEntity), initializer); } public Attribute CreateAttribute(System.Type type) { return CreateAttribute(TypeSystemServices.Map(type)); } public Attribute CreateAttribute(IType type) { return CreateAttribute(DefaultConstructorFor(type)); } public Attribute CreateAttribute(IConstructor constructor) { return new Attribute { Name = constructor.DeclaringType.FullName, Entity = constructor }; } public Attribute CreateAttribute(IConstructor constructor, Expression arg) { var attribute = CreateAttribute(constructor); attribute.Arguments.Add(arg); return attribute; } public Ast.Module CreateModule(string moduleName, string nameSpace) { var module = new Ast.Module { Name = moduleName }; if (!string.IsNullOrEmpty(nameSpace)) module.Namespace = new NamespaceDeclaration(nameSpace); InternalTypeSystemProvider.EntityFor(module); // ensures the module is bound return module; } private InternalTypeSystemProvider InternalTypeSystemProvider { get { return _internalTypeSystemProvider.Instance; } } public BooClassBuilder CreateClass(string name) { return new BooClassBuilder(name); } public BooClassBuilder CreateClass(string name, TypeMemberModifiers modifiers) { var builder = CreateClass(name); builder.Modifiers = modifiers; return builder; } public Expression CreateDefaultInitializer(LexicalInfo li, ReferenceExpression target, IType type) { return type.IsValueType ? CreateInitValueType(li, target) : CreateAssignment(li, target, CreateNullLiteral()); } public Expression CreateDefaultInitializer(LexicalInfo li, InternalLocal local) { return CreateDefaultInitializer(li, CreateReference(local), local.Type); } public Expression CreateInitValueType(LexicalInfo li, ReferenceExpression target) { var mie = CreateBuiltinInvocation(li, BuiltinFunction.InitValueType); mie.Arguments.Add(target); return mie; } public Expression CreateInitValueType(LexicalInfo li, InternalLocal local) { return CreateInitValueType(li, CreateReference(local)); } public Expression CreateCast(IType type, Expression target) { if (type == target.ExpressionType) return target; var expression = new CastExpression(target.LexicalInfo); expression.Type = CreateTypeReference(type); expression.Target = target; expression.ExpressionType = type; return expression; } public TypeofExpression CreateTypeofExpression(IType type) { return new TypeofExpression { Type = CreateTypeReference(type), ExpressionType = TypeSystemServices.TypeType }; } public Expression CreateTypeofExpression(System.Type type) { return CreateTypeofExpression(TypeSystemServices.Map(type)); } public ReferenceExpression CreateLabelReference(LabelStatement label) { var reference = new ReferenceExpression(label.LexicalInfo, label.Name); reference.Entity = label.Entity; return reference; } public Statement CreateSwitch(LexicalInfo li, Expression offset, IEnumerable<LabelStatement> labels) { offset.LexicalInfo = li; return CreateSwitch(offset, labels); } public Statement CreateSwitch(Expression offset, IEnumerable<LabelStatement> labels) { MethodInvocationExpression sw = CreateBuiltinInvocation(offset.LexicalInfo, BuiltinFunction.Switch); sw.Arguments.Add(offset); foreach (LabelStatement label in labels) { sw.Arguments.Add(CreateLabelReference(label)); } sw.ExpressionType = TypeSystemServices.VoidType; return new ExpressionStatement(sw); } public Expression CreateAddressOfExpression(IMethod method) { MethodInvocationExpression mie = new MethodInvocationExpression(); mie.Target = CreateBuiltinReference(BuiltinFunction.AddressOf); mie.Arguments.Add(CreateMethodReference(method)); mie.ExpressionType = TypeSystemServices.IntPtrType; return mie; } public MethodInvocationExpression CreateMethodInvocation(Expression target, MethodInfo method) { return CreateMethodInvocation(target, TypeSystemServices.Map(method)); } public MethodInvocationExpression CreatePropertyGet(Expression target, IProperty property) { return property.IsExtension ? CreateMethodInvocation(property.GetGetMethod(), target) : CreateMethodInvocation(target, property.GetGetMethod()); } public MethodInvocationExpression CreatePropertySet(Expression target, IProperty property, Expression value) { return CreateMethodInvocation(target, property.GetSetMethod(), value); } public MethodInvocationExpression CreateMethodInvocation(MethodInfo staticMethod, Expression arg) { return CreateMethodInvocation(TypeSystemServices.Map(staticMethod), arg); } public MethodInvocationExpression CreateMethodInvocation(MethodInfo staticMethod, Expression arg0, Expression arg1) { return CreateMethodInvocation(TypeSystemServices.Map(staticMethod), arg0, arg1); } public MethodInvocationExpression CreateMethodInvocation(LexicalInfo li, Expression target, IMethod tag, Expression arg) { MethodInvocationExpression mie = CreateMethodInvocation(target, tag, arg); mie.LexicalInfo = li; return mie; } public MethodInvocationExpression CreateMethodInvocation(Expression target, IMethod tag, Expression arg) { MethodInvocationExpression mie = CreateMethodInvocation(target, tag); mie.Arguments.Add(arg); return mie; } public MethodInvocationExpression CreateMethodInvocation(Expression target, IMethod entity, Expression arg1, Expression arg2) { MethodInvocationExpression mie = CreateMethodInvocation(target, entity, arg1); mie.Arguments.Add(arg2); return mie; } public MethodInvocationExpression CreateMethodInvocation(LexicalInfo li, IMethod staticMethod, Expression arg0, Expression arg1) { MethodInvocationExpression expression = CreateMethodInvocation(staticMethod, arg0, arg1); expression.LexicalInfo = li; return expression; } public MethodInvocationExpression CreateMethodInvocation(IMethod staticMethod, Expression arg0, Expression arg1) { MethodInvocationExpression mie = CreateMethodInvocation(staticMethod, arg0); mie.Arguments.Add(arg1); return mie; } public MethodInvocationExpression CreateMethodInvocation(LexicalInfo li, IMethod staticMethod, Expression arg0, Expression arg1, Expression arg2) { MethodInvocationExpression expression = CreateMethodInvocation(staticMethod, arg0, arg1, arg2); expression.LexicalInfo = li; return expression; } public MethodInvocationExpression CreateMethodInvocation(IMethod staticMethod, Expression arg0, Expression arg1, Expression arg2) { MethodInvocationExpression mie = CreateMethodInvocation(staticMethod, arg0, arg1); mie.Arguments.Add(arg2); return mie; } public MethodInvocationExpression CreateMethodInvocation(IMethod staticMethod, Expression arg) { MethodInvocationExpression mie = CreateMethodInvocation(staticMethod); mie.LexicalInfo = arg.LexicalInfo; mie.Arguments.Add(arg); return mie; } public MethodInvocationExpression CreateMethodInvocation(IMethod method) { MethodInvocationExpression mie = new MethodInvocationExpression(); mie.Target = CreateMemberReference(method); mie.ExpressionType = method.ReturnType; return mie; } public TypeReference CreateTypeReference(Type type) { return CreateTypeReference(TypeSystemServices.Map(type)); } public TypeReference CreateTypeReference(LexicalInfo li, Type type) { return CreateTypeReference(li, TypeSystemServices.Map(type)); } public TypeReference CreateTypeReference(LexicalInfo li, IType type) { TypeReference reference = CreateTypeReference(type); reference.LexicalInfo = li; return reference; } public TypeReference CreateTypeReference(IType type) { return TypeReferenceFactory.TypeReferenceFor(type); } private ITypeReferenceFactory TypeReferenceFactory { get { return _typeReferenceFactory.Value; } } public SuperLiteralExpression CreateSuperReference(IType expressionType) { return new SuperLiteralExpression { ExpressionType = expressionType }; } public SelfLiteralExpression CreateSelfReference(LexicalInfo location, IType expressionType) { var reference = CreateSelfReference(expressionType); reference.LexicalInfo = location; return reference; } public SelfLiteralExpression CreateSelfReference(IType expressionType) { return new SelfLiteralExpression { ExpressionType = expressionType }; } public ReferenceExpression CreateLocalReference(string name, InternalLocal entity) { return CreateTypedReference(name, entity); } public ReferenceExpression CreateTypedReference(string name, ITypedEntity entity) { ReferenceExpression expression = new ReferenceExpression(name); expression.Entity = entity; expression.ExpressionType = entity.Type; return expression; } public ReferenceExpression CreateReference(IEntity entity) { switch (entity.EntityType) { case EntityType.Local: return CreateReference((InternalLocal)entity); case EntityType.Field: return CreateReference((IField)entity); case EntityType.Parameter: return CreateReference((InternalParameter)entity); //case EntityType.Custom: return CreateTypedReference(entity.Name, (ITypedEntity)entity); case EntityType.Property: return CreateReference((IProperty)entity); } return CreateTypedReference(entity.Name, (ITypedEntity)entity); } public ReferenceExpression CreateReference(InternalLocal local) { return CreateLocalReference(local.Name, local); } public MemberReferenceExpression CreateReference(LexicalInfo li, Field field) { MemberReferenceExpression e = CreateReference(field); e.LexicalInfo = li; return e; } public MemberReferenceExpression CreateReference(Field field) { return CreateReference((IField)field.Entity); } public MemberReferenceExpression CreateReference(IField field) { return CreateMemberReference(field); } public MemberReferenceExpression CreateReference(Property property) { return CreateReference((IProperty)property.Entity); } public MemberReferenceExpression CreateReference(IProperty property) { return CreateMemberReference(property); } public MemberReferenceExpression CreateMemberReference(IMember member) { Expression target = member.IsStatic ? (Expression)CreateReference(member.DeclaringType) : (Expression)CreateSelfReference(member.DeclaringType); return CreateMemberReference(target, member); } public MemberReferenceExpression CreateMemberReference(LexicalInfo li, Expression target, IMember member) { MemberReferenceExpression expression = CreateMemberReference(target, member); expression.LexicalInfo = li; return expression; } public MemberReferenceExpression CreateMemberReference(Expression target, IMember member) { MemberReferenceExpression reference = MemberReferenceForEntity(target, member); reference.ExpressionType = member.Type; return reference; } public MemberReferenceExpression MemberReferenceForEntity(Expression target, IEntity entity) { MemberReferenceExpression reference = new MemberReferenceExpression(target.LexicalInfo); reference.Target = target; reference.Name = entity.Name; reference.Entity = entity; return reference; } public MethodInvocationExpression CreateMethodInvocation(LexicalInfo li, Expression target, IMethod entity) { MethodInvocationExpression expression = CreateMethodInvocation(target, entity); expression.LexicalInfo = li; return expression; } public MethodInvocationExpression CreateMethodInvocation(Expression target, IMethod entity) { return new MethodInvocationExpression(target.LexicalInfo) { Target = CreateMemberReference(target, entity), ExpressionType = entity.ReturnType }; } public ReferenceExpression CreateReference(LexicalInfo info, IType type) { var expression = CreateReference(type); expression.LexicalInfo = info; return expression; } public ReferenceExpression CreateReference(LexicalInfo li, System.Type type) { return CreateReference(li, TypeSystemServices.Map(type)); } public ReferenceExpression CreateReference(IType type) { return new ReferenceExpression(type.FullName) {Entity = type, IsSynthetic = true}; } public MethodInvocationExpression CreateEvalInvocation(LexicalInfo li) { return CreateBuiltinInvocation(li, BuiltinFunction.Eval); } private static MethodInvocationExpression CreateBuiltinInvocation(LexicalInfo li, BuiltinFunction builtin) { return new MethodInvocationExpression(li) { Target = CreateBuiltinReference(builtin) }; } public static ReferenceExpression CreateBuiltinReference(BuiltinFunction builtin) { return new ReferenceExpression(builtin.Name) { Entity = builtin }; } public MethodInvocationExpression CreateEvalInvocation(LexicalInfo li, Expression arg, Expression value) { MethodInvocationExpression eval = CreateEvalInvocation(li); eval.Arguments.Add(arg); eval.Arguments.Add(value); eval.ExpressionType = value.ExpressionType; return eval; } public UnpackStatement CreateUnpackStatement(DeclarationCollection declarations, Expression expression) { UnpackStatement unpack = new UnpackStatement(expression.LexicalInfo); unpack.Declarations.AddRange(declarations); unpack.Expression = expression; return unpack; } public BinaryExpression CreateAssignment(LexicalInfo li, Expression lhs, Expression rhs) { BinaryExpression assignment = CreateAssignment(lhs, rhs); assignment.LexicalInfo = li; return assignment; } public BinaryExpression CreateAssignment(Expression lhs, Expression rhs) { return CreateBoundBinaryExpression(TypeSystemServices.GetExpressionType(lhs), BinaryOperatorType.Assign, lhs, rhs); } public Expression CreateMethodReference(IMethod method) { return CreateMemberReference(method); } public Expression CreateMethodReference(LexicalInfo lexicalInfo, IMethod method) { var e = CreateMethodReference(method); e.LexicalInfo = lexicalInfo; return e; } public BinaryExpression CreateBoundBinaryExpression(IType expressionType, BinaryOperatorType op, Expression lhs, Expression rhs) { return new BinaryExpression(op, lhs, rhs) { ExpressionType = expressionType, IsSynthetic = true }; } public BoolLiteralExpression CreateBoolLiteral(bool value) { return new BoolLiteralExpression(value) { ExpressionType = TypeSystemServices.BoolType }; } public StringLiteralExpression CreateStringLiteral(string value) { return new StringLiteralExpression(value) { ExpressionType = TypeSystemServices.StringType }; } public NullLiteralExpression CreateNullLiteral() { return new NullLiteralExpression { ExpressionType = Null.Default }; } public ArrayLiteralExpression CreateObjectArray(ExpressionCollection items) { return CreateArray(TypeSystemServices.ObjectArrayType, items); } public ArrayLiteralExpression CreateArray(IType arrayType, ExpressionCollection items) { if (!arrayType.IsArray) throw new ArgumentException(string.Format("'{0}' is not an array type!", arrayType), "arrayType"); var array = new ArrayLiteralExpression(); array.ExpressionType = arrayType; array.Items.AddRange(items); TypeSystemServices.MapToConcreteExpressionTypes(array.Items); return array; } public IntegerLiteralExpression CreateIntegerLiteral(int value) { return new IntegerLiteralExpression(value) { ExpressionType = TypeSystemServices.IntType }; } public IntegerLiteralExpression CreateIntegerLiteral(long value) { return new IntegerLiteralExpression(value) { ExpressionType = TypeSystemServices.LongType }; } public SlicingExpression CreateSlicing(Expression target, int begin) { var arrayType = target.ExpressionType as IArrayType; var expressionType = arrayType != null ? arrayType.ElementType : TypeSystemServices.ObjectType; return new SlicingExpression(target, CreateIntegerLiteral(begin)) { ExpressionType = expressionType }; } public ReferenceExpression CreateReference(ParameterDeclaration parameter) { return CreateReference((InternalParameter)TypeSystemServices.GetEntity(parameter)); } public ReferenceExpression CreateReference(InternalParameter parameter) { return new ReferenceExpression(parameter.Name) { Entity = parameter, ExpressionType = parameter.Type }; } public UnaryExpression CreateNotExpression(Expression node) { return new UnaryExpression { LexicalInfo = node.LexicalInfo, Operand = node, Operator = UnaryOperatorType.LogicalNot, ExpressionType = TypeSystemServices.BoolType }; } public ParameterDeclaration CreateParameterDeclaration(int index, string name, IType type, bool byref) { var modifiers = byref ? ParameterModifiers.Ref : ParameterModifiers.None; var parameter = new ParameterDeclaration(name, CreateTypeReference(type), modifiers); parameter.Entity = new InternalParameter(parameter, index); return parameter; } public ParameterDeclaration CreateParameterDeclaration(int index, string name, IType type) { return CreateParameterDeclaration(index, name, type, false); } //TODO: >=0.9, support constraints here public GenericParameterDeclaration CreateGenericParameterDeclaration(int index, string name) { GenericParameterDeclaration p = new GenericParameterDeclaration(name); p.Entity = new InternalGenericParameter(_tss, p, index); return p; } public Constructor CreateConstructor(TypeMemberModifiers modifiers) { Constructor constructor = new Constructor(); constructor.Modifiers = modifiers; constructor.IsSynthetic = true; EnsureEntityFor(constructor); return constructor; } private void EnsureEntityFor(TypeMember member) { InternalTypeSystemProvider.EntityFor(member); } public Constructor CreateStaticConstructor(TypeDefinition type) { var constructor = new Constructor(); constructor.IsSynthetic = true; constructor.Modifiers = TypeMemberModifiers.Private | TypeMemberModifiers.Static; EnsureEntityFor(constructor); type.Members.Add(constructor); return constructor; } public MethodInvocationExpression CreateConstructorInvocation(ClassDefinition cd) { IConstructor constructor = ((IType)cd.Entity).GetConstructors().First(); return CreateConstructorInvocation(constructor); } public MethodInvocationExpression CreateConstructorInvocation(IConstructor constructor, Expression arg1, Expression arg2) { MethodInvocationExpression mie = CreateConstructorInvocation(constructor, arg1); mie.Arguments.Add(arg2); return mie; } public MethodInvocationExpression CreateConstructorInvocation(IConstructor constructor, Expression arg) { MethodInvocationExpression mie = CreateConstructorInvocation(constructor); mie.LexicalInfo = arg.LexicalInfo; mie.Arguments.Add(arg); return mie; } public MethodInvocationExpression CreateConstructorInvocation(LexicalInfo lexicalInfo, IConstructor constructor, params Expression[] args) { MethodInvocationExpression mie = CreateConstructorInvocation(constructor); mie.LexicalInfo = lexicalInfo; mie.Arguments.AddRange(args); return mie; } public MethodInvocationExpression CreateConstructorInvocation(IConstructor constructor) { MethodInvocationExpression mie = new MethodInvocationExpression(); mie.Target = new ReferenceExpression(constructor.DeclaringType.FullName); mie.Target.Entity = constructor; mie.ExpressionType = constructor.DeclaringType; return mie; } public ExpressionStatement CreateSuperConstructorInvocation(IType baseType) { return CreateSuperConstructorInvocation(DefaultConstructorFor(baseType)); } private IConstructor DefaultConstructorFor(IType baseType) { IConstructor defaultConstructor = TypeSystemServices.GetDefaultConstructor(baseType); if (null == defaultConstructor) throw new ArgumentException("No default constructor for type '" + baseType + "'."); return defaultConstructor; } public ExpressionStatement CreateSuperConstructorInvocation(IConstructor defaultConstructor) { var call = new MethodInvocationExpression(new SuperLiteralExpression()); call.Target.Entity = defaultConstructor; call.ExpressionType = TypeSystemServices.VoidType; return new ExpressionStatement(call); } public MethodInvocationExpression CreateSuperMethodInvocation(IMethod superMethod) { var mie = new MethodInvocationExpression(CreateMemberReference(CreateSuperReference(superMethod.DeclaringType), superMethod)); mie.ExpressionType = superMethod.ReturnType; return mie; } public MethodInvocationExpression CreateSuperMethodInvocation(IMethod superMethod, Expression arg) { MethodInvocationExpression mie = CreateSuperMethodInvocation(superMethod); mie.Arguments.Add(arg); return mie; } public Method CreateVirtualMethod(string name, IType returnType) { return CreateVirtualMethod(name, CreateTypeReference(returnType)); } public Method CreateVirtualMethod(string name, TypeReference returnType) { return CreateMethod(name, returnType, TypeMemberModifiers.Public|TypeMemberModifiers.Virtual); } public Method CreateMethod(string name, IType returnType, TypeMemberModifiers modifiers) { return CreateMethod(name, CreateTypeReference(returnType), modifiers); } public Method CreateMethod(string name, TypeReference returnType, TypeMemberModifiers modifiers) { Method method = new Method(name); method.Modifiers = modifiers; method.ReturnType = returnType; method.IsSynthetic = true; EnsureEntityFor(method); return method; } public Property CreateProperty(string name, IType type) { Property property = new Property(name); property.Modifiers = TypeMemberModifiers.Public; property.Type = CreateTypeReference(type); property.IsSynthetic = true; EnsureEntityFor(property); return property; } public Field CreateField(string name, IType type) { Field field = new Field(); field.Modifiers = TypeMemberModifiers.Protected; field.Name = name; field.Type = CreateTypeReference(type); field.Entity = new InternalField(field); field.IsSynthetic = true; return field; } public Method CreateRuntimeMethod(string name, TypeReference returnType) { Method method = CreateVirtualMethod(name, returnType); method.ImplementationFlags = MethodImplementationFlags.Runtime; return method; } public Method CreateRuntimeMethod(string name, IType returnType) { return CreateRuntimeMethod(name, CreateTypeReference(returnType)); } public Method CreateRuntimeMethod(string name, IType returnType, IParameter[] parameters, bool hasParamArray) { Method method = CreateRuntimeMethod(name, returnType); DeclareParameters(method, parameters); method.Parameters.HasParamArray = hasParamArray; return method; } public void DeclareParameters(INodeWithParameters method, IParameter[] parameters) { DeclareParameters(method, parameters, 0); } public void DeclareParameters(INodeWithParameters method, IParameter[] parameters, int parameterIndexDelta) { for (int i=0; i < parameters.Length; ++i) { IParameter p = parameters[i]; int pIndex = parameterIndexDelta + i; method.Parameters.Add( CreateParameterDeclaration(pIndex, string.IsNullOrEmpty(p.Name) ? "arg"+pIndex : p.Name, p.Type, p.IsByRef)); } } public void DeclareGenericParameters(INodeWithGenericParameters node, IGenericParameter[] parameters) { DeclareGenericParameters(node, parameters, 0); } public void DeclareGenericParameters(INodeWithGenericParameters node, IGenericParameter[] parameters, int parameterIndexDelta) { for (int i=0; i < parameters.Length; ++i) { var prototype = parameters[i]; var newParameter = CreateGenericParameterDeclaration(parameterIndexDelta + i, prototype.Name); node.GenericParameters.Add(newParameter); } } public Method CreateAbstractMethod(LexicalInfo lexicalInfo, IMethod baseMethod) { TypeMemberModifiers visibility = VisibilityFrom(baseMethod); return CreateMethodFromPrototype(lexicalInfo, baseMethod, visibility | TypeMemberModifiers.Abstract); } private TypeMemberModifiers VisibilityFrom(IMethod baseMethod) { if (baseMethod.IsPublic) return TypeMemberModifiers.Public; if (baseMethod.IsInternal) return TypeMemberModifiers.Internal; return TypeMemberModifiers.Protected; } public Method CreateMethodFromPrototype(IMethod baseMethod, TypeMemberModifiers newModifiers) { return CreateMethodFromPrototype(LexicalInfo.Empty, baseMethod, newModifiers); } public Method CreateMethodFromPrototype(LexicalInfo lexicalInfo, IMethod baseMethod, TypeMemberModifiers newModifiers) { return CreateMethodFromPrototype(lexicalInfo, baseMethod, newModifiers, baseMethod.Name); } public Method CreateMethodFromPrototype(LexicalInfo location, IMethod baseMethod, TypeMemberModifiers newModifiers, string newMethodName) { var method = new Method(location); method.Name = newMethodName; method.Modifiers = newModifiers; method.IsSynthetic = true; var optionalTypeMappings = DeclareGenericParametersFromPrototype(method, baseMethod); var typeReferenceFactory = optionalTypeMappings != null ? new MappedTypeReferenceFactory(TypeReferenceFactory, optionalTypeMappings) : TypeReferenceFactory; _typeReferenceFactory.With(typeReferenceFactory, ()=> { DeclareParameters(method, baseMethod.GetParameters(), baseMethod.IsStatic ? 0 : 1); method.ReturnType = CreateTypeReference(baseMethod.ReturnType); }); EnsureEntityFor(method); return method; } private IDictionary<IType, IType> DeclareGenericParametersFromPrototype(Method method, IMethod baseMethod) { var genericMethodInfo = baseMethod.GenericInfo; if (genericMethodInfo == null) return null; var prototypeParameters = genericMethodInfo.GenericParameters; DeclareGenericParameters(method, prototypeParameters); var newGenericParameters = method.GenericParameters.ToArray(p => (IGenericParameter)p.Entity); return CreateDictionaryMapping(prototypeParameters, newGenericParameters); } private static IDictionary<IType, IType> CreateDictionaryMapping(IGenericParameter[] from, IGenericParameter[] to) { var mappings = new Dictionary<IType, IType>(from.Length); for (int i=0; i<from.Length; ++i) mappings.Add(from[i], to[i]); return mappings; } public Event CreateAbstractEvent(LexicalInfo lexicalInfo, IEvent baseEvent) { Event ev = new Event(lexicalInfo); ev.Name = baseEvent.Name; ev.Type = CreateTypeReference(baseEvent.Type); ev.Add = CreateAbstractMethod(lexicalInfo, baseEvent.GetAddMethod()); ev.Remove = CreateAbstractMethod(lexicalInfo, baseEvent.GetRemoveMethod()); EnsureEntityFor(ev); return ev; } public Expression CreateNotNullTest(Expression target) { BinaryExpression test = new BinaryExpression(target.LexicalInfo, BinaryOperatorType.ReferenceInequality, target, CreateNullLiteral()); test.ExpressionType = TypeSystemServices.BoolType; return test; } public RaiseStatement RaiseException(LexicalInfo lexicalInfo, IConstructor exceptionConstructor, params Expression[] args) { Debug.Assert(TypeSystemServices.IsValidException(exceptionConstructor.DeclaringType)); return new RaiseStatement(lexicalInfo, CreateConstructorInvocation(lexicalInfo, exceptionConstructor, args)); } public InternalLocal DeclareTempLocal(Method node, IType type) { var local = DeclareLocal(node, My<UniqueNameProvider>.Instance.GetUniqueName(), type); local.IsPrivateScope = true; return local; } public InternalLocal DeclareLocal(Method node, string name, IType type) { Local local = new Local(node.LexicalInfo, name); InternalLocal entity = new InternalLocal(local, type); local.Entity = entity; node.Locals.Add(local); return entity; } public void BindParameterDeclarations(bool isStatic, INodeWithParameters node) { // arg0 is the this pointer when member is not static int delta = isStatic ? 0 : 1; ParameterDeclarationCollection parameters = node.Parameters; for (int i=0; i<parameters.Count; ++i) { ParameterDeclaration parameter = parameters[i]; if (null == parameter.Type) { if (parameter.IsParamArray) { parameter.Type = CreateTypeReference(TypeSystemServices.ObjectArrayType); } else { parameter.Type = CreateTypeReference(TypeSystemServices.ObjectType); } } parameter.Entity = new InternalParameter(parameter, i + delta); } } public InternalLabel CreateLabel(Node sourceNode, string name) { return new InternalLabel(new LabelStatement(sourceNode.LexicalInfo, name)); } public TypeMember CreateStub(ClassDefinition node, IMember member) { IMethod baseMethod = member as IMethod; if (null != baseMethod) return CreateMethodStub(baseMethod); IProperty property = member as IProperty; if (null != property) return CreatePropertyStub(node, property); return null; } Method CreateMethodStub(IMethod baseMethod) { var stub = CreateMethodFromPrototype(baseMethod, TypeSystemServices.GetAccess(baseMethod) | TypeMemberModifiers.Virtual); var notImplementedException = new MethodInvocationExpression { Target = new MemberReferenceExpression(new ReferenceExpression("System"), "NotImplementedException") }; stub.Body.Statements.Add(new RaiseStatement(notImplementedException) { LexicalInfo = LexicalInfo.Empty }); return stub; } Property CreatePropertyStub(ClassDefinition node, IProperty baseProperty) { //try to complete partial implementation if any Property property = node.Members[baseProperty.Name] as Property; if (null == property) { property = new Property(LexicalInfo.Empty); property.Name = baseProperty.Name; property.Modifiers = TypeSystemServices.GetAccess(baseProperty) | TypeMemberModifiers.Virtual; property.IsSynthetic = true; DeclareParameters(property, baseProperty.GetParameters(), baseProperty.IsStatic ? 0 : 1); property.Type = CreateTypeReference(baseProperty.Type); } if (property.Getter == null && null != baseProperty.GetGetMethod()) property.Getter = CreateMethodStub(baseProperty.GetGetMethod()); if (property.Setter == null && null != baseProperty.GetSetMethod()) property.Setter = CreateMethodStub(baseProperty.GetSetMethod()); EnsureEntityFor(property); return property; } public Constructor GetOrCreateStaticConstructorFor(TypeDefinition type) { return type.GetStaticConstructor() ?? CreateStaticConstructor(type); } } }
/// <summary> /// NoiseGradient.cs /// Author: trent (5/16/16) /// Modified: /// /// Based on the implementation by Jordan Peck: https://github.com/Auburns/FastNoise /// </summary> /// <summary> /// NoiseGradient Class Definition. /// /// Gradient noise class. /// </summary> public class NoiseGradient : Noise { public static readonly float[,] LUT_Gradient2D = { { 0.465254262011416f, -0.885177084927198f }, { 0.999814701091156f, -0.0192500255065206f }, { 0.562013227349949f, 0.827128244157878f }, { 0.540531763173497f, -0.841323607775599f }, { -0.97869393624958f, 0.20532457024989f }, { -0.022259068317433f, 0.999752236245381f }, { -0.763453105361241f, -0.645863264100288f }, { -0.877652307360767f, 0.479297848299283f }, { -0.429945697678765f, 0.902854748587789f }, { -0.880336026899474f, 0.474350587374832f }, { -0.999734062007074f, 0.0230609033395389f }, { 0.961877124516138f, -0.273481987217745f }, { 0.485111864938318f, 0.874452101887844f }, { -0.307899752943979f, 0.951418804805243f }, { -0.991765219175154f, 0.128069317303008f }, { 0.937814305853532f, -0.347137332674633f }, { -0.398552509901734f, -0.917145515635893f }, { 0.701222178891205f, -0.712942813857514f }, { 0.873193936119955f, 0.487372906431349f }, { -0.514304676201594f, -0.857607544298191f }, { 0.0428414754286589f, 0.999081882521696f }, { -0.88038067821201f, 0.474267710719338f }, { 0.14177264550869f, 0.989899245875795f }, { -0.887664663265946f, -0.46049044027966f }, { 0.999983713358517f, -0.00570727760945115f }, { -0.623600504016441f, -0.781743187620104f }, { 0.888019464508127f, -0.459805861918592f }, { 0.600087177175954f, -0.79993460969569f }, { -0.560441030370991f, 0.828194331951567f }, { 0.958552181052623f, -0.284917033887514f }, { 0.6683586377581f, 0.743839183785136f }, { 0.709718808827001f, 0.704485068966819f }, { 0.695776987881928f, 0.718257880662615f }, { 0.154316110318401f, -0.988021527142096f }, { -0.725364342269412f, -0.688365143629501f }, { -0.999918869545931f, 0.0127379090116007f }, { 0.805508244111792f, 0.592584566680519f }, { -0.996506623245929f, 0.0835137702836865f }, { -0.73969279786535f, -0.67294469667732f }, { 0.695504007775371f, -0.718522216196824f }, { -0.999983227160896f, 0.00579183881678425f }, { -0.714924640549655f, 0.699201514825981f }, { -0.835103934916504f, -0.550092190352645f }, { 0.84959050330652f, 0.527442865807639f }, { -0.171610706906682f, 0.985164841676249f }, { 0.3561994988697f, 0.934409929851441f }, { -0.409182557485348f, -0.912452538299801f }, { 0.463529807851185f, 0.886081326534672f }, { -0.962925769084928f, -0.269766497608949f }, { 0.744285209959416f, 0.66786190656128f }, { -0.691027420259623f, 0.722828544296177f }, { 0.981612661017864f, 0.190883691627725f }, { 0.928340009081787f, 0.371732198683444f }, { -0.120562843572988f, 0.992705696946278f }, { 0.789437446513116f, -0.61383101749818f }, { 0.999774655712189f, -0.0212282310985648f }, { -0.902267580211854f, 0.431176545858708f }, { -0.912180652347305f, -0.4097883081339f }, { -0.770294485489921f, -0.637688329533965f }, { 0.20063205075057f, 0.979666667908846f }, { -0.982785937329741f, -0.184747940142514f }, { 0.857295252061123f, -0.514825068147866f }, { -0.6880675701609f, -0.725646621223357f }, { 0.703885918434739f, -0.710313039320893f }, { 0.80736694412922f, -0.590049673779628f }, { 0.501306939228223f, -0.865269526033149f }, { 0.994382489412099f, -0.105846420584718f }, { 0.496494368044017f, -0.868039942917705f }, { 0.077642279257408f, -0.996981281906393f }, { 0.951970808735996f, -0.30618879684687f }, { -0.761381916275718f, -0.648303615267041f }, { 0.925704511866975f, 0.378247480770363f }, { 0.307462004306155f, 0.951560358520699f }, { -0.722833511616144f, -0.6910222243059f }, { 0.365487416741135f, -0.930816280585966f }, { -0.452581511359919f, 0.891723037481466f }, { -0.696052038963733f, -0.717991336336609f }, { -0.731589205376628f, -0.681745725748533f }, { -0.584030912612065f, 0.811731416857521f }, { -0.622817071437575f, -0.782367493909303f }, { -0.250124556053565f, -0.968213667771224f }, { -0.972374793807189f, -0.233425063710878f }, { -0.970811073944879f, 0.239845489234194f }, { 0.972096169972212f, -0.234582685476477f }, { -0.56398693111627f, -0.825783713529185f }, { -0.697050386134155f, 0.717022146931478f }, { -0.0346220968223854f, -0.999400475490992f }, { -0.218763172462792f, -0.975777984161364f }, { -0.526228595935678f, 0.850343145335791f }, { 0.878475471267297f, 0.477787448957902f }, { -0.543258510315468f, 0.839565477476188f }, { -0.424638392098636f, 0.905363040970795f }, { -0.511241626148254f, -0.859437024855975f }, { 0.310536598007565f, -0.950561424263518f }, { 0.647207900842245f, 0.762313539881967f }, { -0.998374197564832f, 0.0569996634795082f }, { -0.384499699032222f, 0.923125116895933f }, { 0.793017652527103f, -0.609198656252953f }, { -0.108016962369769f, 0.994149051118799f }, { -0.931126682943364f, 0.364695901143526f }, { -0.801286360381044f, -0.598281011454734f }, { 0.875902620980454f, -0.482487925817394f }, { -0.731473336626206f, 0.681870044660216f }, { -0.315759562725525f, -0.948839237461956f }, { -0.0770741115938651f, -0.997025366438596f }, { -0.822418334736048f, 0.568883188967635f }, { -0.998852401248829f, -0.0478944727442276f }, { 0.996841343178929f, -0.0794187416749304f }, { -0.632437179039341f, 0.774611654036241f }, { 0.719989390873874f, 0.693985069745068f }, { 0.99256596306396f, -0.121707883750037f }, { 0.851153933233715f, -0.524916166583558f }, { 0.952866133004913f, 0.303391055524489f }, { 0.983070281370671f, 0.183228878416556f }, { 0.751614346163695f, 0.659602815822462f }, { 0.549915829679874f, 0.83522007894177f }, { 0.529779603383605f, 0.8481353499523f }, { -0.738299650910558f, -0.67447285005799f }, { -0.888225309084572f, -0.459408097775406f }, { 0.69138401830353f, 0.722487466489534f }, { 0.895582660271765f, -0.4448951546382f }, { -0.823764839572624f, -0.566931644101728f }, { 0.481527438369519f, 0.876431016165727f }, { -0.393245292146023f, 0.9194335974963f }, { 0.511430719572624f, 0.859324513252955f }, { 0.709782009015835f, 0.704421393540433f }, { -0.123429256704187f, -0.992353373848979f }, { -0.796333188996483f, -0.60485820826264f }, }; public static readonly float[,] LUT_Gradient3D = { { 0.969192790963703f, -0.204588387787502f, -0.137145636191962f }, { 0.0105050866706296f, 0.869235070511719f, -0.494287401565657f }, { -0.00713466534361336f, -0.0561560433951495f, -0.998396512083569f }, { -0.99998707996014f, 0.00085789886042815f, 0.00501038145637507f }, { -0.729044421579981f, -0.0724223391156089f, 0.680624151907743f }, { -0.769477416524206f, 0.638612501748049f, 0.00886442724220208f }, { -0.148489274637499f, -0.733777362959066f, 0.662964340614538f }, { 0.00192647521945516f, -0.688227670545063f, 0.725492220626345f }, { 0.307853961011481f, -0.888296843306306f, 0.340814695782903f }, { -0.136873983993337f, 0.99058218544213f, 0.0035279442294635f }, { 0.981422965662359f, 0.0873011939299262f, -0.170843390299155f }, { 0.977985182924792f, 0.0274298762917452f, 0.206863684261352f }, { -4.10904184278805E-08f, -0.984715746607902f, -0.174169165992265f }, { -0.00576047279073815f, -0.00207046110763061f, 0.999981264896512f }, { 0.385796494451913f, -0.382885124111844f, 0.839380751865608f }, { 0.196898025871543f, -0.533803208609833f, 0.822365674068256f }, { -0.953574229510659f, -0.197141111727736f, -0.227665480211439f }, { 0.958192898763756f, -0.00565943080050262f, 0.286067019423289f }, { -0.000021414243574488f, 0.308183457620683f, 0.951326944846192f }, { -0.00156590253858546f, -0.936777289401244f, -0.349922645753741f }, { 0.010162930999189f, 0.907036729301754f, 0.420928837846829f }, { -0.0468274165634939f, 0.74026530347444f, -0.670682095727837f }, { -0.958782958606567f, 0.0676203469753538f, -0.275975953591197f }, { 0.000771226398681087f, -0.963152702156633f, 0.268954043543163f }, { -0.939601847652347f, 0.341933173840782f, -0.0151681414637957f }, { 0.0836248033533964f, 0.431468628956066f, 0.898243683245743f }, { -0.97637082132863f, 0.118948680332271f, 0.180419596234078f }, { 0.103518422502263f, 0.000465187240855595f, -0.994627427634827f }, { -0.141353740004181f, 0.0778654829014707f, -0.98689213532146f }, { 0.0700630230682292f, 0.912644877864809f, -0.402703985212052f }, { 0.991874945122624f, -0.0502217417385342f, 0.116884001876814f }, { -0.707119760481927f, 0.700142261026601f, -0.0989063125414175f }, { 0.0976913606831578f, 0.99518571412564f, -0.00786081726752686f }, { 0.865756754070504f, 0.268594575188625f, 0.422282129577546f }, { 0.0124864728918991f, -0.922679395826772f, -0.385365826859963f }, { -0.0174011080646746f, -0.984212730893662f, 0.176132057800279f }, { 0.983085383617433f, 0.183144250425653f, 0.00114544916535278f }, { 0.84177325324929f, -0.000849099388075524f, 0.539830593005191f }, { -0.773202768542597f, 0.634158480426922f, -0.000707404184135718f }, { -0.399463762408861f, 0.520122522942901f, -0.754918050949683f }, { -0.0543404007696243f, 0.853240000077495f, -0.51867969221086f }, { 0.0787561128671418f, -0.0445112338899157f, -0.995899706167069f }, { -0.149110911377271f, -0.855893524471146f, -0.495189065788614f }, { 0.128579845943545f, 0.95447163354276f, 0.26916746456314f }, { -6.48712081276198E-06f, -0.417292224145094f, 0.908772358528778f }, { -0.18395289837094f, 0.967255425062472f, 0.174866445804071f }, { -0.0956465003848313f, -0.995413983868259f, -0.00165761384418054f }, { -0.493402767926647f, 0.252656257103973f, 0.83229713705415f }, { 0.941743815026262f, -0.00313821941824732f, 0.336316426061328f }, { -0.406002839825049f, -0.660621950516609f, -0.631458892208849f }, { -0.0151930656231186f, 0.000118750826499392f, 0.999884571665756f }, { 0.681786958463344f, -0.719431781259153f, 0.132606392695014f }, { 0.973323591185432f, -0.228922756390528f, 0.0153479134887209f }, { -0.810634856852843f, -0.585551171144037f, 0.000977152504195713f }, { -0.181398855060402f, -0.831693356111209f, 0.524767202465292f }, { -0.733900500867695f, 0.679256981569713f, 8.84021970721802E-05f }, { 0.271727663466327f, -0.889119678670303f, -0.368280156821335f }, { 0.298233653375395f, -0.0312311598898426f, -0.953981814630813f }, { -0.752318728102205f, -0.00392703305301813f, 0.658787605953604f }, { 0.00665991896444102f, -0.893539727653096f, 0.448934739784101f }, { -0.17274029679022f, 0.981849574845414f, 0.0783083791219516f }, { 0.740984319707759f, -1.24163939998686E-09f, 0.671522328703395f }, { -0.91345982474963f, 0.00101800775270491f, 0.40692764986984f }, { 0.166118424599226f, -0.966950978532905f, -0.193417874362556f }, { -0.371630916510155f, 0.92837704130171f, -0.00255559732836468f }, { 0.114876798169617f, 0.991537470331245f, 0.0604712011738797f }, { 0.42509283827761f, -0.861877415693766f, -0.276520160498508f }, { 0.0914177278602429f, 0.937282941514681f, 0.336368081985282f }, { -0.138897098096673f, 0.574329772420649f, -0.806754552916541f }, { 4.20730659972853E-05f, -0.973522779481066f, 0.228590017413966f }, { -0.19883302527571f, -0.769560727972852f, -0.606829229702725f }, { 0.0747279815185906f, 0.375429090417211f, 0.92383371168553f }, { 0.0360592551928224f, 0.999349653582228f, 1.40580077597545E-07f }, { -0.630789398266975f, 0.775912761477526f, 0.00800759703705387f }, { 0.999468273136104f, 0.0122075383077114f, -0.0302348640281232f }, { 0.0234858830298487f, 0.722121551769761f, -0.691367397096465f }, { 0.044647769484317f, -0.998966611124733f, -0.00850214902496602f }, { -0.155624581702642f, 0.0567240593672596f, -0.98618627584183f }, { -0.564856042306962f, 0.825189463979779f, 2.46592673497201E-06f }, { -0.00280893077197093f, -0.849678682544325f, 0.527293320968186f }, { 0.85760478967376f, 0.0912484314080345f, -0.506149926893406f }, { -0.983676972673489f, -0.138789081908023f, -0.11453036355067f }, { -0.995791780173427f, 0.0916344946719056f, 0.00136011957614869f }, { 0.0705163298667096f, 0.9883873876068f, -0.134602448870495f }, { 0.151288867759186f, -0.946777269461834f, -0.28412053871999f }, { -0.479182164834798f, 2.28582795501955E-06f, 0.877715473772117f }, { -0.920617168247744f, -0.0874211800038508f, -0.380554288918466f }, { 0.647008224881357f, -0.0116892424293656f, -0.76239341454875f }, { 0.00348600295131339f, 0.00264876419739902f, 0.999990415869897f }, { 0.293662611616922f, 0.774229458412962f, -0.560652313170918f }, { -0.0230822002633608f, -0.133701316157593f, -0.99075282996756f }, { 0.0891587773276397f, -0.70303221860981f, -0.705546888606285f }, { -0.716380181025389f, -0.675240051032385f, 0.175642562369752f }, { -0.110229513550145f, -0.0380431704478986f, 0.993177814655951f }, { 0.901899360101853f, -0.423583957873496f, -0.0845823556073773f }, { -0.188144760211676f, 0.981876973408649f, 0.0227850454193412f }, { -0.992971049488398f, -0.00105311622549315f, -0.118352802350111f }, { 0.974825103742426f, -0.22297088847484f, 2.51166485428216E-06f }, { 0.917736330268161f, 0.253456586759036f, -0.305810050087285f }, { 0.754361752313554f, 0.655909079393725f, -0.0268631013715986f }, { -0.00493426945610691f, 0.999852337890823f, -0.0164607229243032f }, { 0.172163344055272f, 0.977404359568319f, -0.122639719750783f }, { 0.20654798485596f, 0.00802290795582379f, 0.978403578744413f }, { -0.0189935909416278f, -0.956252765802595f, -0.291924461801387f }, { -0.298030174309119f, -0.101625749247146f, -0.949131298762838f }, { -0.525057139557522f, -0.851050276233871f, 0.00533174661105069f }, { 0.00362214069523366f, 0.401488407244411f, -0.915856942401558f }, { 0.7517944143271f, 0.19472711592481f, 0.629989292694866f }, { 0.501284099317453f, -0.0225214021165674f, 0.864989617404853f }, { -0.985033512468648f, 0.1680612553394f, -0.0382673982316817f }, { 0.00137633273570574f, -0.0442369494900767f, -0.999020118920542f }, { -0.724166817672979f, -0.688818418185576f, 0.033340770082758f }, { -0.0128146550963728f, -0.0397993929245446f, 0.99912551410601f }, { 0.802033957950016f, 0.595775400910827f, -0.0423462154693413f }, { -0.902335114745471f, -0.411652900762455f, -0.127801525777801f }, { 7.40750655087705E-05f, -0.890177016591854f, 0.455614830360591f }, { -0.0563694832642116f, 0.998393830705426f, -0.00567804243293261f }, { 0.804825783463094f, 0.0873894235068948f, -0.587042202002675f }, { 0.902405167679558f, 0.0887442050097385f, -0.421650778989461f }, { 0.0138828478418606f, -0.26021714739708f, 0.965450310858268f }, { -0.0235002961872274f, -0.1428517727679f, -0.989465061079056f }, { 0.543378228613975f, 0.00830368325812741f, 0.839446930730399f }, { -0.956960500295924f, 0.0113747804839107f, 0.289995198653906f }, { -0.00858337504492301f, -0.949962410388146f, -0.312246288244364f }, { -0.731827611403257f, 0.00140870300297461f, -0.681488343806152f }, { 0.844453636307317f, 0.498643416559842f, -0.195583228444764f }, { -0.997648624781726f, 0.000128342870118087f, -0.0685361583343983f }, { 0.00700544496566235f, -0.020878882722484f, 0.999757468587804f }, }; /// <summary> /// NoiseBasic Constructor. /// </summary> public NoiseGradient( ) { noiseType = NoiseType.Gradient; } /// <summary> /// Get a 2D gradient LUT index. /// </summary> /// <param name="xi">xi</param> /// <param name="yi">yi</param> /// <param name="x">x</param> /// <param name="y">y</param> /// <returns>2D look-up table result.</returns> float GetGradientCoord( int xi, int yi, float x, float y ) { float xs = x - ( float )xi; float ys = y - ( float )yi; int lutPos = GetLUTIndex( xi, yi ); return ( xs*LUT_Gradient2D[lutPos, 0] + ys*LUT_Gradient2D[lutPos, 1] ); } /// <summary> /// Get a 3D gradient LUT index. /// </summary> /// <param name="xi">xi</param> /// <param name="yi">yi</param> /// <param name="zi">zi</param> /// <param name="x">x</param> /// <param name="y">y</param> /// <param name="z">z</param> /// <returns>3D look-up table result.</returns> float GetGradientCoord( int xi, int yi, int zi, float x, float y, float z ) { float xs = x - ( float )xi; float ys = y - ( float )yi; float zs = z - ( float )zi; int lutPos = GetLUTIndex( xi, yi, zi ); return( xs*LUT_Gradient3D[lutPos, 0] + ys*LUT_Gradient3D[lutPos, 1] + zs*LUT_Gradient3D[lutPos, 2] ); } /// <summary> /// Get a 2D noise value. /// </summary> /// <param name="x">x</param> /// <param name="y">y</param> /// <returns>Result of 2D noise.</returns> float GetGradient( float x, float y ) { int x0 = FastFloor( x ); int y0 = FastFloor( y ); int x1 = x0 + 1; int y1 = y0 + 1; float xs = 0.0f; float ys = 0.0f; switch( interpolationType ) { case InterpolationType.Linear: xs = x - ( float )x0; ys = y - ( float )y0; break; case InterpolationType.Hermite: xs = InterpHermite( x - ( float )x0 ); ys = InterpHermite( y - ( float )y0 ); break; case InterpolationType.Quintic: xs = InterpQuintic( x - ( float )x0 ); ys = InterpQuintic( y - ( float )y0 ); break; } float xf0 = Lerp( GetGradientCoord( x0, y0, x, y ), GetGradientCoord( x1, y0, x, y ), xs ); float xf1 = Lerp( GetGradientCoord( x0, y1, x, y ), GetGradientCoord( x1, y1, x, y ), xs ); return( Lerp( xf0, xf1, ys )*1.4f ); } /// <summary> /// Get a 3D noise value. /// </summary> /// <param name="x">x</param> /// <param name="y">y</param> /// <param name="z">z</param> /// <returns>Result of 3D noise.</returns> private float GetGradient( float x, float y, float z ) { int x0 = FastFloor( x ); int y0 = FastFloor( y ); int z0 = FastFloor( z ); int x1 = x0 + 1; int y1 = y0 + 1; int z1 = z0 + 1; float xs = 0.0f; float ys = 0.0f; float zs = 0.0f; switch( interpolationType ) { case InterpolationType.Linear: xs = x - ( float )x0; ys = y - ( float )y0; zs = z - ( float )z0; break; case InterpolationType.Hermite: xs = InterpHermite( x - ( float )x0 ); ys = InterpHermite( y - ( float )y0 ); zs = InterpHermite( z - ( float )z0 ); break; case InterpolationType.Quintic: xs = InterpQuintic( x - ( float )x0 ); ys = InterpQuintic( y - ( float )y0 ); zs = InterpQuintic( z - ( float )z0 ); break; } float xf00 = Lerp( GetGradientCoord( x0, y0, z0, x, y, z ), GetGradientCoord( x1, y0, z0, x, y, z ), xs ); float xf10 = Lerp( GetGradientCoord( x0, y1, z0, x, y, z ), GetGradientCoord( x1, y1, z0, x, y, z ), xs ); float xf01 = Lerp( GetGradientCoord( x0, y0, z1, x, y, z ), GetGradientCoord( x1, y0, z1, x, y, z ), xs ); float xf11 = Lerp( GetGradientCoord( x0, y1, z1, x, y, z ), GetGradientCoord( x1, y1, z1, x, y, z ), xs ); float yf0 = Lerp( xf00, xf10, ys ); float yf1 = Lerp( xf01, xf11, ys ); return( Lerp( yf0, yf1, zs )*1.4f ); } /// <summary> /// 2D noise gradient type method. /// </summary> /// <param name="x">x</param> /// <param name="y">y</param> /// <returns>Noise value.</returns> public override float GetNoise( float x, float y ) { x*= frequency; y*= frequency; float sum = 0.0f; float max = 1.0f; float amp = 1.0f; uint i = 0; int seedPrev = seed; switch( fractalType ) { case FractalType.FBM: sum = GetGradient( x, y ); while( ++i < octaves ) { x*= lacunarity; y*= lacunarity; amp*= gain; max+= amp; ++seed; sum+= GetGradient( x, y )*amp; } break; case FractalType.Billow: sum = FastAbs( GetGradient( x, y ) )*2.0f - 1.0f; while( ++i < octaves ) { x*= lacunarity; y*= lacunarity; amp*= gain; max+= amp; ++seed; sum+= ( FastAbs( GetGradient( x, y ) )*2.0f - 1.0f )*amp; } break; case FractalType.RigidMulti: sum = 1.0f - FastAbs( GetGradient( x, y ) ); while( ++i < octaves ) { x*= lacunarity; y*= lacunarity; amp*= gain; ++seed; sum -= ( 1.0f - FastAbs( GetGradient( x, y ) ) )*amp; } break; } seed = seedPrev; return( sum/max ); } /// <summary> /// 3D noise gradient type method. /// </summary> /// <param name="x">x</param> /// <param name="y">y</param> /// <param name="z">z</param> /// <returns>Noise value.</returns> public override float GetNoise( float x, float y, float z ) { x*= frequency; y*= frequency; z*= frequency; x*= frequency; y*= frequency; float sum = 0.0f; float max = 1.0f; float amp = 1.0f; uint i = 0; int seedPrev = seed; switch( fractalType ) { case FractalType.FBM: sum = GetGradient( x, y, z ); while( ++i < octaves ) { x*= lacunarity; y*= lacunarity; z*= lacunarity; amp*= gain; max+= amp; ++seed; sum+= GetGradient( x, y, z )*amp; } break; case FractalType.Billow: sum = FastAbs( GetGradient( x, y ) )*2.0f - 1.0f; while( ++i < octaves ) { x*= lacunarity; y*= lacunarity; z*= lacunarity; amp*= gain; max+= amp; ++seed; sum+= ( FastAbs( GetGradient( x, y, z ) )*2.0f - 1.0f )*amp; } break; case FractalType.RigidMulti: sum = 1.0f - FastAbs( GetGradient( x, y, z ) ); while( ++i < octaves ) { x*= lacunarity; y*= lacunarity; z*= lacunarity; amp*= gain; ++seed; sum -= ( 1.0f - FastAbs( GetGradient( x, y, z ) ) )*amp; } break; } seed = seedPrev; return( sum/max ); } /// <summary> /// 4D noise gradient type method (not implemented, just returns 3D noise value). /// </summary> /// <param name="x">x</param> /// <param name="y">y</param> /// <param name="z">z</param> /// <param name="w">w</param> /// <returns>Noise value.</returns> public override float GetNoise( float x, float y, float z, float w ) { // No implementation; Return 3D noise value. // Toss in a console print here eventually. // Which means it'll probably never get done. return( GetNoise( x, y, z ) ); } }
// 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. //------------------------------------------------------------------------------ // <auto-generated> // This code was generated by google-apis-code-generator 1.5.1 // C# generator version: 1.27.1 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ /** * \brief * Google Cloud Speech API Version v1 * * \section ApiInfo API Version Information * <table> * <tr><th>API * <td><a href='https://cloud.google.com/speech/'>Google Cloud Speech API</a> * <tr><th>API Version<td>v1 * <tr><th>API Rev<td>20170705 (916) * <tr><th>API Docs * <td><a href='https://cloud.google.com/speech/'> * https://cloud.google.com/speech/</a> * <tr><th>Discovery Name<td>speech * </table> * * \section ForMoreInfo For More Information * * The complete API documentation for using Google Cloud Speech API can be found at * <a href='https://cloud.google.com/speech/'>https://cloud.google.com/speech/</a>. * * For more information about the Google APIs Client Library for .NET, see * <a href='https://developers.google.com/api-client-library/dotnet/get_started'> * https://developers.google.com/api-client-library/dotnet/get_started</a> */ namespace Google.Apis.Speech.v1 { /// <summary>The Speech Service.</summary> public class SpeechService : Google.Apis.Services.BaseClientService { /// <summary>The API version.</summary> public const string Version = "v1"; /// <summary>The discovery version used to generate this service.</summary> public static Google.Apis.Discovery.DiscoveryVersion DiscoveryVersionUsed = Google.Apis.Discovery.DiscoveryVersion.Version_1_0; /// <summary>Constructs a new service.</summary> public SpeechService() : this(new Google.Apis.Services.BaseClientService.Initializer()) {} /// <summary>Constructs a new service.</summary> /// <param name="initializer">The service initializer.</param> public SpeechService(Google.Apis.Services.BaseClientService.Initializer initializer) : base(initializer) { operations = new OperationsResource(this); speech = new SpeechResource(this); } /// <summary>Gets the service supported features.</summary> public override System.Collections.Generic.IList<string> Features { get { return new string[0]; } } /// <summary>Gets the service name.</summary> public override string Name { get { return "speech"; } } /// <summary>Gets the service base URI.</summary> public override string BaseUri { get { return "https://speech.googleapis.com/"; } } /// <summary>Gets the service base path.</summary> public override string BasePath { get { return ""; } } #if !NET40 /// <summary>Gets the batch base URI; <c>null</c> if unspecified.</summary> public override string BatchUri { get { return "https://speech.googleapis.com/batch"; } } /// <summary>Gets the batch base path; <c>null</c> if unspecified.</summary> public override string BatchPath { get { return "batch"; } } #endif /// <summary>Available OAuth 2.0 scopes for use with the Google Cloud Speech API.</summary> public class Scope { /// <summary>View and manage your data across Google Cloud Platform services</summary> public static string CloudPlatform = "https://www.googleapis.com/auth/cloud-platform"; } private readonly OperationsResource operations; /// <summary>Gets the Operations resource.</summary> public virtual OperationsResource Operations { get { return operations; } } private readonly SpeechResource speech; /// <summary>Gets the Speech resource.</summary> public virtual SpeechResource Speech { get { return speech; } } } ///<summary>A base abstract class for Speech requests.</summary> public abstract class SpeechBaseServiceRequest<TResponse> : Google.Apis.Requests.ClientServiceRequest<TResponse> { ///<summary>Constructs a new SpeechBaseServiceRequest instance.</summary> protected SpeechBaseServiceRequest(Google.Apis.Services.IClientService service) : base(service) { } /// <summary>V1 error format.</summary> [Google.Apis.Util.RequestParameterAttribute("$.xgafv", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<XgafvEnum> Xgafv { get; set; } /// <summary>V1 error format.</summary> public enum XgafvEnum { /// <summary>v1 error format</summary> [Google.Apis.Util.StringValueAttribute("1")] Value1, /// <summary>v2 error format</summary> [Google.Apis.Util.StringValueAttribute("2")] Value2, } /// <summary>OAuth access token.</summary> [Google.Apis.Util.RequestParameterAttribute("access_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string AccessToken { get; set; } /// <summary>Data format for response.</summary> /// [default: json] [Google.Apis.Util.RequestParameterAttribute("alt", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<AltEnum> Alt { get; set; } /// <summary>Data format for response.</summary> public enum AltEnum { /// <summary>Responses with Content-Type of application/json</summary> [Google.Apis.Util.StringValueAttribute("json")] Json, /// <summary>Media download with context-dependent Content-Type</summary> [Google.Apis.Util.StringValueAttribute("media")] Media, /// <summary>Responses with Content-Type of application/x-protobuf</summary> [Google.Apis.Util.StringValueAttribute("proto")] Proto, } /// <summary>OAuth bearer token.</summary> [Google.Apis.Util.RequestParameterAttribute("bearer_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string BearerToken { get; set; } /// <summary>JSONP</summary> [Google.Apis.Util.RequestParameterAttribute("callback", Google.Apis.Util.RequestParameterType.Query)] public virtual string Callback { get; set; } /// <summary>Selector specifying which fields to include in a partial response.</summary> [Google.Apis.Util.RequestParameterAttribute("fields", Google.Apis.Util.RequestParameterType.Query)] public virtual string Fields { get; set; } /// <summary>API key. Your API key identifies your project and provides you with API access, quota, and reports. /// Required unless you provide an OAuth 2.0 token.</summary> [Google.Apis.Util.RequestParameterAttribute("key", Google.Apis.Util.RequestParameterType.Query)] public virtual string Key { get; set; } /// <summary>OAuth 2.0 token for the current user.</summary> [Google.Apis.Util.RequestParameterAttribute("oauth_token", Google.Apis.Util.RequestParameterType.Query)] public virtual string OauthToken { get; set; } /// <summary>Pretty-print response.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("pp", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> Pp { get; set; } /// <summary>Returns response with indentations and line breaks.</summary> /// [default: true] [Google.Apis.Util.RequestParameterAttribute("prettyPrint", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<bool> PrettyPrint { get; set; } /// <summary>Available to use for quota purposes for server-side applications. Can be any arbitrary string /// assigned to a user, but should not exceed 40 characters.</summary> [Google.Apis.Util.RequestParameterAttribute("quotaUser", Google.Apis.Util.RequestParameterType.Query)] public virtual string QuotaUser { get; set; } /// <summary>Legacy upload protocol for media (e.g. "media", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("uploadType", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadType { get; set; } /// <summary>Upload protocol for media (e.g. "raw", "multipart").</summary> [Google.Apis.Util.RequestParameterAttribute("upload_protocol", Google.Apis.Util.RequestParameterType.Query)] public virtual string UploadProtocol { get; set; } /// <summary>Initializes Speech parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "$.xgafv", new Google.Apis.Discovery.Parameter { Name = "$.xgafv", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "access_token", new Google.Apis.Discovery.Parameter { Name = "access_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "alt", new Google.Apis.Discovery.Parameter { Name = "alt", IsRequired = false, ParameterType = "query", DefaultValue = "json", Pattern = null, }); RequestParameters.Add( "bearer_token", new Google.Apis.Discovery.Parameter { Name = "bearer_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "callback", new Google.Apis.Discovery.Parameter { Name = "callback", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "fields", new Google.Apis.Discovery.Parameter { Name = "fields", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "key", new Google.Apis.Discovery.Parameter { Name = "key", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "oauth_token", new Google.Apis.Discovery.Parameter { Name = "oauth_token", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pp", new Google.Apis.Discovery.Parameter { Name = "pp", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "prettyPrint", new Google.Apis.Discovery.Parameter { Name = "prettyPrint", IsRequired = false, ParameterType = "query", DefaultValue = "true", Pattern = null, }); RequestParameters.Add( "quotaUser", new Google.Apis.Discovery.Parameter { Name = "quotaUser", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "uploadType", new Google.Apis.Discovery.Parameter { Name = "uploadType", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "upload_protocol", new Google.Apis.Discovery.Parameter { Name = "upload_protocol", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } /// <summary>The "operations" collection of methods.</summary> public class OperationsResource { private const string Resource = "operations"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public OperationsResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to /// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether /// the cancellation succeeded or whether the operation completed despite cancellation. On successful /// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value /// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary> /// <param name="body">The body of the request.</param> /// <param name="name">The name of the operation resource to be cancelled.</param> public virtual CancelRequest Cancel(Google.Apis.Speech.v1.Data.CancelOperationRequest body, string name) { return new CancelRequest(service, body, name); } /// <summary>Starts asynchronous cancellation on a long-running operation. The server makes a best effort to /// cancel the operation, but success is not guaranteed. If the server doesn't support this method, it returns /// `google.rpc.Code.UNIMPLEMENTED`. Clients can use Operations.GetOperation or other methods to check whether /// the cancellation succeeded or whether the operation completed despite cancellation. On successful /// cancellation, the operation is not deleted; instead, it becomes an operation with an Operation.error value /// with a google.rpc.Status.code of 1, corresponding to `Code.CANCELLED`.</summary> public class CancelRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1.Data.Empty> { /// <summary>Constructs a new Cancel request.</summary> public CancelRequest(Google.Apis.Services.IClientService service, Google.Apis.Speech.v1.Data.CancelOperationRequest body, string name) : base(service) { Name = name; Body = body; InitParameters(); } /// <summary>The name of the operation resource to be cancelled.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Speech.v1.Data.CancelOperationRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "cancel"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/operations/{+name}:cancel"; } } /// <summary>Initializes Cancel parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^[^/]+$", }); } } /// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in /// the operation result. It does not cancel the operation. If the server doesn't support this method, it /// returns `google.rpc.Code.UNIMPLEMENTED`.</summary> /// <param name="name">The name of the operation resource to be deleted.</param> public virtual DeleteRequest Delete(string name) { return new DeleteRequest(service, name); } /// <summary>Deletes a long-running operation. This method indicates that the client is no longer interested in /// the operation result. It does not cancel the operation. If the server doesn't support this method, it /// returns `google.rpc.Code.UNIMPLEMENTED`.</summary> public class DeleteRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1.Data.Empty> { /// <summary>Constructs a new Delete request.</summary> public DeleteRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation resource to be deleted.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "delete"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "DELETE"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/operations/{+name}"; } } /// <summary>Initializes Delete parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^[^/]+$", }); } } /// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the /// operation result at intervals as recommended by the API service.</summary> /// <param name="name">The name of the operation resource.</param> public virtual GetRequest Get(string name) { return new GetRequest(service, name); } /// <summary>Gets the latest state of a long-running operation. Clients can use this method to poll the /// operation result at intervals as recommended by the API service.</summary> public class GetRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1.Data.Operation> { /// <summary>Constructs a new Get request.</summary> public GetRequest(Google.Apis.Services.IClientService service, string name) : base(service) { Name = name; InitParameters(); } /// <summary>The name of the operation resource.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Path)] public virtual string Name { get; private set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "get"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/operations/{+name}"; } } /// <summary>Initializes Get parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = true, ParameterType = "path", DefaultValue = null, Pattern = @"^[^/]+$", }); } } /// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this /// method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, /// such as `users/operations`. To override the binding, API services can add a binding such as /// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default /// name includes the operations collection id, however overriding users must ensure the name binding is the /// parent resource, without the operations collection id.</summary> public virtual ListRequest List() { return new ListRequest(service); } /// <summary>Lists operations that match the specified filter in the request. If the server doesn't support this /// method, it returns `UNIMPLEMENTED`. /// /// NOTE: the `name` binding allows API services to override the binding to use different resource name schemes, /// such as `users/operations`. To override the binding, API services can add a binding such as /// `"/v1/{name=users}/operations"` to their service configuration. For backwards compatibility, the default /// name includes the operations collection id, however overriding users must ensure the name binding is the /// parent resource, without the operations collection id.</summary> public class ListRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1.Data.ListOperationsResponse> { /// <summary>Constructs a new List request.</summary> public ListRequest(Google.Apis.Services.IClientService service) : base(service) { InitParameters(); } /// <summary>The standard list page token.</summary> [Google.Apis.Util.RequestParameterAttribute("pageToken", Google.Apis.Util.RequestParameterType.Query)] public virtual string PageToken { get; set; } /// <summary>The name of the operation's parent resource.</summary> [Google.Apis.Util.RequestParameterAttribute("name", Google.Apis.Util.RequestParameterType.Query)] public virtual string Name { get; set; } /// <summary>The standard list page size.</summary> [Google.Apis.Util.RequestParameterAttribute("pageSize", Google.Apis.Util.RequestParameterType.Query)] public virtual System.Nullable<int> PageSize { get; set; } /// <summary>The standard list filter.</summary> [Google.Apis.Util.RequestParameterAttribute("filter", Google.Apis.Util.RequestParameterType.Query)] public virtual string Filter { get; set; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "list"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "GET"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/operations"; } } /// <summary>Initializes List parameter list.</summary> protected override void InitParameters() { base.InitParameters(); RequestParameters.Add( "pageToken", new Google.Apis.Discovery.Parameter { Name = "pageToken", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "name", new Google.Apis.Discovery.Parameter { Name = "name", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "pageSize", new Google.Apis.Discovery.Parameter { Name = "pageSize", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); RequestParameters.Add( "filter", new Google.Apis.Discovery.Parameter { Name = "filter", IsRequired = false, ParameterType = "query", DefaultValue = null, Pattern = null, }); } } } /// <summary>The "speech" collection of methods.</summary> public class SpeechResource { private const string Resource = "speech"; /// <summary>The service which this resource belongs to.</summary> private readonly Google.Apis.Services.IClientService service; /// <summary>Constructs a new resource.</summary> public SpeechResource(Google.Apis.Services.IClientService service) { this.service = service; } /// <summary>Performs asynchronous speech recognition: receive results via the google.longrunning.Operations /// interface. Returns either an `Operation.error` or an `Operation.response` which contains a /// `LongRunningRecognizeResponse` message.</summary> /// <param name="body">The body of the request.</param> public virtual LongrunningrecognizeRequest Longrunningrecognize(Google.Apis.Speech.v1.Data.LongRunningRecognizeRequest body) { return new LongrunningrecognizeRequest(service, body); } /// <summary>Performs asynchronous speech recognition: receive results via the google.longrunning.Operations /// interface. Returns either an `Operation.error` or an `Operation.response` which contains a /// `LongRunningRecognizeResponse` message.</summary> public class LongrunningrecognizeRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1.Data.Operation> { /// <summary>Constructs a new Longrunningrecognize request.</summary> public LongrunningrecognizeRequest(Google.Apis.Services.IClientService service, Google.Apis.Speech.v1.Data.LongRunningRecognizeRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Speech.v1.Data.LongRunningRecognizeRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "longrunningrecognize"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/speech:longrunningrecognize"; } } /// <summary>Initializes Longrunningrecognize parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } /// <summary>Performs synchronous speech recognition: receive results after all audio has been sent and /// processed.</summary> /// <param name="body">The body of the request.</param> public virtual RecognizeRequest Recognize(Google.Apis.Speech.v1.Data.RecognizeRequest body) { return new RecognizeRequest(service, body); } /// <summary>Performs synchronous speech recognition: receive results after all audio has been sent and /// processed.</summary> public class RecognizeRequest : SpeechBaseServiceRequest<Google.Apis.Speech.v1.Data.RecognizeResponse> { /// <summary>Constructs a new Recognize request.</summary> public RecognizeRequest(Google.Apis.Services.IClientService service, Google.Apis.Speech.v1.Data.RecognizeRequest body) : base(service) { Body = body; InitParameters(); } /// <summary>Gets or sets the body of this request.</summary> Google.Apis.Speech.v1.Data.RecognizeRequest Body { get; set; } ///<summary>Returns the body of the request.</summary> protected override object GetBody() { return Body; } ///<summary>Gets the method name.</summary> public override string MethodName { get { return "recognize"; } } ///<summary>Gets the HTTP method.</summary> public override string HttpMethod { get { return "POST"; } } ///<summary>Gets the REST path.</summary> public override string RestPath { get { return "v1/speech:recognize"; } } /// <summary>Initializes Recognize parameter list.</summary> protected override void InitParameters() { base.InitParameters(); } } } } namespace Google.Apis.Speech.v1.Data { /// <summary>The request message for Operations.CancelOperation.</summary> public class CancelOperationRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A generic empty message that you can re-use to avoid defining duplicated empty messages in your APIs. A /// typical example is to use it as the request or the response type of an API method. For instance: /// /// service Foo { rpc Bar(google.protobuf.Empty) returns (google.protobuf.Empty); } /// /// The JSON representation for `Empty` is empty JSON object `{}`.</summary> public class Empty : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The response message for Operations.ListOperations.</summary> public class ListOperationsResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The standard List next-page token.</summary> [Newtonsoft.Json.JsonPropertyAttribute("nextPageToken")] public virtual string NextPageToken { get; set; } /// <summary>A list of operations that matches the specified filter in the request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("operations")] public virtual System.Collections.Generic.IList<Operation> Operations { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The top-level message sent by the client for the `LongRunningRecognize` method.</summary> public class LongRunningRecognizeRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>*Required* The audio data to be recognized.</summary> [Newtonsoft.Json.JsonPropertyAttribute("audio")] public virtual RecognitionAudio Audio { get; set; } /// <summary>*Required* Provides information to the recognizer that specifies how to process the /// request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("config")] public virtual RecognitionConfig Config { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>This resource represents a long-running operation that is the result of a network API call.</summary> public class Operation : Google.Apis.Requests.IDirectResponseSchema { /// <summary>If the value is `false`, it means the operation is still in progress. If true, the operation is /// completed, and either `error` or `response` is available.</summary> [Newtonsoft.Json.JsonPropertyAttribute("done")] public virtual System.Nullable<bool> Done { get; set; } /// <summary>The error result of the operation in case of failure or cancellation.</summary> [Newtonsoft.Json.JsonPropertyAttribute("error")] public virtual Status Error { get; set; } /// <summary>Service-specific metadata associated with the operation. It typically contains progress /// information and common metadata such as create time. Some services might not provide such metadata. Any /// method that returns a long-running operation should document the metadata type, if any.</summary> [Newtonsoft.Json.JsonPropertyAttribute("metadata")] public virtual System.Collections.Generic.IDictionary<string,object> Metadata { get; set; } /// <summary>The server-assigned name, which is only unique within the same service that originally returns it. /// If you use the default HTTP mapping, the `name` should have the format of /// `operations/some/unique/name`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("name")] public virtual string Name { get; set; } /// <summary>The normal response of the operation in case of success. If the original method returns no data on /// success, such as `Delete`, the response is `google.protobuf.Empty`. If the original method is standard /// `Get`/`Create`/`Update`, the response should be the resource. For other methods, the response should have /// the type `XxxResponse`, where `Xxx` is the original method name. For example, if the original method name /// is `TakeSnapshot()`, the inferred response type is `TakeSnapshotResponse`.</summary> [Newtonsoft.Json.JsonPropertyAttribute("response")] public virtual System.Collections.Generic.IDictionary<string,object> Response { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Contains audio data in the encoding specified in the `RecognitionConfig`. Either `content` or `uri` /// must be supplied. Supplying both or neither returns google.rpc.Code.INVALID_ARGUMENT. See [audio /// limits](https://cloud.google.com/speech/limits#content).</summary> public class RecognitionAudio : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The audio data bytes encoded as specified in `RecognitionConfig`. Note: as with all bytes fields, /// protobuffers use a pure binary representation, whereas JSON representations use base64.</summary> [Newtonsoft.Json.JsonPropertyAttribute("content")] public virtual string Content { get; set; } /// <summary>URI that points to a file that contains audio data bytes as specified in `RecognitionConfig`. /// Currently, only Google Cloud Storage URIs are supported, which must be specified in the following format: /// `gs://bucket_name/object_name` (other URI formats return google.rpc.Code.INVALID_ARGUMENT). For more /// information, see [Request URIs](https://cloud.google.com/storage/docs/reference-uris).</summary> [Newtonsoft.Json.JsonPropertyAttribute("uri")] public virtual string Uri { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Provides information to the recognizer that specifies how to process the request.</summary> public class RecognitionConfig : Google.Apis.Requests.IDirectResponseSchema { /// <summary>*Required* Encoding of audio data sent in all `RecognitionAudio` messages.</summary> [Newtonsoft.Json.JsonPropertyAttribute("encoding")] public virtual string Encoding { get; set; } /// <summary>*Required* The language of the supplied audio as a [BCP-47](https://www.rfc- /// editor.org/rfc/bcp/bcp47.txt) language tag. Example: "en-US". See [Language /// Support](https://cloud.google.com/speech/docs/languages) for a list of the currently supported language /// codes.</summary> [Newtonsoft.Json.JsonPropertyAttribute("languageCode")] public virtual string LanguageCode { get; set; } /// <summary>*Optional* Maximum number of recognition hypotheses to be returned. Specifically, the maximum /// number of `SpeechRecognitionAlternative` messages within each `SpeechRecognitionResult`. The server may /// return fewer than `max_alternatives`. Valid values are `0`-`30`. A value of `0` or `1` will return a maximum /// of one. If omitted, will return a maximum of one.</summary> [Newtonsoft.Json.JsonPropertyAttribute("maxAlternatives")] public virtual System.Nullable<int> MaxAlternatives { get; set; } /// <summary>*Optional* If set to `true`, the server will attempt to filter out profanities, replacing all but /// the initial character in each filtered word with asterisks, e.g. "f***". If set to `false` or omitted, /// profanities won't be filtered out.</summary> [Newtonsoft.Json.JsonPropertyAttribute("profanityFilter")] public virtual System.Nullable<bool> ProfanityFilter { get; set; } /// <summary>*Required* Sample rate in Hertz of the audio data sent in all `RecognitionAudio` messages. Valid /// values are: 8000-48000. 16000 is optimal. For best results, set the sampling rate of the audio source to /// 16000 Hz. If that's not possible, use the native sample rate of the audio source (instead of re- /// sampling).</summary> [Newtonsoft.Json.JsonPropertyAttribute("sampleRateHertz")] public virtual System.Nullable<int> SampleRateHertz { get; set; } /// <summary>*Optional* A means to provide context to assist the speech recognition.</summary> [Newtonsoft.Json.JsonPropertyAttribute("speechContexts")] public virtual System.Collections.Generic.IList<SpeechContext> SpeechContexts { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The top-level message sent by the client for the `Recognize` method.</summary> public class RecognizeRequest : Google.Apis.Requests.IDirectResponseSchema { /// <summary>*Required* The audio data to be recognized.</summary> [Newtonsoft.Json.JsonPropertyAttribute("audio")] public virtual RecognitionAudio Audio { get; set; } /// <summary>*Required* Provides information to the recognizer that specifies how to process the /// request.</summary> [Newtonsoft.Json.JsonPropertyAttribute("config")] public virtual RecognitionConfig Config { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The only message returned to the client by the `Recognize` method. It contains the result as zero or /// more sequential `SpeechRecognitionResult` messages.</summary> public class RecognizeResponse : Google.Apis.Requests.IDirectResponseSchema { /// <summary>*Output-only* Sequential list of transcription results corresponding to sequential portions of /// audio.</summary> [Newtonsoft.Json.JsonPropertyAttribute("results")] public virtual System.Collections.Generic.IList<SpeechRecognitionResult> Results { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Provides "hints" to the speech recognizer to favor specific words and phrases in the results.</summary> public class SpeechContext : Google.Apis.Requests.IDirectResponseSchema { /// <summary>*Optional* A list of strings containing words and phrases "hints" so that the speech recognition is /// more likely to recognize them. This can be used to improve the accuracy for specific words and phrases, for /// example, if specific commands are typically spoken by the user. This can also be used to add additional /// words to the vocabulary of the recognizer. See [usage /// limits](https://cloud.google.com/speech/limits#content).</summary> [Newtonsoft.Json.JsonPropertyAttribute("phrases")] public virtual System.Collections.Generic.IList<string> Phrases { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>Alternative hypotheses (a.k.a. n-best list).</summary> public class SpeechRecognitionAlternative : Google.Apis.Requests.IDirectResponseSchema { /// <summary>*Output-only* The confidence estimate between 0.0 and 1.0. A higher number indicates an estimated /// greater likelihood that the recognized words are correct. This field is typically provided only for the top /// hypothesis, and only for `is_final=true` results. Clients should not rely on the `confidence` field as it is /// not guaranteed to be accurate or consistent. The default of 0.0 is a sentinel value indicating `confidence` /// was not set.</summary> [Newtonsoft.Json.JsonPropertyAttribute("confidence")] public virtual System.Nullable<float> Confidence { get; set; } /// <summary>*Output-only* Transcript text representing the words that the user spoke.</summary> [Newtonsoft.Json.JsonPropertyAttribute("transcript")] public virtual string Transcript { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>A speech recognition result corresponding to a portion of the audio.</summary> public class SpeechRecognitionResult : Google.Apis.Requests.IDirectResponseSchema { /// <summary>*Output-only* May contain one or more recognition hypotheses (up to the maximum specified in /// `max_alternatives`). These alternatives are ordered in terms of accuracy, with the first/top alternative /// being the most probable, as ranked by the recognizer.</summary> [Newtonsoft.Json.JsonPropertyAttribute("alternatives")] public virtual System.Collections.Generic.IList<SpeechRecognitionAlternative> Alternatives { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } /// <summary>The `Status` type defines a logical error model that is suitable for different programming /// environments, including REST APIs and RPC APIs. It is used by [gRPC](https://github.com/grpc). The error model /// is designed to be: /// /// - Simple to use and understand for most users - Flexible enough to meet unexpected needs /// /// # Overview /// /// The `Status` message contains three pieces of data: error code, error message, and error details. The error code /// should be an enum value of google.rpc.Code, but it may accept additional error codes if needed. The error /// message should be a developer-facing English message that helps developers *understand* and *resolve* the error. /// If a localized user-facing error message is needed, put the localized message in the error details or localize /// it in the client. The optional error details may contain arbitrary information about the error. There is a /// predefined set of error detail types in the package `google.rpc` that can be used for common error conditions. /// /// # Language mapping /// /// The `Status` message is the logical representation of the error model, but it is not necessarily the actual wire /// format. When the `Status` message is exposed in different client libraries and different wire protocols, it can /// be mapped differently. For example, it will likely be mapped to some exceptions in Java, but more likely mapped /// to some error codes in C. /// /// # Other uses /// /// The error model and the `Status` message can be used in a variety of environments, either with or without APIs, /// to provide a consistent developer experience across different environments. /// /// Example uses of this error model include: /// /// - Partial errors. If a service needs to return partial errors to the client, it may embed the `Status` in the /// normal response to indicate the partial errors. /// /// - Workflow errors. A typical workflow has multiple steps. Each step may have a `Status` message for error /// reporting. /// /// - Batch operations. If a client uses batch request and batch response, the `Status` message should be used /// directly inside batch response, one for each error sub-response. /// /// - Asynchronous operations. If an API call embeds asynchronous operation results in its response, the status of /// those operations should be represented directly using the `Status` message. /// /// - Logging. If some API errors are stored in logs, the message `Status` could be used directly after any /// stripping needed for security/privacy reasons.</summary> public class Status : Google.Apis.Requests.IDirectResponseSchema { /// <summary>The status code, which should be an enum value of google.rpc.Code.</summary> [Newtonsoft.Json.JsonPropertyAttribute("code")] public virtual System.Nullable<int> Code { get; set; } /// <summary>A list of messages that carry the error details. There will be a common set of message types for /// APIs to use.</summary> [Newtonsoft.Json.JsonPropertyAttribute("details")] public virtual System.Collections.Generic.IList<System.Collections.Generic.IDictionary<string,object>> Details { get; set; } /// <summary>A developer-facing error message, which should be in English. Any user-facing error message should /// be localized and sent in the google.rpc.Status.details field, or localized by the client.</summary> [Newtonsoft.Json.JsonPropertyAttribute("message")] public virtual string Message { get; set; } /// <summary>The ETag of the item.</summary> public virtual string ETag { get; set; } } }
// ----------------------------------------------------------------------------- // qf4net Library // // Port of Samek's Quantum Framework to C#. The implementation takes the liberty // to depart from Miro Samek's code where the specifics of desktop systems // (compared to embedded systems) seem to warrant a different approach. // Please see accompanying documentation for details. // // Reference: // Practical Statecharts in C/C++; Quantum Programming for Embedded Systems // Author: Miro Samek, Ph.D. // http://www.quantum-leaps.com/book.htm // // ----------------------------------------------------------------------------- // // Copyright (C) 2003-2004, The qf4net Team // All rights reserved // Lead: Rainer Hessmer, Ph.D. (rainer@hessmer.org) // // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // - Redistributions of source code must retain the above copyright // notice, this list of conditions and the following disclaimer. // // - Neither the name of the qf4net-Team, nor the names of its contributors // may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL // THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, // INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) // HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, // STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED // OF THE POSSIBILITY OF SUCH DAMAGE. // ----------------------------------------------------------------------------- using System; using System.Threading; using qf4net; namespace qf4net { /// <summary> /// Thread-safe event queue holding <see cref="QEvent"/> instances. /// </summary> public class QEventQueue : IQEventQueue { private LinkedEventList m_EventList; /// <summary> /// Creates a new empty <see cref="QEventQueue"/> /// </summary> public QEventQueue() { m_EventList = new LinkedEventList(); } /// <summary> /// Returns <see langword="true"/> if the <see cref="QEventQueue"/> is empty /// </summary> public bool IsEmpty { get { lock(m_EventList) { return m_EventList.IsEmpty; } } } /// <summary> /// Number of events in the queue /// </summary> public int Count { get { lock(m_EventList) { return m_EventList.Count; } } } /// <summary> /// Inserts the <see paramref="qEvent"/> at the end of the queue (First In First Out). /// </summary> /// <param name="qEvent"></param> public void EnqueueFIFO(IQEvent qEvent) { lock(m_EventList) { m_EventList.InsertNewTail(qEvent); Monitor.Pulse(m_EventList); } } /// <summary> /// Inserts the <see paramref="qEvent"/> at the beginning of the queue (First In First Out). /// </summary> /// <param name="qEvent"></param> public void EnqueueLIFO(IQEvent qEvent) { lock(m_EventList) { m_EventList.InsertNewHead(qEvent); Monitor.Pulse(m_EventList); } } /// <summary> /// Dequeues the first <see cref="QEvent"/> in the <see cref="QEventQueue"/>. If the <see cref="QEventQueue"/> /// is currently empty then it blocks until the a new <see cref="QEvent"/> is put into the <see cref="QEventQueue"/>. /// </summary> /// <returns>The first <see cref="QEvent"/> in the <see cref="QEventQueue"/>.</returns> public IQEvent DeQueue() { lock(m_EventList) { if (m_EventList.IsEmpty) { // We wait for the next event to be put into the queue Monitor.Wait(m_EventList); } return m_EventList.RemoveHeadEvent(); } } /// <summary> /// Allows the caller to peek at the head of the <see cref="QEventQueue"/>. /// </summary> /// <returns>The <see cref="IQEvent"/> at the head of the <see cref="QEventQueue"/> if it exists; /// otherwise <see langword="null"/></returns> public IQEvent Peek() { lock (m_EventList) { if (m_EventList.IsEmpty) { return null; } else { return m_EventList.Head.QEvent; } } } #region Helper class LinkedEventList /// <summary> /// Simple single linked list for <see cref="QEvent"/> instances /// </summary> private class LinkedEventList { private EventNode m_HeadNode; private EventNode m_TailNode; private int m_Count; internal LinkedEventList() { m_HeadNode = null; m_TailNode = null; m_Count = 0; } internal int Count { get { return m_Count; } } internal bool IsEmpty { get { return (m_Count == 0); } } internal void InsertNewHead(IQEvent qEvent) { if (m_Count == 0) { // We create the first node in the linked list m_HeadNode = m_TailNode = new EventNode(qEvent, null); } else { EventNode newHead = new EventNode(qEvent, m_HeadNode); m_HeadNode = newHead; } m_Count++; } internal void InsertNewTail(IQEvent qEvent) { if (m_Count == 0) { // We create the first node in the linked list m_HeadNode = m_TailNode = new EventNode(qEvent, null); } else { EventNode newTail = new EventNode(qEvent, null); m_TailNode.NextNode = newTail; m_TailNode = newTail; } m_Count++; } internal EventNode Head { get { return m_HeadNode; } } internal EventNode Tail { get { return m_TailNode; } } /// <summary> /// Removes the current head node from the linked list and returns its associated <see cref="QEvent"/>. /// </summary> /// <returns></returns> internal IQEvent RemoveHeadEvent() { IQEvent qEvent = null; if (m_HeadNode != null) { qEvent = m_HeadNode.QEvent; m_HeadNode = m_HeadNode.NextNode; m_Count--; } return qEvent; } #region Helper class EventNode internal class EventNode { private IQEvent m_QEvent; private EventNode m_NextNode; internal EventNode(IQEvent qEvent, EventNode nextNode) { m_QEvent = qEvent; m_NextNode = nextNode; } internal EventNode NextNode { get { return m_NextNode; } set { m_NextNode = value; } } internal IQEvent QEvent { get { return m_QEvent; } set { m_QEvent = value; } } } #endregion } #endregion } }
using UnityEngine; using System.Collections; using System.Collections.Generic; public class GLexMaterial : GLexComponent { private static readonly Dictionary<string, string> ExportedTextureSlots = new Dictionary<string, string> { { "diffuse", "DIFFUSE_MAP" }, { "normal", "NORMAL_MAP" }, { "specular", "SPECULAR_MAP" }, { "emissive", "EMISSIVE_MAP" }, { "AO", "AO_MAP" }, { "light", "LIGHT_MAP" }, }; public class Uniform { public string Name; public string Type; public string Value; public Uniform(Material material, string uniform, string type) { Type = type; Name = uniform; if (Type.Equals("float")) { float f = material.GetFloat(Name); Value = f.ToString(GLexConfig.HighPrecision); } else if (Type.Equals("color") || Type.Equals("vector3")) { Color color = material.GetColor(Name); Value = "[ " + color.r.ToString(GLexConfig.MediumPrecision) + ", " + color.g.ToString(GLexConfig.MediumPrecision) + ", " + color.b.ToString(GLexConfig.MediumPrecision) + " ]"; } else if (Type.Equals("color32") || Type.Equals("vector4")) { Vector4 color32 = material.GetVector(Name); Value = "[ " + color32.x.ToString(GLexConfig.MediumPrecision) + ", " + color32.y.ToString(GLexConfig.MediumPrecision) + ", " + color32.z.ToString(GLexConfig.MediumPrecision) + ", " + color32.z.ToString(GLexConfig.MediumPrecision) + " ]"; } } } private static int mUniqueId; private static List<GLexMaterial> mMaterials; private static GLexMaterial[] mMaterialsAsArray; private Material mMaterial; private GLexMaterialSettings mMaterialSettings; private string mUniqueName; private List<GLexTexture> mTextures; private GLexShader mShader; public GLexMaterial(Material material, Component meshRenderer) { mMaterial = material; mMaterialSettings = meshRenderer.GetComponent<GLexMaterialSettings>(); mUniqueName = mMaterial.name; while (UniqueNameExists( mUniqueName )) { mUniqueName = mMaterial.name + (mUniqueId++).ToString(); } mMaterials.Add(this); AddTextures(); AddShader(); } public static void Reset() { mUniqueId = 0; mMaterials = new List<GLexMaterial>(); } new public static void PrepareForExport() { mMaterialsAsArray = mMaterials.ToArray(); } private void AddTextures() { mTextures = new List<GLexTexture>(); foreach (KeyValuePair<string, string> uniform in GLexConfig.TextureUniforms) { if (mMaterial.HasProperty(uniform.Value)) { Texture2D texture = mMaterial.GetTexture(uniform.Value) as Texture2D; mTextures.Add(GLexTexture.Get(texture)); } } } private void AddShader() { if (!GLexShader.Exists(mMaterial.shader)) { mShader = new GLexShader(mMaterial.shader); } else { mShader = GLexShader.Get(mMaterial.shader); } } // texture access methods private bool HasTextureOn(string uniform) { if (mMaterial.HasProperty(GLexConfig.GetTextureUniformFor(uniform))) { return mMaterial.GetTexture(GLexConfig.GetTextureUniformFor(uniform)) != null; } else { return false; } } private Texture2D GetTextureOn(string uniform) { if (HasTextureOn(uniform)) { return mMaterial.GetTexture(GLexConfig.GetTextureUniformFor(uniform)) as Texture2D; } else { Debug.LogError("GLexMaterial.GetTextureOn: " + uniform + " doesn't exist"); return null; } } private string GetTextureNameOn(string uniform) { if (HasTextureOn(uniform)) { return GetTextureOn(uniform).name; } else { Debug.LogError("GLexMaterial.GetTextureNameFor: " + uniform + " doesn't exist"); return "error"; } } private string GetTextureOffetFor(string uniform) { if (HasTextureOn(uniform)) { Vector2 offset = mMaterial.GetTextureOffset(uniform); return offset.x + ", " + offset.y; } else { Debug.LogError("GLexMaterial.GetOffetFor: " + uniform + " doesn't exist"); return "error"; } } private string GetTextureScalingFor(string uniform) { if (HasTextureOn(uniform)) { Vector2 scale = mMaterial.GetTextureScale(uniform); return scale.x + ", " + scale.y; } else { Debug.LogError("GLexMaterial.GetOffetFor: " + uniform + " doesn't exist"); return "error"; } } protected override string IdExtension { get { return GLexConfig.GetExtensionFor("material"); } } // template interface starts here public override string Name { get { return NamesUtil.CleanMaterial(mUniqueName); } } public string ShaderName { get { return NamesUtil.CleanShader(mMaterial.shader.name); } } public GLexMaterialSettings Settings { get { return mMaterialSettings; } } public KeyValuePair<string, string>[] BoundTextures { get { var lst = new List<KeyValuePair<string, string>>(); foreach (var kvp in ExportedTextureSlots) { var slotName = GLexConfig.GetTextureUniformFor(kvp.Key); var slotTexture = mMaterial.GetTexture(slotName); Debug.Log ("Texture: " + kvp.Key + " - " + slotName + " = " + slotTexture); if (slotTexture == null) { continue; } foreach (var tex in mTextures) { if (tex != null && tex.Texture == slotTexture) { lst.Add(new KeyValuePair<string, string>(kvp.Value, tex.Id)); break; } } } return lst.ToArray(); } } public Uniform[] Uniforms { get { List<Uniform> uniforms = new List<Uniform>(); foreach (KeyValuePair<string, string> uniformAndType in GLexConfig.Uniforms) { string uniform = uniformAndType.Key; string type = uniformAndType.Value; if (mMaterial.HasProperty(uniform)) { uniforms.Add(new Uniform(mMaterial, uniform, type)); } } return uniforms.ToArray(); } } public string RenderQueue { get { int renderQueue = GLexConfig.TransformRenderQueue(mMaterial.renderQueue); int renderQueueOffset = 0; if (mMaterialSettings != null) { renderQueueOffset = mMaterialSettings.renderQueueOffset; if (mMaterialSettings.renderQueueOverrideEnabled) { renderQueue = mMaterialSettings.renderQueue; } } return (renderQueue + renderQueueOffset).ToString(); } } public string Blending { get { return GetSetting("blending", GLexMaterialSettings.Blending.NoBlending); } } public string BlendEquation { get { return GetSetting("blendEquation", GLexMaterialSettings.BlendEquation.AddEquation); } } public string BlendSource { get { return GetSetting("blendSource", GLexMaterialSettings.BlendSrc.SrcAlphaFactor); } } public string BlendDestination { get { return GetSetting("blendDestination", GLexMaterialSettings.BlendDst.OneMinusSrcAlphaFactor); } } public string Culling { get { return GetSetting("culling", true); } } public string CullFace { get { return GetSetting("cullFace", GLexMaterialSettings.CullFace.Back); } } public string FrontFace { get { return GetSetting("frontFace", GLexMaterialSettings.FrontFace.CCW); } } public string DepthTest { get { return GetSetting("depthTest", true); } } public string DepthWrite { get { return GetSetting("depthWrite", true); } } public string OffsetEnabled { get { return GetSetting("offsetEnabled", false); } } public string OffsetFactor { get { return GetSetting("offsetFactor", 1f); } } public string OffsetUnits { get { return GetSetting("offsetUnits", 1f); } } public string IsWireframe { get { return GetSetting("wireframe", false); } } public string IsFlat { get { return GetSetting("flat", false); } } public string ZSortOffset { get { return GetSetting("zSortOffset", 0); } } private string GetSetting(string property, System.Object defaultValue) { if (mMaterialSettings != null) { return mMaterialSettings.GetSettingAsString(property); } if (defaultValue.GetType() == typeof(bool)) { return defaultValue.ToString().Equals("True") ? "true" : "false"; } else { return defaultValue.ToString(); } } public GLexTexture[] Textures { get { return mTextures.ToArray(); } } public GLexShader Shader { get { return mShader; } } // static public static GLexMaterial[] MaterialsAsArray { get { return mMaterialsAsArray; } } public static bool Exists(string name, Component meshRenderer) { foreach (GLexMaterial material in mMaterials) { if (NamesUtil.CleanMaterial(material.mMaterial.name) == name && HasSameMaterialSettings(material.mMaterialSettings, meshRenderer.GetComponent<GLexMaterialSettings>())) { return true; } } return false; } public static bool UniqueNameExists(string uniqueName) { foreach (GLexMaterial material in mMaterials) { if (material.mUniqueName == uniqueName) { return true; } } return false; } private static bool HasSameMaterialSettings(GLexMaterialSettings a, GLexMaterialSettings b) { bool aIsDefault = b == null ? true : b.IsDefault; bool bIsDefault = a == null ? true : a.IsDefault; if (aIsDefault && bIsDefault) { return true; } else if (b != null && a != null) { return b.Equals(a); } else { return false; } } public static GLexMaterial Get(Material material, Component meshRenderer) { string name = NamesUtil.CleanMaterial(material.name); if (Exists(name, meshRenderer)) { return Get(name, meshRenderer); } else { return new GLexMaterial(material, meshRenderer); } } public static GLexMaterial Get(string name, Component meshRenderer) { foreach (GLexMaterial material in mMaterials) { if (NamesUtil.CleanMaterial(material.mMaterial.name) == name && HasSameMaterialSettings(material.mMaterialSettings, meshRenderer.GetComponent<GLexMaterialSettings>())) { return material; } } Debug.LogError("GLexMaterial.Get: Trying to get " + name + " but it doesn't exists!"); return null; } }
// Copyright (c) 2015, Outercurve Foundation. // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // - Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // - Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // - Neither the name of the Outercurve Foundation nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR // ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES // (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON // ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS // SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Specialized; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; using WebsitePanel.Portal.ProviderControls; using WebsitePanel.Providers.HostedSolution; using WebsitePanel.EnterpriseServer; using WebsitePanel.EnterpriseServer.Base.HostedSolution; using WebsitePanel.Providers.OS; namespace WebsitePanel.Portal.ExchangeServer { public partial class EnterpriseStorageFolderGeneralSettings : WebsitePanelModuleBase { #region Constants private const int OneGb = 1024; #endregion protected void Page_Load(object sender, EventArgs e) { if (!IsPostBack) { if (!ES.Services.EnterpriseStorage.CheckUsersDomainExists(PanelRequest.ItemID)) { Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "enterprisestorage_folders", "ItemID=" + PanelRequest.ItemID)); } BindSettings(); OrganizationStatistics organizationStats = ES.Services.Organizations.GetOrganizationStatisticsByOrganization(PanelRequest.ItemID); if (organizationStats.AllocatedEnterpriseStorageSpace != -1) { rangeFolderSize.MaximumValue = Math.Round((organizationStats.AllocatedEnterpriseStorageSpace - (decimal)organizationStats.UsedEnterpriseStorageSpace) / OneGb + Utils.ParseDecimal(txtFolderSize.Text, 0), 2).ToString(); rangeFolderSize.ErrorMessage = string.Format("The quota you've entered exceeds the available quota for organization ({0}Gb)", rangeFolderSize.MaximumValue); } } } private void BindSettings() { try { // get settings SystemFile folder = ES.Services.EnterpriseStorage.GetEnterpriseFolder(PanelRequest.ItemID, PanelRequest.FolderID); litFolderName.Text = string.Format("{0}", folder.Name); // bind form txtFolderName.Text = folder.Name; lblFolderUrl.Text = folder.Url; if (folder.FRSMQuotaMB != -1) { txtFolderSize.Text = (Math.Round((decimal)folder.FRSMQuotaMB / OneGb, 2)).ToString(); } switch (folder.FsrmQuotaType) { case QuotaType.Hard: rbtnQuotaHard.Checked = true; break; case QuotaType.Soft: rbtnQuotaSoft.Checked = true; break; } var serviceId = ES.Services.EnterpriseStorage.GetEnterpriseStorageServiceId(PanelRequest.ItemID); StringDictionary settings = ConvertArrayToDictionary(ES.Services.Servers.GetServiceSettings(serviceId)); btnMigrate.Visible = folder.StorageSpaceFolderId == null && Utils.ParseBool(settings[EnterpriseStorage_Settings.UseStorageSpaces], false); if (folder.StorageSpaceFolderId != null) { uncPathRow.Visible = edaRow.Visible = abeRow.Visible = true; lblUncPath.Text = folder.UncPath; chkAbe.Checked = ES.Services.StorageSpaces.GetStorageSpaceFolderAbeStatus(folder.StorageSpaceFolderId.Value); chkEda.Checked = ES.Services.StorageSpaces.GetStorageSpaceFolderEncryptDataAccessStatus(folder.StorageSpaceFolderId.Value); } } catch (Exception ex) { messageBox.ShowErrorMessage("ENETERPRISE_STORAGE_GET_FOLDER_SETTINGS", ex); } } protected void btnSave_Click(object sender, EventArgs e) { if (!Page.IsValid) return; try { litFolderName.Text = txtFolderName.Text; SystemFile folder = new SystemFile { Name = PanelRequest.FolderID, Url = lblFolderUrl.Text }; if (!ES.Services.EnterpriseStorage.CheckEnterpriseStorageInitialization(PanelSecurity.PackageId, PanelRequest.ItemID)) { ES.Services.EnterpriseStorage.CreateEnterpriseStorage(PanelSecurity.PackageId, PanelRequest.ItemID); } //File is renaming if (PanelRequest.FolderID != txtFolderName.Text) { //check if filename is correct if (!EnterpriseStorageHelper.ValidateFolderName(txtFolderName.Text)) { messageBox.ShowErrorMessage("FILES_INCORRECT_FOLDER_NAME"); return; } folder = ES.Services.EnterpriseStorage.RenameEnterpriseFolder(PanelRequest.ItemID, PanelRequest.FolderID, txtFolderName.Text); if (folder == null) { messageBox.ShowErrorMessage("FOLDER_ALREADY_EXIST"); return; } } ES.Services.EnterpriseStorage.SetEnterpriseFolderGeneralSettings( PanelRequest.ItemID, folder, false, (int)(decimal.Parse(txtFolderSize.Text) * OneGb), rbtnQuotaSoft.Checked ? QuotaType.Soft : QuotaType.Hard); if (edaRow.Visible && abeRow.Visible) { ES.Services.EnterpriseStorage.SetEsFolderShareSettings(PanelRequest.ItemID, PanelRequest.FolderID, chkAbe.Checked, chkEda.Checked); } Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "enterprisestorage_folders", "ItemID=" + PanelRequest.ItemID)); } catch (Exception ex) { messageBox.ShowErrorMessage("ENTERPRISE_STORAGE_UPDATE_FOLDER_SETTINGS", ex); } } protected void btnMigrate_Click(object sender, EventArgs e) { try { var result = ES.Services.EnterpriseStorage.MoveToStorageSpace( PanelRequest.ItemID, PanelRequest.FolderID); messageBox.ShowMessage(result, "ES_MOVE_TO_STORAGE_SPACE", null); if (result.IsSuccess) { Response.Redirect(EditUrl("SpaceID", PanelSecurity.PackageId.ToString(), "enterprisestorage_folders", "ItemID=" + PanelRequest.ItemID)); } } catch (Exception ex) { messageBox.ShowErrorMessage("ENTERPRISE_STORAGE_MIGRATE_TO_STORAGE_SPACES", ex); } } private StringDictionary ConvertArrayToDictionary(string[] settings) { StringDictionary r = new StringDictionary(); foreach (string setting in settings) { int idx = setting.IndexOf('='); r.Add(setting.Substring(0, idx), setting.Substring(idx + 1)); } return r; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Diagnostics; using System.Dynamic.Utils; using System.Reflection; namespace System.Linq.Expressions { /// <summary> /// Represents an operation between an expression and a type. /// </summary> [DebuggerTypeProxy(typeof(Expression.TypeBinaryExpressionProxy))] public sealed class TypeBinaryExpression : Expression { private readonly Expression _expression; private readonly Type _typeOperand; private readonly ExpressionType _nodeKind; internal TypeBinaryExpression(Expression expression, Type typeOperand, ExpressionType nodeKind) { _expression = expression; _typeOperand = typeOperand; _nodeKind = nodeKind; } /// <summary> /// Gets the static type of the expression that this <see cref="Expression" /> represents. /// </summary> /// <returns>The <see cref="Type"/> that represents the static type of the expression.</returns> public sealed override Type Type { get { return typeof(bool); } } /// <summary> /// Returns the node type of this Expression. Extension nodes should return /// ExpressionType.Extension when overriding this method. /// </summary> /// <returns>The <see cref="ExpressionType"/> of the expression.</returns> public sealed override ExpressionType NodeType { get { return _nodeKind; } } /// <summary> /// Gets the expression operand of a type test operation. /// </summary> public Expression Expression { get { return _expression; } } /// <summary> /// Gets the type operand of a type test operation. /// </summary> public Type TypeOperand { get { return _typeOperand; } } #region Reduce TypeEqual internal Expression ReduceTypeEqual() { Type cType = Expression.Type; if (cType.GetTypeInfo().IsValueType) { if (cType.IsNullableType()) { // If the expression type is a a nullable type, it will match if // the value is not null and the type operand // either matches or is its type argument (T to its T?). if (cType.GetNonNullableType() != _typeOperand.GetNonNullableType()) { return Expression.Block(Expression, Expression.Constant(false)); } else { return Expression.NotEqual(Expression, Expression.Constant(null, Expression.Type)); } } else { // For other value types (including Void), we can // determine the result now return Expression.Block(Expression, Expression.Constant(cType == _typeOperand.GetNonNullableType())); } } Debug.Assert(TypeUtils.AreReferenceAssignable(typeof(object), Expression.Type), "Expecting reference types only after this point."); // Can check the value right now for constants. if (Expression.NodeType == ExpressionType.Constant) { return ReduceConstantTypeEqual(); } // expression is a ByVal parameter. Can safely reevaluate. var parameter = Expression as ParameterExpression; if (parameter != null && !parameter.IsByRef) { return ByValParameterTypeEqual(parameter); } // Create a temp so we only evaluate the left side once parameter = Expression.Parameter(typeof(object)); return Expression.Block( new[] { parameter }, Expression.Assign(parameter, Expression), ByValParameterTypeEqual(parameter) ); } // Helper that is used when re-eval of LHS is safe. private Expression ByValParameterTypeEqual(ParameterExpression value) { Expression getType = Expression.Call(value, typeof(object).GetMethod("GetType")); // In remoting scenarios, obj.GetType() can return an interface. // But JIT32's optimized "obj.GetType() == typeof(ISomething)" codegen, // causing it to always return false. // We workaround this optimization by generating different, less optimal IL // if TypeOperand is an interface. if (_typeOperand.GetTypeInfo().IsInterface) { var temp = Expression.Parameter(typeof(Type)); getType = Expression.Block(new[] { temp }, Expression.Assign(temp, getType), temp); } // We use reference equality when comparing to null for correctness // (don't invoke a user defined operator), and reference equality // on types for performance (so the JIT can optimize the IL). return Expression.AndAlso( Expression.ReferenceNotEqual(value, Expression.Constant(null)), Expression.ReferenceEqual( getType, Expression.Constant(_typeOperand.GetNonNullableType(), typeof(Type)) ) ); } private Expression ReduceConstantTypeEqual() { ConstantExpression ce = Expression as ConstantExpression; //TypeEqual(null, T) always returns false. if (ce.Value == null) { return Expression.Constant(false); } else { return Expression.Constant(_typeOperand.GetNonNullableType() == ce.Value.GetType()); } } #endregion /// <summary> /// Dispatches to the specific visit method for this node type. /// </summary> protected internal override Expression Accept(ExpressionVisitor visitor) { return visitor.VisitTypeBinary(this); } /// <summary> /// Creates a new expression that is like this one, but using the /// supplied children. If all of the children are the same, it will /// return this expression. /// </summary> /// <param name="expression">The <see cref="Expression" /> property of the result.</param> /// <returns>This expression if no children changed, or an expression with the updated children.</returns> public TypeBinaryExpression Update(Expression expression) { if (expression == Expression) { return this; } if (NodeType == ExpressionType.TypeIs) { return Expression.TypeIs(expression, TypeOperand); } return Expression.TypeEqual(expression, TypeOperand); } } public partial class Expression { /// <summary> /// Creates a <see cref="TypeBinaryExpression"/>. /// </summary> /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param> /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="TypeIs"/> and for which the <see cref="Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns> public static TypeBinaryExpression TypeIs(Expression expression, Type type) { RequiresCanRead(expression, nameof(expression)); ContractUtils.RequiresNotNull(type, nameof(type)); if (type.IsByRef) throw Error.TypeMustNotBeByRef(); return new TypeBinaryExpression(expression, type, ExpressionType.TypeIs); } /// <summary> /// Creates a <see cref="TypeBinaryExpression"/> that compares run-time type identity. /// </summary> /// <param name="expression">An <see cref="Expression"/> to set the <see cref="Expression"/> property equal to.</param> /// <param name="type">A <see cref="Type"/> to set the <see cref="TypeBinaryExpression.TypeOperand"/> property equal to.</param> /// <returns>A <see cref="TypeBinaryExpression"/> for which the <see cref="NodeType"/> property is equal to <see cref="TypeEqual"/> and for which the <see cref="Expression"/> and <see cref="TypeBinaryExpression.TypeOperand"/> properties are set to the specified values.</returns> public static TypeBinaryExpression TypeEqual(Expression expression, Type type) { RequiresCanRead(expression, nameof(expression)); ContractUtils.RequiresNotNull(type, nameof(type)); if (type.IsByRef) throw Error.TypeMustNotBeByRef(); return new TypeBinaryExpression(expression, type, ExpressionType.TypeEqual); } } }
using System; using System.Collections.Generic; using System.Text; using System.Data.SqlServerCe; using System.Windows.Forms; using System.Data; using System.IO; using System.Reflection; namespace Factotum { static class Globals { public static string dbName = "Factotum.sdf"; public static Guid? CurrentOutageID; // Beta versions show "Beta" and build date in main form title public static bool IsBeta = false; // The current database connection public static SqlCeConnection cnn; // Info about the current database public static int DatabaseVersion; public static int CompatibleDBVersion; public static bool IsMasterDB; public static bool IsNewDB; public static string dbPassword = "omigod"; private static string versionString; public static string VersionString { get { if (versionString == null) { Version version = System.Reflection.Assembly.GetExecutingAssembly().GetName().Version; versionString = version.Major + "." + version.Minor + (Globals.IsBeta ? " (Beta)":""); } return versionString; } } // Broadcast changes to the current database. public static event EventHandler DatabaseChanged; public static void OnDatabaseChanged() { // If we opened an outage database, the CurrentOutageID may change Globals.SetCurrentOutageID(); // Copy to a temporary variable to be thread-safe. EventHandler temp = DatabaseChanged; if (temp != null) temp(new object(), new EventArgs()); } // Broadcast changes to the current database. public static event EventHandler CurrentOutageChanged; public static void OnCurrentOutageChanged() { // Copy to a temporary variable to be thread-safe. EventHandler temp = CurrentOutageChanged; if (temp != null) temp(new object(), new EventArgs()); } // Initialize and open the connection to the database Factotum.sdf in the app dir public static void InitConnection() { if (!File.Exists(Globals.FactotumDatabaseFilePath)) { File.Copy(Globals.AppFolder + "\\" + dbName,Globals.FactotumDatabaseFilePath); } cnn = new SqlCeConnection(Globals.FactotumConnectionString()); cnn.Open(); } // This method should be called when the application loads and whenever a new // database file is opened public static void ReadDatabaseInfo() { if (Globals.cnn.State != ConnectionState.Open) cnn.Open(); SqlCeCommand cmd = cnn.CreateCommand(); cmd.CommandText = @"Select DatabaseVersion, SiteActivationKey, MasterRegCheckedOn, UnverifiedSessionCount, IsMasterDB, IsNewDB, IsInactivatedDB from Globals"; SqlCeDataReader rdr = cmd.ExecuteReader(); if (rdr.Read()) { DatabaseVersion = (int)rdr["DatabaseVersion"]; IsMasterDB = (bool)rdr["IsMasterDB"]; IsNewDB = (bool)rdr["IsNewDB"]; } rdr.Close(); // CompatibleDBVersion was added in Database Version 4 if (DatabaseVersion > 3) { if (Globals.cnn.State != ConnectionState.Open) cnn.Open(); cmd = cnn.CreateCommand(); cmd.CommandText = "Select CompatibleDBVersion from Globals"; rdr = cmd.ExecuteReader(); if (rdr.Read()) { CompatibleDBVersion = (int)rdr["CompatibleDBVersion"]; } rdr.Close(); } else CompatibleDBVersion = 3; // I Don't think it matters what this is set to. OnDatabaseChanged(); } public static void ConvertCurrentDbToMaster() { if (Globals.IsMasterDB) { MessageBox.Show("The current database is already a master database", "Factotum"); return; } // Update the isLocalChange and isUsedInOutage flags for the configuration tables. ChangeFinder.CleanUpOutageDatabase(Globals.cnn); // Delete all outage-specific data Amputate_outageSpecific(); // Set the dbtype to Master // Also, in case this is a new database, reset the IsNewDB flag. if (cnn.State != ConnectionState.Open) cnn.Open(); SqlCeCommand cmd; cmd = cnn.CreateCommand(); cmd.CommandText = @"Update Globals set IsMasterDB = 1, IsNewDB = 0"; int recordsAffected = cmd.ExecuteNonQuery(); ReadDatabaseInfo(); } public static void Amputate_outageSpecific() { SqlCeCommand cmd; cmd = cnn.CreateCommand(); cmd.CommandText = "Delete from GridCells"; if (cnn.State != ConnectionState.Open) cnn.Open(); cmd.ExecuteNonQuery(); cmd = cnn.CreateCommand(); cmd.CommandText = "Update Grids Set GrdParentID = NULL where GrdParentID IS NOT NULL"; if (cnn.State != ConnectionState.Open) cnn.Open(); cmd.ExecuteNonQuery(); cmd = cnn.CreateCommand(); cmd.CommandText = "Delete from Grids"; if (cnn.State != ConnectionState.Open) cnn.Open(); cmd.ExecuteNonQuery(); cmd = cnn.CreateCommand(); cmd.CommandText = "Delete from Graphics"; if (cnn.State != ConnectionState.Open) cnn.Open(); cmd.ExecuteNonQuery(); cmd = cnn.CreateCommand(); cmd.CommandText = "Delete from Dsets"; if (cnn.State != ConnectionState.Open) cnn.Open(); cmd.ExecuteNonQuery(); cmd = cnn.CreateCommand(); cmd.CommandText = "Delete from Inspections"; if (cnn.State != ConnectionState.Open) cnn.Open(); cmd.ExecuteNonQuery(); cmd = cnn.CreateCommand(); cmd.CommandText = "Delete from InspectedComponents"; if (cnn.State != ConnectionState.Open) cnn.Open(); cmd.ExecuteNonQuery(); cmd = cnn.CreateCommand(); cmd.CommandText = "Delete from Kits"; if (cnn.State != ConnectionState.Open) cnn.Open(); cmd.ExecuteNonQuery(); } // Check to see if the version stored in the DB matches that stored in the settings. public static bool IsDatabaseOk(out string message) { message = null; // If the app is expecting a database older than the compatible version of the current database, // we never want to try to open it. if (CompatibleDBVersion > UserSettings.sets.DbVersion) { message = "The version of the selected data file (" + DatabaseVersion + ") is not supported by this version of Factotum.\n" + "Please upgrade to the latest version of Factotum"; return false; } else if (DatabaseVersion < UserSettings.sets.DbVersion) { // Upgrade the database to the currently supported version DatabaseUpdater updater = new DatabaseUpdater(DatabaseVersion, Globals.cnn); updater.UpdateToCurrent(); } return true; } // This is the REAL connection string for the database. // Leave the application property set - it's being used by some designers public static string FactotumConnectionString() { return ConnectionStringForPath(AppDataFolder,dbName); } // Get a database connection string for a given database file path public static string ConnectionStringForPath(string path, string dbname) { return ConnectionStringForPath(path + "\\" + dbName); } public static string ConnectionStringForPath(string path) { return "Datasource = \"" + path + "\"; Password = \"" + dbPassword + "\";"; } // We need this function because the property cnn.ConnectionString removes the password public static string ConnectionStringFromConnection(SqlCeConnection cnn) { return cnn.ConnectionString + " Password = \"" + dbPassword + "\";"; } // The application folder public static string AppFolder = System.Windows.Forms.Application.StartupPath; // The application data folder // The App Domain property "DataDirectory" is set to this in AppMain upon startup, // so |DataDirectory| and Globals.AppDataFolder should always have the same value. // Some of the .NET designers want to use the |DataDirectory| property. public static string AppDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData) + "\\" + Application.CompanyName + "\\" + Application.ProductName; // This is used by various file copy operations public static string FactotumDatabaseFilePath = AppDataFolder + "\\Factotum.sdf"; // Set the Factotum data folder by default public static void SetDefaultFactotumDataFolder() { if (UserSettings.sets.FactotumDataFolder.Length == 0) { UserSettings.sets.FactotumDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Factotum"; UserSettings.Save(); } } // Set the Image folder by default public static void SetDefaultImageFolder() { if (UserSettings.sets.DefaultImageFolder.Length == 0) { UserSettings.sets.DefaultImageFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Factotum\\Images"; UserSettings.Save(); } } // Set the Meter Text files folder by default public static void SetDefaultMeterDataFolder() { if (UserSettings.sets.MeterDataFolder.Length == 0) { UserSettings.sets.MeterDataFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop) + "\\Factotum\\Meter text files"; UserSettings.Save(); } } // The Factotum Data Folder public static string FactotumDataFolder { get { return UserSettings.sets.FactotumDataFolder; } } // The Factotum Backup file path public static string FactotumBackupFilePath { get { return UserSettings.sets.FactotumDataFolder + "\\_Autobackup.sdf"; } } // The meter data folder inside the desktop factotum folder public static string MeterDataFolder { get { return UserSettings.sets.MeterDataFolder; } } // The image data folder inside the desktop factotum folder public static string ImageFolder { get { return UserSettings.sets.DefaultImageFolder; } } // Convert the string property CurrentOutageID to Guid public static void SetCurrentOutageID() { if (Globals.IsMasterDB) { // If a Master Database is loaded, we should use the property setting for the // current outage id if it's set to the id of a valid outage in the database. // Otherwise (if it's null or invalid) we should set it to the id of the // first outage in the database. // If there are no outages in the database (i.e. a new install, we set it to null) // Set the property to whatever we come up with... Guid? outageID; if (UserSettings.sets.CurrentOutageID.Length == 0) outageID = null; else outageID = new Guid(UserSettings.sets.CurrentOutageID); if (outageID != null) { // Check if it's valid SqlCeCommand cmd = cnn.CreateCommand(); cmd.CommandText = "Select OtgDBid from Outages where OtgDBid = @p0"; cmd.Parameters.Add("@p0", outageID); object result = DowUtils.Util.NullForDbNull(cmd.ExecuteScalar()); if (result == null) { // It was invalid, so try to get the first cmd = cnn.CreateCommand(); cmd.CommandText = "Select OtgDBid from Outages"; result = DowUtils.Util.NullForDbNull(cmd.ExecuteScalar()); if (result == null) outageID = null; else outageID = (Guid?)result; } // Else -- It was found, so outageID is ok as is. UserSettings.sets.CurrentOutageID = outageID.ToString(); UserSettings.Save(); CurrentOutageID = outageID; } else { CurrentOutageID = null; } } else { // An Outage database is loaded, so the current outage is simply the only outage // in the database. Don't worry about setting the property to this. SqlCeCommand cmd = cnn.CreateCommand(); cmd.CommandText = "Select OtgDBid from Outages"; object result = DowUtils.Util.NullForDbNull(cmd.ExecuteScalar()); if (result != null) CurrentOutageID = (Guid?)result; // An outage data file must contain an outage... unless it's a new db!!! else if (!Globals.IsNewDB) throw new Exception("Outage Data File must contain an Outage"); } OnCurrentOutageChanged(); } // Check to see if an instance of the form set to the selected ID already exists // If so, activate it. public static bool CanActivateForm(Form curForm, string formToOpen, Guid? ID) { Form[] siblings = curForm.MdiParent.MdiChildren; bool activated = false; foreach (Form sibling in siblings) { if (sibling.GetType().Name == formToOpen) { if ((sibling as IEntityEditForm).Entity.ID == ID) { sibling.Activate(); activated = true; break; } } } return activated; } // Check to see if an instance of the form set to the selected ID already exists // If so, activate it and send out a reference to the form. public static bool CanActivateForm(Form curForm, string formToOpen, Guid? ID, out Form frmFound) { frmFound = null; Form[] siblings = curForm.MdiParent.MdiChildren; bool activated = false; foreach (Form sibling in siblings) { if (sibling.GetType().Name == formToOpen) { if ((sibling as IEntityEditForm).Entity.ID == ID) { sibling.Activate(); activated = true; frmFound = sibling; break; } } } return activated; } // Check to see if an instance of the form set to the selected ID exists public static bool IsFormOpen(Form curForm, string testForm, Guid? ID) { Form[] siblings = curForm.MdiParent.MdiChildren; bool open = false; foreach (Form sibling in siblings) { if (sibling.GetType().Name == testForm) { if ((sibling as IEntityEditForm).Entity.ID == ID) { open = true; break; } } } return open; } // Delete the temp table if it exists. // For temp tables that shouldn't exist under normal circumstances. public static void DeleteTempTableIfExists(string tableName) { SqlCeCommand cmd; cmd = Globals.cnn.CreateCommand(); cmd.CommandText = @"SELECT Count(*) FROM Information_schema.tables WHERE table_name = '" + tableName + "'"; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); if ((int)cmd.ExecuteScalar() > 0) { cmd = Globals.cnn.CreateCommand(); cmd.CommandText = "drop table " + tableName; if (Globals.cnn.State != ConnectionState.Open) Globals.cnn.Open(); cmd.ExecuteNonQuery(); } } // Get a unique name for backing up the current database. public static string getUniqueBackupFileName(string folder) { string baseName; if (Globals.IsMasterDB) baseName = "Master"; // An outage database must have an outage so if we're not a master, CurrentOutageID should be set. else baseName = new EOutage(Globals.CurrentOutageID).OutageName; return getUniqueBackupFileName(folder, baseName, Globals.IsMasterDB, true, false); } public static string getUniqueBackupFileName(string folder, string inPrefix, bool forMaster, bool includeDate, bool isFinal) { string suffix = (forMaster ? ".mfac" : ".ofac"); DirectoryInfo di = new DirectoryInfo(folder); FileInfo[] dbFiles = di.GetFiles("*" + suffix); string base_prefix = inPrefix + (includeDate ? "_" + DateTime.Today.ToString("yyyy-MM-dd") : ""); base_prefix += (isFinal ? "_" + "Final" : ""); string prefix = base_prefix; int foundCount = 1; bool found = true; while (found) { found = false; foreach (FileInfo fi in dbFiles) { if (fi.Name.Substring(0, fi.Name.Length - fi.Extension.Length) == prefix) { prefix = base_prefix + "_" + foundCount; found = true; foundCount++; break; } } } return prefix + suffix; } } // Enums used by lots of view forms public enum FilterActiveStatus { ShowActive, ShowInactive } public enum FilterYesNoAll { ShowAll, Yes, No } }
#region Copyright (c) all rights reserved. // <copyright file="DittoEventSource.cs"> // THIS CODE AND INFORMATION ARE PROVIDED AS IS WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. // </copyright> #endregion namespace Ditto.Core { using System; using System.Collections; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Tracing; using System.Globalization; using System.Text; /// <summary> /// Ditto Event Source. /// </summary> [EventSource(Name = "Snape-Ditto")] public sealed partial class DittoEventSource : EventSource { /// <summary> /// The log instance. /// </summary> private static readonly Lazy<DittoEventSource> Instance = new Lazy<DittoEventSource>(() => new DittoEventSource()); /// <summary> /// Prevents a default instance of the <see cref="DittoEventSource"/> class from being created. /// </summary> private DittoEventSource() { } /// <summary> /// Gets the log instance. /// </summary> /// <value> /// The log instance. /// </value> public static DittoEventSource Log { get { return DittoEventSource.Instance.Value; } } /// <summary> /// Log an exception. /// </summary> /// <param name="ex">The exception.</param> public static void ExceptionRaised(Exception ex) { if (ex is AggregateException aggregateException) { foreach (var inner in aggregateException.Flatten().InnerExceptions) { ExceptionRaised(inner); } } else { if (ex != null) { var exceptionData = new StringBuilder(); foreach (DictionaryEntry entry in ex.Data) { exceptionData.AppendFormat(CultureInfo.CurrentCulture, "{0}={1}|", entry.Key, entry.Value); } Log.ExceptionRaised(ex.Message, ex.HelpLink, exceptionData.ToString()); } else { Log.UnknownExceptionRaised(); } } } /// <summary> /// Application startup log event. /// </summary> [Event(1, Message = "Application starting", Keywords = Keywords.Performance)] public void ApplicationStart() { this.WriteEvent(1); } /// <summary> /// Application complete log event. /// </summary> [Event(2, Message = "Application complete", Keywords = Keywords.Performance)] public void ApplicationComplete() { this.WriteEvent(2); } /// <summary> /// Exception thrown log event. /// </summary> /// <param name="message">The message.</param> /// <param name="helpLink">The help link.</param> /// <param name="data">The exception data.</param> [Event(3, Message = "Exception: {0} help='{1}' [{2}]", Keywords = Keywords.Diagnostic, Level = EventLevel.Error)] public void ExceptionRaised(string message, string helpLink, string data) { this.WriteEvent(3, message, helpLink, data); } /// <summary> /// Log a database query. /// </summary> /// <param name="database">The database.</param> /// <param name="query">The query.</param> /// <param name="operationId">The operation identifier.</param> [Event(10, Message = "Database {0} query {1} for operation {2}", Keywords = Keywords.Database)] public void DatabaseQuery(string database, string query, Guid operationId) { if (this.IsEnabled()) { this.WriteEvent(10, database, "\n" + query + "\n", operationId); } } /// <summary> /// Exception thrown log event. /// </summary> [Event(10001, Message = "Unknown exception", Keywords = Keywords.Diagnostic, Level = EventLevel.Error)] public void UnknownExceptionRaised() { this.WriteEvent(10001); } /// <summary> /// Parsing the script file. /// </summary> /// <param name="script">The script.</param> /// <param name="environment">The environment.</param> [Event(10002, Message = "Parsing script file '{0}' for '{1}'", Keywords = Keywords.Diagnostic, Level = EventLevel.Informational)] public void ParsingScriptFile(string script, string environment) { if (this.IsEnabled()) { this.WriteEvent(10002, script, environment); } } /// <summary> /// Bulk copy progress. /// </summary> /// <param name="target">The target.</param> /// <param name="rows">The row count copied.</param> [Event(10003, Message = "'{0}': '{1}' rows copied", Keywords = Keywords.Diagnostic, Level = EventLevel.Verbose)] public void BulkCopyProgress(string target, long rows) { if (this.IsEnabled()) { this.WriteEvent(10003, target, rows); } } /// <summary> /// Logs a program argument. /// </summary> /// <param name="name">The argument name.</param> /// <param name="value">The argument value.</param> [Event(10004, Message = "Arg '{0}': '{1}'", Keywords = Keywords.Diagnostic, Level = EventLevel.Informational)] public void ProgramArgument(string name, string value) { if (this.IsEnabled()) { this.WriteEvent(10004, name, value); } } /// <summary> /// Logs the fact that the special target connection was generated. /// </summary> /// <param name="connectionString">The connection string.</param> [Event(10005, Message = "Target connection generated to '{0}'", Keywords = Keywords.Diagnostic, Level = EventLevel.Informational)] public void TargetConnectionGenerated(string connectionString) { if (this.IsEnabled()) { this.WriteEvent(10005, connectionString); } } /// <summary> /// Logs the fact that a file is being read. /// </summary> /// <param name="fileName">The file name.</param> [Event(10006, Message = "Loading file '{0}'", Keywords = Keywords.Source, Level = EventLevel.Informational)] public void LoadingFile(string fileName) { if (this.IsEnabled()) { this.WriteEvent(10006, fileName); } } /// <summary> /// Keywords constants. /// </summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Standard event source pattern [JS]")] public static class Keywords { /// <summary> /// The database keyword. /// </summary> public const EventKeywords Database = (EventKeywords)1; /// <summary> /// The diagnostic keyword. /// </summary> public const EventKeywords Diagnostic = (EventKeywords)2; /// <summary> /// The performance keyword. /// </summary> public const EventKeywords Performance = (EventKeywords)4; /// <summary> /// The source keyword. /// </summary> public const EventKeywords Source = (EventKeywords)8; } /// <summary> /// Tasks constants. /// </summary> [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible", Justification = "Standard event source pattern [JS]")] public static class Tasks { /// <summary> /// An extract task. /// </summary> public const EventTask Extract = (EventTask)1; /// <summary> /// A load task. /// </summary> public const EventTask Load = (EventTask)2; /// <summary> /// A database query task. /// </summary> public const EventTask DataQuery = (EventTask)4; } } }
/// 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. /// /// UserResource /// </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; using Twilio.Types; namespace Twilio.Rest.FrontlineApi.V1 { public class UserResource : Resource { public sealed class StateTypeEnum : StringEnum { private StateTypeEnum(string value) : base(value) {} public StateTypeEnum() {} public static implicit operator StateTypeEnum(string value) { return new StateTypeEnum(value); } public static readonly StateTypeEnum Active = new StateTypeEnum("active"); public static readonly StateTypeEnum Deactivated = new StateTypeEnum("deactivated"); } private static Request BuildFetchRequest(FetchUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Get, Rest.Domain.FrontlineApi, "/v1/Users/" + options.PathSid + "", queryParams: options.GetParams(), headerParams: null ); } /// <summary> /// Fetch a frontline user /// </summary> /// <param name="options"> Fetch User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static UserResource Fetch(FetchUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildFetchRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Fetch a frontline user /// </summary> /// <param name="options"> Fetch User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<UserResource> FetchAsync(FetchUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildFetchRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Fetch a frontline user /// </summary> /// <param name="pathSid"> The SID of the User resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static UserResource Fetch(string pathSid, ITwilioRestClient client = null) { var options = new FetchUserOptions(pathSid); return Fetch(options, client); } #if !NET35 /// <summary> /// Fetch a frontline user /// </summary> /// <param name="pathSid"> The SID of the User resource to fetch </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<UserResource> FetchAsync(string pathSid, ITwilioRestClient client = null) { var options = new FetchUserOptions(pathSid); return await FetchAsync(options, client); } #endif private static Request BuildUpdateRequest(UpdateUserOptions options, ITwilioRestClient client) { return new Request( HttpMethod.Post, Rest.Domain.FrontlineApi, "/v1/Users/" + options.PathSid + "", postParams: options.GetParams(), headerParams: null ); } /// <summary> /// Update an existing frontline user /// </summary> /// <param name="options"> Update User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static UserResource Update(UpdateUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = client.Request(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #if !NET35 /// <summary> /// Update an existing frontline user /// </summary> /// <param name="options"> Update User parameters </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<UserResource> UpdateAsync(UpdateUserOptions options, ITwilioRestClient client = null) { client = client ?? TwilioClient.GetRestClient(); var response = await client.RequestAsync(BuildUpdateRequest(options, client)); return FromJson(response.Content); } #endif /// <summary> /// Update an existing frontline user /// </summary> /// <param name="pathSid"> The SID of the User resource to update </param> /// <param name="friendlyName"> The string that you assigned to describe the User </param> /// <param name="avatar"> The avatar URL which will be shown in Frontline application </param> /// <param name="state"> Current state of this user </param> /// <param name="isAvailable"> Whether the User is available for new conversations </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> A single instance of User </returns> public static UserResource Update(string pathSid, string friendlyName = null, string avatar = null, UserResource.StateTypeEnum state = null, bool? isAvailable = null, ITwilioRestClient client = null) { var options = new UpdateUserOptions(pathSid){FriendlyName = friendlyName, Avatar = avatar, State = state, IsAvailable = isAvailable}; return Update(options, client); } #if !NET35 /// <summary> /// Update an existing frontline user /// </summary> /// <param name="pathSid"> The SID of the User resource to update </param> /// <param name="friendlyName"> The string that you assigned to describe the User </param> /// <param name="avatar"> The avatar URL which will be shown in Frontline application </param> /// <param name="state"> Current state of this user </param> /// <param name="isAvailable"> Whether the User is available for new conversations </param> /// <param name="client"> Client to make requests to Twilio </param> /// <returns> Task that resolves to A single instance of User </returns> public static async System.Threading.Tasks.Task<UserResource> UpdateAsync(string pathSid, string friendlyName = null, string avatar = null, UserResource.StateTypeEnum state = null, bool? isAvailable = null, ITwilioRestClient client = null) { var options = new UpdateUserOptions(pathSid){FriendlyName = friendlyName, Avatar = avatar, State = state, IsAvailable = isAvailable}; return await UpdateAsync(options, client); } #endif /// <summary> /// Converts a JSON string into a UserResource object /// </summary> /// <param name="json"> Raw JSON string </param> /// <returns> UserResource object represented by the provided JSON </returns> public static UserResource FromJson(string json) { // Convert all checked exceptions to Runtime try { return JsonConvert.DeserializeObject<UserResource>(json); } catch (JsonException e) { throw new ApiException(e.Message, e); } } /// <summary> /// The unique string that identifies the resource /// </summary> [JsonProperty("sid")] public string Sid { get; private set; } /// <summary> /// The string that identifies the resource's User /// </summary> [JsonProperty("identity")] public string Identity { get; private set; } /// <summary> /// The string that you assigned to describe the User /// </summary> [JsonProperty("friendly_name")] public string FriendlyName { get; private set; } /// <summary> /// The avatar URL which will be shown in Frontline application /// </summary> [JsonProperty("avatar")] public string Avatar { get; private set; } /// <summary> /// Current state of this user /// </summary> [JsonProperty("state")] [JsonConverter(typeof(StringEnumConverter))] public UserResource.StateTypeEnum State { get; private set; } /// <summary> /// Whether the User is available for new conversations /// </summary> [JsonProperty("is_available")] public bool? IsAvailable { get; private set; } /// <summary> /// An absolute URL for this user. /// </summary> [JsonProperty("url")] public Uri Url { get; private set; } private UserResource() { } } }
/* Copyright (c) Citrix Systems Inc. * All rights reserved. * * Redistribution and use in source and binary forms, * with or without modification, are permitted provided * that the following conditions are met: * * * 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. * * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND * CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, * INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR * CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, * SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, * BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, * WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING * NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE * OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF * SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using XenAdmin.Dialogs; using XenAdmin.Network; using XenAPI; using XenAdmin.Core; using System.Text.RegularExpressions; namespace XenAdmin.Dialogs { public partial class NameAndConnectionPrompt : XenDialogBase { public NameAndConnectionPrompt() { InitializeComponent(); } protected override void OnLoad(EventArgs e) { base.OnLoad(e); foreach (IXenConnection connection in ConnectionsManager.XenConnections) { if (!connection.IsConnected) continue; Pool pool = Helpers.GetPool(connection); if (pool != null) { comboBox.Items.Add(pool); continue; } Host master = Helpers.GetMaster(connection); if (master != null) { comboBox.Items.Add(master); continue; } } comboBox.Sorted = true; if (comboBox.Items.Count > 0) { // check to see if the user is readonly on connections, try and choose a sensible default int nonReadOnlyIndex = -1; for (int i = 0; i < comboBox.Items.Count; i++) { IXenObject xo = comboBox.Items[i] as IXenObject; if (xo != null && (xo.Connection.Session.IsLocalSuperuser || !XenAdmin.Commands.CrossConnectionCommand.IsReadOnly(xo.Connection))) { nonReadOnlyIndex = i; break; } } if (nonReadOnlyIndex == -1) comboBox.SelectedIndex = 0; else comboBox.SelectedIndex = nonReadOnlyIndex; } UpdateOK(); } public String PromptedName { get { return textBox.Text; } set { textBox.Text = value; } } public string OKText { set { okButton.Text = value; } } private string helpID = null; internal string HelpID { set { helpID = value; } } internal override string HelpName { get { return helpID ?? base.HelpName; } } public IXenConnection Connection { get { IXenObject o = comboBox.SelectedItem as IXenObject; if (o == null) return null; return o.Connection; } } private void textBox1_TextChanged(object sender, EventArgs e) { UpdateOK(); } private Regex invalid_folder = new Regex("^[ /]+$"); private void UpdateOK() { okButton.Enabled = !String.IsNullOrEmpty(textBox.Text.Trim()) && !invalid_folder.IsMatch(textBox.Text); } private const int PADDING = 1; private void comboBox_DrawItem(object sender, DrawItemEventArgs e) { ComboBox comboBox = sender as ComboBox; if (comboBox == null) return; if (e.Index < 0 || e.Index >= comboBox.Items.Count) return; Graphics g = e.Graphics; e.DrawBackground(); IXenObject o = comboBox.Items[e.Index] as IXenObject; if (o == null) return; Image image = Images.GetImage16For(o); Rectangle bounds = e.Bounds; if (image != null) g.DrawImage(image, bounds.X + PADDING, bounds.Y + PADDING, bounds.Height - 2 * PADDING, bounds.Height - 2 * PADDING); String name = Helpers.GetName(o).Ellipsise(50); e.DrawFocusRectangle(); if (name != null) using (Brush brush = new SolidBrush(e.ForeColor)) g.DrawString(name, Program.DefaultFont, brush, new Rectangle(bounds.X + bounds.Height, bounds.Y, bounds.Width - bounds.Height, bounds.Height)); } private void okButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.OK; Close(); } private void cancelButton_Click(object sender, EventArgs e) { DialogResult = DialogResult.Cancel; Close(); } } }
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using NodaTime; using QuantConnect.Configuration; using QuantConnect.Data; using QuantConnect.Data.Market; using QuantConnect.Interfaces; using QuantConnect.Logging; using QuantConnect.Packets; using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using QuantConnect.Util; using HistoryRequest = QuantConnect.Data.HistoryRequest; using Timer = System.Timers.Timer; using System.Threading; namespace QuantConnect.ToolBox.IQFeed { /// <summary> /// IQFeedDataQueueHandler is an implementation of IDataQueueHandler and IHistoryProvider /// </summary> public class IQFeedDataQueueHandler : HistoryProviderBase, IDataQueueHandler, IDataQueueUniverseProvider { private bool _isConnected; private readonly HashSet<Symbol> _symbols; private readonly Dictionary<Symbol, Symbol> _underlyings; private readonly object _sync = new object(); private IQFeedDataQueueUniverseProvider _symbolUniverse; //Socket connections: private AdminPort _adminPort; private Level1Port _level1Port; private HistoryPort _historyPort; private readonly IDataAggregator _aggregator = Composer.Instance.GetExportedValueByTypeName<IDataAggregator>( Config.Get("data-aggregator", "QuantConnect.Lean.Engine.DataFeeds.AggregationManager")); private readonly EventBasedDataQueueHandlerSubscriptionManager _subscriptionManager; /// <summary> /// Gets the total number of data points emitted by this history provider /// </summary> public override int DataPointCount { get; } = 0; /// <summary> /// IQFeedDataQueueHandler is an implementation of IDataQueueHandler: /// </summary> public IQFeedDataQueueHandler() { _symbols = new HashSet<Symbol>(); _underlyings = new Dictionary<Symbol, Symbol>(); _subscriptionManager = new EventBasedDataQueueHandlerSubscriptionManager(); _subscriptionManager.SubscribeImpl += (s, t) => { Subscribe(s); return true; }; _subscriptionManager.UnsubscribeImpl += (s, t) => { Unsubscribe(s); return true; }; if (!IsConnected) Connect(); } /// <summary> /// Subscribe to the specified configuration /// </summary> /// <param name="dataConfig">defines the parameters to subscribe to a data feed</param> /// <param name="newDataAvailableHandler">handler to be fired on new data available</param> /// <returns>The new enumerator for this subscription request</returns> public IEnumerator<BaseData> Subscribe(SubscriptionDataConfig dataConfig, EventHandler newDataAvailableHandler) { if (!CanSubscribe(dataConfig.Symbol)) { return null; } var enumerator = _aggregator.Add(dataConfig, newDataAvailableHandler); _subscriptionManager.Subscribe(dataConfig); return enumerator; } /// <summary> /// Adds the specified symbols to the subscription: new IQLevel1WatchItem("IBM", true) /// </summary> /// <param name="symbols">The symbols to be added keyed by SecurityType</param> public void Subscribe(IEnumerable<Symbol> symbols) { try { foreach (var symbol in symbols) { lock (_sync) { Log.Trace("IQFeed.Subscribe(): Subscribe Request: " + symbol.ToString()); if (_symbols.Add(symbol)) { // processing canonical option symbol to subscribe to underlying prices var subscribeSymbol = symbol; if (symbol.ID.SecurityType == SecurityType.Option && symbol.IsCanonical()) { subscribeSymbol = symbol.Underlying; _underlyings.Add(subscribeSymbol, symbol); } if (symbol.ID.SecurityType == SecurityType.Future && symbol.IsCanonical()) { // do nothing for now. Later might add continuous contract symbol. return; } var ticker = _symbolUniverse.GetBrokerageSymbol(subscribeSymbol); if (!string.IsNullOrEmpty(ticker)) { _level1Port.Subscribe(ticker); Log.Trace("IQFeed.Subscribe(): Subscribe Processed: {0} ({1})", symbol.Value, ticker); } else { Log.Error("IQFeed.Subscribe(): Symbol {0} was not found in IQFeed symbol universe", symbol.Value); } } } } } catch (Exception err) { Log.Error("IQFeed.Subscribe(): " + err.Message); } } /// <summary> /// Removes the specified configuration /// </summary> /// <param name="dataConfig">Subscription config to be removed</param> public void Unsubscribe(SubscriptionDataConfig dataConfig) { _subscriptionManager.Unsubscribe(dataConfig); _aggregator.Remove(dataConfig); } /// <summary> /// Sets the job we're subscribing for /// </summary> /// <param name="job">Job we're subscribing for</param> public void SetJob(LiveNodePacket job) { } /// <summary> /// Removes the specified symbols to the subscription /// </summary> /// <param name="symbols">The symbols to be removed keyed by SecurityType</param> public void Unsubscribe(IEnumerable<Symbol> symbols) { try { foreach (var symbol in symbols) { lock (_sync) { Log.Trace("IQFeed.Unsubscribe(): " + symbol.ToString()); _symbols.Remove(symbol); var subscribeSymbol = symbol; if (symbol.ID.SecurityType == SecurityType.Option && symbol.ID.StrikePrice == 0.0m) { subscribeSymbol = symbol.Underlying; _underlyings.Remove(subscribeSymbol); } var ticker = _symbolUniverse.GetBrokerageSymbol(subscribeSymbol); if (_level1Port.Contains(ticker)) { _level1Port.Unsubscribe(ticker); } } } } catch (Exception err) { Log.Error("IQFeed.Unsubscribe(): " + err.Message); } } /// <summary> /// Initializes this history provider to work for the specified job /// </summary> /// <param name="parameters">The initialization parameters</param> public override void Initialize(HistoryProviderInitializeParameters parameters) { } /// <summary> /// Gets the history for the requested securities /// </summary> /// <param name="requests">The historical data requests</param> /// <param name="sliceTimeZone">The time zone used when time stamping the slice instances</param> /// <returns>An enumerable of the slices of data covering the span specified in each request</returns> public override IEnumerable<Slice> GetHistory(IEnumerable<HistoryRequest> requests, DateTimeZone sliceTimeZone) { foreach (var request in requests) { foreach (var slice in _historyPort.ProcessHistoryRequests(request)) { yield return slice; } } } /// <summary> /// Indicates the connection is live. /// </summary> public bool IsConnected => _isConnected; /// <summary> /// Connect to the IQ Feed using supplied username and password information. /// </summary> private void Connect() { try { // Launch the IQ Feed Application: Log.Trace("IQFeed.Connect(): Launching client..."); if (OS.IsWindows) { // IQConnect is only supported on Windows var connector = new IQConnect(Config.Get("iqfeed-productName"), "1.0"); connector.Launch(); } // Initialise one admin port Log.Trace("IQFeed.Connect(): Connecting to admin..."); _adminPort = new AdminPort(); _adminPort.Connect(); _adminPort.SetAutoconnect(); _adminPort.SetClientStats(false); _adminPort.SetClientName("Admin"); _adminPort.DisconnectedEvent += AdminPortOnDisconnectedEvent; _adminPort.ConnectedEvent += AdminPortOnConnectedEvent; _symbolUniverse = new IQFeedDataQueueUniverseProvider(); Log.Trace("IQFeed.Connect(): Connecting to L1 data..."); _level1Port = new Level1Port(_aggregator, _symbolUniverse); _level1Port.Connect(); _level1Port.SetClientName("Level1"); Log.Trace("IQFeed.Connect(): Connecting to Historical data..."); _historyPort = new HistoryPort(_symbolUniverse); _historyPort.Connect(); _historyPort.SetClientName("History"); _isConnected = true; } catch (Exception err) { Log.Error("IQFeed.Connect(): Error Connecting to IQFeed: " + err.Message); _isConnected = false; } } /// <summary> /// Disconnect from all ports we're subscribed to: /// </summary> /// <remarks> /// Not being used. IQ automatically disconnect on killing LEAN /// </remarks> private void Disconnect() { if (_adminPort != null) _adminPort.Disconnect(); if (_level1Port != null) _level1Port.Disconnect(); _isConnected = false; Log.Trace("IQFeed.Disconnect(): Disconnected"); } /// <summary> /// Returns true if this data provide can handle the specified symbol /// </summary> /// <param name="symbol">The symbol to be handled</param> /// <returns>True if this data provider can get data for the symbol, false otherwise</returns> private static bool CanSubscribe(Symbol symbol) { var market = symbol.ID.Market; var securityType = symbol.ID.SecurityType; if (symbol.Value.IndexOfInvariant("universe", true) != -1) return false; return (securityType == SecurityType.Equity && market == Market.USA) || (securityType == SecurityType.Forex && market == Market.FXCM) || (securityType == SecurityType.Option && market == Market.USA) || (securityType == SecurityType.Future); } /// <summary> /// Admin port is connected. /// </summary> private void AdminPortOnConnectedEvent(object sender, ConnectedEventArgs connectedEventArgs) { _isConnected = true; Log.Error("IQFeed.AdminPortOnConnectedEvent(): ADMIN PORT CONNECTED!"); } /// <summary> /// Admin port disconnected from the IQFeed server. /// </summary> private void AdminPortOnDisconnectedEvent(object sender, DisconnectedEventArgs disconnectedEventArgs) { _isConnected = false; Log.Error("IQFeed.AdminPortOnDisconnectedEvent(): ADMIN PORT DISCONNECTED!"); } /// <summary> /// Method returns a collection of Symbols that are available at the data source. /// </summary> /// <param name="lookupName">String representing the name to lookup</param> /// <param name="securityType">Expected security type of the returned symbols (if any)</param> /// <param name="includeExpired">Include expired contracts</param> /// <param name="securityCurrency">Expected security currency(if any)</param> /// <param name="securityExchange">Expected security exchange name(if any)</param> /// <returns>Symbol results</returns> public IEnumerable<Symbol> LookupSymbols(string lookupName, SecurityType securityType, bool includeExpired, string securityCurrency = null, string securityExchange = null) { return _symbolUniverse.LookupSymbols(lookupName, securityType, includeExpired, securityCurrency, securityExchange); } /// <summary> /// Method returns a collection of Symbols that are available at the data source. /// </summary> /// <param name="symbol">Symbol to lookup</param> /// <param name="includeExpired">Include expired contracts</param> /// <param name="securityCurrency">Expected security currency(if any)</param> /// <returns>Symbol results</returns> public IEnumerable<Symbol> LookupSymbols(Symbol symbol, bool includeExpired, string securityCurrency) { return LookupSymbols(symbol.ID.Symbol, symbol.SecurityType, includeExpired, securityCurrency); } /// <summary> /// Returns whether selection can take place or not. /// </summary> /// <returns>True if selection can take place</returns> public bool CanPerformSelection() { return _symbolUniverse.CanPerformSelection(); } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { _symbolUniverse.DisposeSafely(); } } /// <summary> /// Admin class type /// </summary> public class AdminPort : IQAdminSocketClient { public AdminPort() : base(80) { } } /// <summary> /// Level 1 Data Request: /// </summary> public class Level1Port : IQLevel1Client { private int count; private DateTime start; private DateTime _feedTime; private Stopwatch _stopwatch = new Stopwatch(); private readonly Timer _timer; private readonly ConcurrentDictionary<string, double> _prices; private readonly ConcurrentDictionary<string, int> _openInterests; private readonly IQFeedDataQueueUniverseProvider _symbolUniverse; private readonly IDataAggregator _aggregator; private int _dataQueueCount; public DateTime FeedTime { get { if (_feedTime == new DateTime()) return DateTime.Now; return _feedTime.AddMilliseconds(_stopwatch.ElapsedMilliseconds); } set { _feedTime = value; _stopwatch = Stopwatch.StartNew(); } } public Level1Port(IDataAggregator aggregator, IQFeedDataQueueUniverseProvider symbolUniverse) : base(80) { start = DateTime.Now; _prices = new ConcurrentDictionary<string, double>(); _openInterests = new ConcurrentDictionary<string, int>(); _aggregator = aggregator; _symbolUniverse = symbolUniverse; Level1SummaryUpdateEvent += OnLevel1SummaryUpdateEvent; Level1TimerEvent += OnLevel1TimerEvent; Level1ServerDisconnectedEvent += OnLevel1ServerDisconnected; Level1ServerReconnectFailed += OnLevel1ServerReconnectFailed; Level1UnknownEvent += OnLevel1UnknownEvent; Level1FundamentalEvent += OnLevel1FundamentalEvent; _timer = new Timer(1000); _timer.Enabled = false; _timer.AutoReset = true; _timer.Elapsed += (sender, args) => { var ticksPerSecond = count / (DateTime.Now - start).TotalSeconds; int dataQueueCount = Interlocked.Exchange(ref _dataQueueCount, 0); if (ticksPerSecond > 1000 || dataQueueCount > 31) { Log.Trace($"IQFeed.OnSecond(): Ticks/sec: {ticksPerSecond.ToStringInvariant("0000.00")} " + $"Engine.Ticks.Count: {dataQueueCount} CPU%: {OS.CpuUsage.ToStringInvariant("0.0") + "%"}" ); } count = 0; start = DateTime.Now; }; _timer.Enabled = true; } private Symbol GetLeanSymbol(string ticker) { return _symbolUniverse.GetLeanSymbol(ticker, SecurityType.Base, null); } private void OnLevel1FundamentalEvent(object sender, Level1FundamentalEventArgs e) { // handle split data, they're only valid today, they'll show up around 4:45am EST if (e.SplitDate1.Date == DateTime.Today && DateTime.Now.TimeOfDay.TotalHours <= 8) // they will always be sent premarket { // get the last price, if it doesn't exist then we'll just issue the split claiming the price was zero // this should (ideally) never happen, but sending this without the price is much better then not sending // it at all double referencePrice; _prices.TryGetValue(e.Symbol, out referencePrice); var symbol = GetLeanSymbol(e.Symbol); var split = new Split(symbol, FeedTime, (decimal)referencePrice, (decimal)e.SplitFactor1, SplitType.SplitOccurred); Emit(split); } } /// <summary> /// Handle a new price update packet: /// </summary> private void OnLevel1SummaryUpdateEvent(object sender, Level1SummaryUpdateEventArgs e) { // if ticker is not found, unsubscribe if (e.NotFound) Unsubscribe(e.Symbol); // only update if we have a value if (e.Last == 0) return; // only accept trade and B/A updates if (e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.ExtendedTrade && e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.Trade && e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.Bid && e.TypeOfUpdate != Level1SummaryUpdateEventArgs.UpdateType.Ask) return; count++; var time = FeedTime; var last = (decimal)(e.TypeOfUpdate == Level1SummaryUpdateEventArgs.UpdateType.ExtendedTrade ? e.ExtendedTradingLast : e.Last); var symbol = GetLeanSymbol(e.Symbol); TickType tradeType; switch (symbol.ID.SecurityType) { // the feed time is in NYC/EDT, convert it into EST case SecurityType.Forex: time = FeedTime.ConvertTo(TimeZones.NewYork, TimeZones.EasternStandard); // TypeOfUpdate always equal to UpdateType.Trade for FXCM, but the message contains B/A and last data tradeType = TickType.Quote; break; // for all other asset classes we leave it as is (NYC/EDT) default: time = FeedTime; tradeType = e.TypeOfUpdate == Level1SummaryUpdateEventArgs.UpdateType.Bid || e.TypeOfUpdate == Level1SummaryUpdateEventArgs.UpdateType.Ask ? TickType.Quote : TickType.Trade; break; } var tick = new Tick(time, symbol, last, (decimal)e.Bid, (decimal)e.Ask) { AskSize = e.AskSize, BidSize = e.BidSize, Quantity = e.IncrementalVolume, TickType = tradeType, DataType = MarketDataType.Tick }; Emit(tick); _prices[e.Symbol] = e.Last; if (symbol.ID.SecurityType == SecurityType.Option || symbol.ID.SecurityType == SecurityType.Future) { if (!_openInterests.ContainsKey(e.Symbol) || _openInterests[e.Symbol] != e.OpenInterest) { var oi = new OpenInterest(time, symbol, e.OpenInterest); Emit(oi); _openInterests[e.Symbol] = e.OpenInterest; } } } private void Emit(BaseData tick) { _aggregator.Update(tick); Interlocked.Increment(ref _dataQueueCount); } /// <summary> /// Set the interal clock time. /// </summary> private void OnLevel1TimerEvent(object sender, Level1TimerEventArgs e) { //If there was a bad tick and the time didn't set right, skip setting it here and just use our millisecond timer to set the time from last time it was set. if (e.DateTimeStamp != DateTime.MinValue) { FeedTime = e.DateTimeStamp; } } /// <summary> /// Server has disconnected, reconnect. /// </summary> private void OnLevel1ServerDisconnected(object sender, Level1ServerDisconnectedArgs e) { Log.Error("IQFeed.OnLevel1ServerDisconnected(): LEVEL 1 PORT DISCONNECTED! " + e.TextLine); } /// <summary> /// Server has disconnected, reconnect. /// </summary> private void OnLevel1ServerReconnectFailed(object sender, Level1ServerReconnectFailedArgs e) { Log.Error("IQFeed.OnLevel1ServerReconnectFailed(): LEVEL 1 PORT DISCONNECT! " + e.TextLine); } /// <summary> /// Got a message we don't know about, log it for posterity. /// </summary> private void OnLevel1UnknownEvent(object sender, Level1TextLineEventArgs e) { Log.Error("IQFeed.OnUnknownEvent(): " + e.TextLine); } } // this type is expected to be used for exactly one job at a time public class HistoryPort : IQLookupHistorySymbolClient { private bool _inProgress; private ConcurrentDictionary<string, HistoryRequest> _requestDataByRequestId; private ConcurrentDictionary<string, List<BaseData>> _currentRequest; private readonly string DataDirectory = Config.Get("data-directory", "../../../Data"); private readonly double MaxHistoryRequestMinutes = Config.GetDouble("max-history-minutes", 5); private readonly IQFeedDataQueueUniverseProvider _symbolUniverse; /// <summary> /// ... /// </summary> public HistoryPort(IQFeedDataQueueUniverseProvider symbolUniverse) : base(80) { _symbolUniverse = symbolUniverse; _requestDataByRequestId = new ConcurrentDictionary<string, HistoryRequest>(); _currentRequest = new ConcurrentDictionary<string, List<BaseData>>(); } /// <summary> /// ... /// </summary> public HistoryPort(IQFeedDataQueueUniverseProvider symbolUniverse, int maxDataPoints, int dataPointsPerSend) : this(symbolUniverse) { MaxDataPoints = maxDataPoints; DataPointsPerSend = dataPointsPerSend; } /// <summary> /// Populate request data /// </summary> public IEnumerable<Slice> ProcessHistoryRequests(HistoryRequest request) { // skipping universe and canonical symbols if (!CanHandle(request.Symbol) || (request.Symbol.ID.SecurityType == SecurityType.Option && request.Symbol.IsCanonical()) || (request.Symbol.ID.SecurityType == SecurityType.Future && request.Symbol.IsCanonical())) { yield break; } // Set this process status _inProgress = true; var ticker = _symbolUniverse.GetBrokerageSymbol(request.Symbol); var start = request.StartTimeUtc.ConvertFromUtc(TimeZones.NewYork); DateTime? end = request.EndTimeUtc.ConvertFromUtc(TimeZones.NewYork); // if we're within a minute of now, don't set the end time if (request.EndTimeUtc >= DateTime.UtcNow.AddMinutes(-1)) { end = null; } Log.Trace($"HistoryPort.ProcessHistoryJob(): Submitting request: {request.Symbol.SecurityType.ToStringInvariant()}-{ticker}: " + $"{request.Resolution.ToStringInvariant()} {start.ToStringInvariant()}->{(end ?? DateTime.UtcNow.AddMinutes(-1)).ToStringInvariant()}" ); int id; var reqid = string.Empty; switch (request.Resolution) { case Resolution.Tick: id = RequestTickData(ticker, start, end, true); reqid = CreateRequestID(LookupType.REQ_HST_TCK, id); break; case Resolution.Daily: id = RequestDailyData(ticker, start, end, true); reqid = CreateRequestID(LookupType.REQ_HST_DWM, id); break; default: var interval = new Interval(GetPeriodType(request.Resolution), 1); id = RequestIntervalData(ticker, interval, start, end, true); reqid = CreateRequestID(LookupType.REQ_HST_INT, id); break; } _requestDataByRequestId[reqid] = request; while (_inProgress) { continue; } // After all data arrive, we pass it to the algorithm through memory and write to a file foreach (var key in _currentRequest.Keys) { List<BaseData> tradeBars; if (_currentRequest.TryRemove(key, out tradeBars)) { foreach (var tradeBar in tradeBars) { // Returns IEnumerable<Slice> object yield return new Slice(tradeBar.EndTime, new[] { tradeBar }); } } } } /// <summary> /// Returns true if this data provide can handle the specified symbol /// </summary> /// <param name="symbol">The symbol to be handled</param> /// <returns>True if this data provider can get data for the symbol, false otherwise</returns> private bool CanHandle(Symbol symbol) { var market = symbol.ID.Market; var securityType = symbol.ID.SecurityType; return (securityType == SecurityType.Equity && market == Market.USA) || (securityType == SecurityType.Forex && market == Market.FXCM) || (securityType == SecurityType.Option && market == Market.USA) || (securityType == SecurityType.Future && IQFeedDataQueueUniverseProvider.FuturesExchanges.Values.Contains(market)); } /// <summary> /// Created new request ID for a given lookup type (tick, intraday bar, daily bar) /// </summary> /// <param name="lookupType">Lookup type: REQ_HST_TCK (tick), REQ_HST_DWM (daily) or REQ_HST_INT (intraday resolutions)</param> /// <param name="id">Sequential identifier</param> /// <returns></returns> private static string CreateRequestID(LookupType lookupType, int id) { return lookupType + id.ToStringInvariant("0000000"); } /// <summary> /// Method called when a new Lookup event is fired /// </summary> /// <param name="e">Received data</param> protected override void OnLookupEvent(LookupEventArgs e) { try { switch (e.Sequence) { case LookupSequence.MessageStart: _currentRequest.AddOrUpdate(e.Id, new List<BaseData>()); break; case LookupSequence.MessageDetail: List<BaseData> current; if (_currentRequest.TryGetValue(e.Id, out current)) { HandleMessageDetail(e, current); } break; case LookupSequence.MessageEnd: _inProgress = false; break; default: throw new ArgumentOutOfRangeException(); } } catch (Exception err) { Log.Error(err); } } /// <summary> /// Put received data into current list of BaseData object /// </summary> /// <param name="e">Received data</param> /// <param name="current">Current list of BaseData object</param> private void HandleMessageDetail(LookupEventArgs e, List<BaseData> current) { var requestData = _requestDataByRequestId[e.Id]; var data = GetData(e, requestData); if (data != null && data.Time != DateTime.MinValue) { current.Add(data); } } /// <summary> /// Transform received data into BaseData object /// </summary> /// <param name="e">Received data</param> /// <param name="requestData">Request information</param> /// <returns>BaseData object</returns> private BaseData GetData(LookupEventArgs e, HistoryRequest requestData) { var isEquity = requestData.Symbol.SecurityType == SecurityType.Equity; try { switch (e.Type) { case LookupType.REQ_HST_TCK: var t = (LookupTickEventArgs)e; var time = isEquity ? t.DateTimeStamp : t.DateTimeStamp.ConvertTo(TimeZones.NewYork, TimeZones.EasternStandard); return new Tick(time, requestData.Symbol, (decimal)t.Last, (decimal)t.Bid, (decimal)t.Ask) { Quantity = t.LastSize }; case LookupType.REQ_HST_INT: var i = (LookupIntervalEventArgs)e; if (i.DateTimeStamp == DateTime.MinValue) return null; var istartTime = i.DateTimeStamp - requestData.Resolution.ToTimeSpan(); if (!isEquity) istartTime = istartTime.ConvertTo(TimeZones.NewYork, TimeZones.EasternStandard); return new TradeBar(istartTime, requestData.Symbol, (decimal)i.Open, (decimal)i.High, (decimal)i.Low, (decimal)i.Close, i.PeriodVolume); case LookupType.REQ_HST_DWM: var d = (LookupDayWeekMonthEventArgs)e; if (d.DateTimeStamp == DateTime.MinValue) return null; var dstartTime = d.DateTimeStamp.Date; if (!isEquity) dstartTime = dstartTime.ConvertTo(TimeZones.NewYork, TimeZones.EasternStandard); return new TradeBar(dstartTime, requestData.Symbol, (decimal)d.Open, (decimal)d.High, (decimal)d.Low, (decimal)d.Close, d.PeriodVolume, requestData.Resolution.ToTimeSpan()); // we don't need to handle these other types case LookupType.REQ_SYM_SYM: case LookupType.REQ_SYM_SIC: case LookupType.REQ_SYM_NAC: case LookupType.REQ_TAB_MKT: case LookupType.REQ_TAB_SEC: case LookupType.REQ_TAB_MKC: case LookupType.REQ_TAB_SIC: case LookupType.REQ_TAB_NAC: default: return null; } } catch (Exception err) { Log.Error("Encountered error while processing request: " + e.Id); Log.Error(err); return null; } } private static PeriodType GetPeriodType(Resolution resolution) { switch (resolution) { case Resolution.Second: return PeriodType.Second; case Resolution.Minute: return PeriodType.Minute; case Resolution.Hour: return PeriodType.Hour; case Resolution.Tick: case Resolution.Daily: default: throw new ArgumentOutOfRangeException("resolution", resolution, null); } } } }
namespace Azure.Storage.Queues { public partial class QueueClient { protected QueueClient() { } public QueueClient(string connectionString, string queueName) { } public QueueClient(string connectionString, string queueName, Azure.Storage.Queues.QueueClientOptions options) { } public QueueClient(System.Uri queueUri, Azure.AzureSasCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueClient(System.Uri queueUri, Azure.Core.TokenCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueClient(System.Uri queueUri, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueClient(System.Uri queueUri, Azure.Storage.StorageSharedKeyCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public virtual string AccountName { get { throw null; } } public virtual bool CanGenerateSasUri { get { throw null; } } public virtual int MaxPeekableMessages { get { throw null; } } public virtual int MessageMaxBytes { get { throw null; } } protected virtual System.Uri MessagesUri { get { throw null; } } public virtual string Name { get { throw null; } } public virtual System.Uri Uri { get { throw null; } } public virtual Azure.Response ClearMessages(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> ClearMessagesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response Create(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> CreateAsync(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response CreateIfNotExists(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> CreateIfNotExistsAsync(System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response Delete(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> DeleteIfExists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> DeleteIfExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DeleteMessage(string messageId, string popReceipt, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteMessageAsync(string messageId, string popReceipt, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<bool> Exists(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<bool>> ExistsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Uri GenerateSasUri(Azure.Storage.Sas.QueueSasBuilder builder) { throw null; } public virtual System.Uri GenerateSasUri(Azure.Storage.Sas.QueueSasPermissions permissions, System.DateTimeOffset expiresOn) { throw null; } public virtual Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier>> GetAccessPolicy(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier>>> GetAccessPolicyAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } protected internal virtual Azure.Storage.Queues.QueueServiceClient GetParentQueueServiceClientCore() { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } protected virtual System.Threading.Tasks.Task OnMessageDecodingFailedAsync(Azure.Storage.Queues.Models.QueueMessage receivedMessage, Azure.Storage.Queues.Models.PeekedMessage peekedMessage, bool isRunningSynchronously, System.Threading.CancellationToken cancellationToken) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.PeekedMessage> PeekMessage(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.PeekedMessage>> PeekMessageAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.PeekedMessage[]> PeekMessages(int? maxMessages = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.PeekedMessage[]>> PeekMessagesAsync(int? maxMessages = default(int?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage> ReceiveMessage(System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage>> ReceiveMessageAsync(System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages() { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages(int? maxMessages = default(int?), System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]> ReceiveMessages(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync() { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync(int? maxMessages = default(int?), System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueMessage[]>> ReceiveMessagesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(System.BinaryData message, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.SendReceipt> SendMessage(string messageText, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(System.BinaryData message, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText, System.TimeSpan? visibilityTimeout = default(System.TimeSpan?), System.TimeSpan? timeToLive = default(System.TimeSpan?), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.SendReceipt>> SendMessageAsync(string messageText, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response SetAccessPolicy(System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier> permissions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> SetAccessPolicyAsync(System.Collections.Generic.IEnumerable<Azure.Storage.Queues.Models.QueueSignedIdentifier> permissions, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response SetMetadata(System.Collections.Generic.IDictionary<string, string> metadata, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> SetMetadataAsync(System.Collections.Generic.IDictionary<string, string> metadata, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt> UpdateMessage(string messageId, string popReceipt, System.BinaryData message, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt> UpdateMessage(string messageId, string popReceipt, string messageText = null, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt>> UpdateMessageAsync(string messageId, string popReceipt, System.BinaryData message, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.UpdateReceipt>> UpdateMessageAsync(string messageId, string popReceipt, string messageText = null, System.TimeSpan visibilityTimeout = default(System.TimeSpan), System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } protected internal virtual Azure.Storage.Queues.QueueClient WithClientSideEncryptionOptionsCore(Azure.Storage.ClientSideEncryptionOptions clientSideEncryptionOptions) { throw null; } } public partial class QueueClientOptions : Azure.Core.ClientOptions { public QueueClientOptions(Azure.Storage.Queues.QueueClientOptions.ServiceVersion version = Azure.Storage.Queues.QueueClientOptions.ServiceVersion.V2020_06_12) { } public System.Uri GeoRedundantSecondaryUri { get { throw null; } set { } } public Azure.Storage.Queues.QueueMessageEncoding MessageEncoding { get { throw null; } set { } } public Azure.Storage.Queues.QueueClientOptions.ServiceVersion Version { get { throw null; } } public event Azure.Core.SyncAsyncEventHandler<Azure.Storage.Queues.QueueMessageDecodingFailedEventArgs> MessageDecodingFailed { add { } remove { } } public enum ServiceVersion { V2019_02_02 = 1, V2019_07_07 = 2, V2019_12_12 = 3, V2020_02_10 = 4, V2020_04_08 = 5, V2020_06_12 = 6, V2020_08_04 = 7, } } public partial class QueueMessageDecodingFailedEventArgs : Azure.SyncAsyncEventArgs { public QueueMessageDecodingFailedEventArgs(Azure.Storage.Queues.QueueClient queueClient, Azure.Storage.Queues.Models.QueueMessage receivedMessage, Azure.Storage.Queues.Models.PeekedMessage peekedMessage, bool isRunningSynchronously, System.Threading.CancellationToken cancellationToken) : base (default(bool), default(System.Threading.CancellationToken)) { } public Azure.Storage.Queues.Models.PeekedMessage PeekedMessage { get { throw null; } } public Azure.Storage.Queues.QueueClient Queue { get { throw null; } } public Azure.Storage.Queues.Models.QueueMessage ReceivedMessage { get { throw null; } } } public enum QueueMessageEncoding { None = 0, Base64 = 1, } public partial class QueueServiceClient { protected QueueServiceClient() { } public QueueServiceClient(string connectionString) { } public QueueServiceClient(string connectionString, Azure.Storage.Queues.QueueClientOptions options) { } public QueueServiceClient(System.Uri serviceUri, Azure.AzureSasCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueServiceClient(System.Uri serviceUri, Azure.Core.TokenCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueServiceClient(System.Uri serviceUri, Azure.Storage.Queues.QueueClientOptions options = null) { } public QueueServiceClient(System.Uri serviceUri, Azure.Storage.StorageSharedKeyCredential credential, Azure.Storage.Queues.QueueClientOptions options = null) { } public virtual string AccountName { get { throw null; } } public virtual bool CanGenerateAccountSasUri { get { throw null; } } public virtual System.Uri Uri { get { throw null; } } public virtual Azure.Response<Azure.Storage.Queues.QueueClient> CreateQueue(string queueName, System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.QueueClient>> CreateQueueAsync(string queueName, System.Collections.Generic.IDictionary<string, string> metadata = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response DeleteQueue(string queueName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> DeleteQueueAsync(string queueName, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public System.Uri GenerateAccountSasUri(Azure.Storage.Sas.AccountSasBuilder builder) { throw null; } public System.Uri GenerateAccountSasUri(Azure.Storage.Sas.AccountSasPermissions permissions, System.DateTimeOffset expiresOn, Azure.Storage.Sas.AccountSasResourceTypes resourceTypes) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueServiceProperties> GetProperties(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueServiceProperties>> GetPropertiesAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Storage.Queues.QueueClient GetQueueClient(string queueName) { throw null; } public virtual Azure.Pageable<Azure.Storage.Queues.Models.QueueItem> GetQueues(Azure.Storage.Queues.Models.QueueTraits traits = Azure.Storage.Queues.Models.QueueTraits.None, string prefix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.AsyncPageable<Azure.Storage.Queues.Models.QueueItem> GetQueuesAsync(Azure.Storage.Queues.Models.QueueTraits traits = Azure.Storage.Queues.Models.QueueTraits.None, string prefix = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response<Azure.Storage.Queues.Models.QueueServiceStatistics> GetStatistics(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response<Azure.Storage.Queues.Models.QueueServiceStatistics>> GetStatisticsAsync(System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual Azure.Response SetProperties(Azure.Storage.Queues.Models.QueueServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } public virtual System.Threading.Tasks.Task<Azure.Response> SetPropertiesAsync(Azure.Storage.Queues.Models.QueueServiceProperties properties, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { throw null; } } public partial class QueueUriBuilder { public QueueUriBuilder(System.Uri uri) { } public string AccountName { get { throw null; } set { } } public string Host { get { throw null; } set { } } public string MessageId { get { throw null; } set { } } public bool Messages { get { throw null; } set { } } public int Port { get { throw null; } set { } } public string Query { get { throw null; } set { } } public string QueueName { get { throw null; } set { } } public Azure.Storage.Sas.SasQueryParameters Sas { get { throw null; } set { } } public string Scheme { get { throw null; } set { } } public override string ToString() { throw null; } public System.Uri ToUri() { throw null; } } } namespace Azure.Storage.Queues.Models { public partial class PeekedMessage { internal PeekedMessage() { } public System.BinaryData Body { get { throw null; } } public long DequeueCount { get { throw null; } } public System.DateTimeOffset? ExpiresOn { get { throw null; } } public System.DateTimeOffset? InsertedOn { get { throw null; } } public string MessageId { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public string MessageText { get { throw null; } } } public partial class QueueAccessPolicy { public QueueAccessPolicy() { } public System.DateTimeOffset? ExpiresOn { get { throw null; } set { } } public string Permissions { get { throw null; } set { } } public System.DateTimeOffset? StartsOn { get { throw null; } set { } } } public partial class QueueAnalyticsLogging { public QueueAnalyticsLogging() { } public bool Delete { get { throw null; } set { } } public bool Read { get { throw null; } set { } } public Azure.Storage.Queues.Models.QueueRetentionPolicy RetentionPolicy { get { throw null; } set { } } public string Version { get { throw null; } set { } } public bool Write { get { throw null; } set { } } } public partial class QueueCorsRule { public QueueCorsRule() { } public string AllowedHeaders { get { throw null; } set { } } public string AllowedMethods { get { throw null; } set { } } public string AllowedOrigins { get { throw null; } set { } } public string ExposedHeaders { get { throw null; } set { } } public int MaxAgeInSeconds { get { throw null; } set { } } } [System.Runtime.InteropServices.StructLayoutAttribute(System.Runtime.InteropServices.LayoutKind.Sequential)] public readonly partial struct QueueErrorCode : System.IEquatable<Azure.Storage.Queues.Models.QueueErrorCode> { private readonly object _dummy; private readonly int _dummyPrimitive; public QueueErrorCode(string value) { throw null; } public static Azure.Storage.Queues.Models.QueueErrorCode AccountAlreadyExists { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AccountBeingCreated { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AccountIsDisabled { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthenticationFailed { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationFailure { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationPermissionMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationProtocolMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationResourceTypeMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationServiceMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode AuthorizationSourceIPMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ConditionHeadersNotSupported { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ConditionNotMet { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode EmptyMetadataKey { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode FeatureVersionMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InsufficientAccountPermissions { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InternalError { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidAuthenticationInfo { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidHeaderValue { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidHttpVerb { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidInput { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMarker { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMd5 { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidMetadata { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidQueryParameterValue { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidRange { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidResourceName { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidUri { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidXmlDocument { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode InvalidXmlNodeValue { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode Md5Mismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MessageNotFound { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MessageTooLarge { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MetadataTooLarge { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MissingContentLengthHeader { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredHeader { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredQueryParameter { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MissingRequiredXmlNode { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode MultipleConditionHeadersNotSupported { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode OperationTimedOut { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode OutOfRangeInput { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode OutOfRangeQueryParameterValue { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode PopReceiptMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode QueueAlreadyExists { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode QueueBeingDeleted { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode QueueDisabled { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode QueueNotEmpty { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode QueueNotFound { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode RequestBodyTooLarge { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode RequestUrlFailedToParse { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ResourceAlreadyExists { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ResourceNotFound { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ResourceTypeMismatch { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode ServerBusy { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedHeader { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedHttpVerb { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedQueryParameter { get { throw null; } } public static Azure.Storage.Queues.Models.QueueErrorCode UnsupportedXmlNode { get { throw null; } } public bool Equals(Azure.Storage.Queues.Models.QueueErrorCode other) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public static bool operator ==(Azure.Storage.Queues.Models.QueueErrorCode left, Azure.Storage.Queues.Models.QueueErrorCode right) { throw null; } public static implicit operator Azure.Storage.Queues.Models.QueueErrorCode (string value) { throw null; } public static bool operator !=(Azure.Storage.Queues.Models.QueueErrorCode left, Azure.Storage.Queues.Models.QueueErrorCode right) { throw null; } public override string ToString() { throw null; } } public partial class QueueGeoReplication { internal QueueGeoReplication() { } public System.DateTimeOffset? LastSyncedOn { get { throw null; } } public Azure.Storage.Queues.Models.QueueGeoReplicationStatus Status { get { throw null; } } } public enum QueueGeoReplicationStatus { Live = 0, Bootstrap = 1, Unavailable = 2, } public partial class QueueItem { internal QueueItem() { } public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } } public string Name { get { throw null; } } } public partial class QueueMessage { internal QueueMessage() { } public System.BinaryData Body { get { throw null; } } public long DequeueCount { get { throw null; } } public System.DateTimeOffset? ExpiresOn { get { throw null; } } public System.DateTimeOffset? InsertedOn { get { throw null; } } public string MessageId { get { throw null; } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public string MessageText { get { throw null; } } public System.DateTimeOffset? NextVisibleOn { get { throw null; } } public string PopReceipt { get { throw null; } } public Azure.Storage.Queues.Models.QueueMessage Update(Azure.Storage.Queues.Models.UpdateReceipt updated) { throw null; } } public partial class QueueMetrics { public QueueMetrics() { } public bool Enabled { get { throw null; } set { } } public bool? IncludeApis { get { throw null; } set { } } public Azure.Storage.Queues.Models.QueueRetentionPolicy RetentionPolicy { get { throw null; } set { } } public string Version { get { throw null; } set { } } } public partial class QueueProperties { public QueueProperties() { } public int ApproximateMessagesCount { get { throw null; } } public System.Collections.Generic.IDictionary<string, string> Metadata { get { throw null; } } } public partial class QueueRetentionPolicy { public QueueRetentionPolicy() { } public int? Days { get { throw null; } set { } } public bool Enabled { get { throw null; } set { } } } public partial class QueueServiceProperties { public QueueServiceProperties() { } public System.Collections.Generic.IList<Azure.Storage.Queues.Models.QueueCorsRule> Cors { get { throw null; } set { } } public Azure.Storage.Queues.Models.QueueMetrics HourMetrics { get { throw null; } set { } } public Azure.Storage.Queues.Models.QueueAnalyticsLogging Logging { get { throw null; } set { } } public Azure.Storage.Queues.Models.QueueMetrics MinuteMetrics { get { throw null; } set { } } } public partial class QueueServiceStatistics { internal QueueServiceStatistics() { } public Azure.Storage.Queues.Models.QueueGeoReplication GeoReplication { get { throw null; } } } public partial class QueueSignedIdentifier { public QueueSignedIdentifier() { } public Azure.Storage.Queues.Models.QueueAccessPolicy AccessPolicy { get { throw null; } set { } } public string Id { get { throw null; } set { } } } public static partial class QueuesModelFactory { public static Azure.Storage.Queues.Models.PeekedMessage PeekedMessage(string messageId, System.BinaryData message, long dequeueCount, System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static Azure.Storage.Queues.Models.PeekedMessage PeekedMessage(string messageId, string messageText, long dequeueCount, System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; } public static Azure.Storage.Queues.Models.QueueGeoReplication QueueGeoReplication(Azure.Storage.Queues.Models.QueueGeoReplicationStatus status, System.DateTimeOffset? lastSyncedOn = default(System.DateTimeOffset?)) { throw null; } public static Azure.Storage.Queues.Models.QueueItem QueueItem(string name, System.Collections.Generic.IDictionary<string, string> metadata = null) { throw null; } public static Azure.Storage.Queues.Models.QueueMessage QueueMessage(string messageId, string popReceipt, System.BinaryData body, long dequeueCount, System.DateTimeOffset? nextVisibleOn = default(System.DateTimeOffset?), System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public static Azure.Storage.Queues.Models.QueueMessage QueueMessage(string messageId, string popReceipt, string messageText, long dequeueCount, System.DateTimeOffset? nextVisibleOn = default(System.DateTimeOffset?), System.DateTimeOffset? insertedOn = default(System.DateTimeOffset?), System.DateTimeOffset? expiresOn = default(System.DateTimeOffset?)) { throw null; } public static Azure.Storage.Queues.Models.QueueProperties QueueProperties(System.Collections.Generic.IDictionary<string, string> metadata, int approximateMessagesCount) { throw null; } public static Azure.Storage.Queues.Models.QueueServiceStatistics QueueServiceStatistics(Azure.Storage.Queues.Models.QueueGeoReplication geoReplication = null) { throw null; } public static Azure.Storage.Queues.Models.SendReceipt SendReceipt(string messageId, System.DateTimeOffset insertionTime, System.DateTimeOffset expirationTime, string popReceipt, System.DateTimeOffset timeNextVisible) { throw null; } public static Azure.Storage.Queues.Models.UpdateReceipt UpdateReceipt(string popReceipt, System.DateTimeOffset nextVisibleOn) { throw null; } } [System.FlagsAttribute] public enum QueueTraits { None = 0, Metadata = 1, } public partial class SendReceipt { internal SendReceipt() { } public System.DateTimeOffset ExpirationTime { get { throw null; } } public System.DateTimeOffset InsertionTime { get { throw null; } } public string MessageId { get { throw null; } } public string PopReceipt { get { throw null; } } public System.DateTimeOffset TimeNextVisible { get { throw null; } } } public partial class UpdateReceipt { internal UpdateReceipt() { } public System.DateTimeOffset NextVisibleOn { get { throw null; } } public string PopReceipt { get { throw null; } } } } namespace Azure.Storage.Queues.Specialized { public partial class ClientSideDecryptionFailureEventArgs { internal ClientSideDecryptionFailureEventArgs() { } public System.Exception Exception { get { throw null; } } } public partial class QueueClientSideEncryptionOptions : Azure.Storage.ClientSideEncryptionOptions { public QueueClientSideEncryptionOptions(Azure.Storage.ClientSideEncryptionVersion version) : base (default(Azure.Storage.ClientSideEncryptionVersion)) { } public event System.EventHandler<Azure.Storage.Queues.Specialized.ClientSideDecryptionFailureEventArgs> DecryptionFailed { add { } remove { } } } public partial class SpecializedQueueClientOptions : Azure.Storage.Queues.QueueClientOptions { public SpecializedQueueClientOptions(Azure.Storage.Queues.QueueClientOptions.ServiceVersion version = Azure.Storage.Queues.QueueClientOptions.ServiceVersion.V2020_06_12) : base (default(Azure.Storage.Queues.QueueClientOptions.ServiceVersion)) { } public Azure.Storage.ClientSideEncryptionOptions ClientSideEncryption { get { throw null; } set { } } } public static partial class SpecializedQueueExtensions { public static Azure.Storage.Queues.QueueServiceClient GetParentQueueServiceClient(this Azure.Storage.Queues.QueueClient client) { throw null; } public static Azure.Storage.Queues.QueueClient WithClientSideEncryptionOptions(this Azure.Storage.Queues.QueueClient client, Azure.Storage.ClientSideEncryptionOptions clientSideEncryptionOptions) { throw null; } } } namespace Azure.Storage.Sas { [System.FlagsAttribute] public enum QueueAccountSasPermissions { All = -1, Read = 1, Write = 2, Delete = 4, List = 8, Add = 16, Update = 32, Process = 64, } public partial class QueueSasBuilder { [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public QueueSasBuilder() { } public QueueSasBuilder(Azure.Storage.Sas.QueueAccountSasPermissions permissions, System.DateTimeOffset expiresOn) { } public QueueSasBuilder(Azure.Storage.Sas.QueueSasPermissions permissions, System.DateTimeOffset expiresOn) { } public System.DateTimeOffset ExpiresOn { get { throw null; } set { } } public string Identifier { get { throw null; } set { } } public Azure.Storage.Sas.SasIPRange IPRange { get { throw null; } set { } } public string Permissions { get { throw null; } } public Azure.Storage.Sas.SasProtocol Protocol { get { throw null; } set { } } public string QueueName { get { throw null; } set { } } public System.DateTimeOffset StartsOn { get { throw null; } set { } } public string Version { get { throw null; } set { } } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override bool Equals(object obj) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override int GetHashCode() { throw null; } public void SetPermissions(Azure.Storage.Sas.QueueAccountSasPermissions permissions) { } public void SetPermissions(Azure.Storage.Sas.QueueSasPermissions permissions) { } public void SetPermissions(string rawPermissions) { } public void SetPermissions(string rawPermissions, bool normalize = false) { } public Azure.Storage.Sas.SasQueryParameters ToSasQueryParameters(Azure.Storage.StorageSharedKeyCredential sharedKeyCredential) { throw null; } [System.ComponentModel.EditorBrowsableAttribute(System.ComponentModel.EditorBrowsableState.Never)] public override string ToString() { throw null; } } [System.FlagsAttribute] public enum QueueSasPermissions { All = -1, Read = 1, Add = 2, Update = 4, Process = 8, } } namespace Microsoft.Extensions.Azure { public static partial class QueueClientBuilderExtensions { public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, string connectionString) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, System.Uri serviceUri) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithCredential { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder>(this TBuilder builder, System.Uri serviceUri, Azure.Storage.StorageSharedKeyCredential sharedKeyCredential) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilder { throw null; } public static Azure.Core.Extensions.IAzureClientBuilder<Azure.Storage.Queues.QueueServiceClient, Azure.Storage.Queues.QueueClientOptions> AddQueueServiceClient<TBuilder, TConfiguration>(this TBuilder builder, TConfiguration configuration) where TBuilder : Azure.Core.Extensions.IAzureClientFactoryBuilderWithConfiguration<TConfiguration> { throw null; } } }
// Copyright 2016 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 Google.Api.Gax; using System; using static Google.Apis.Storage.v1.ObjectsResource; using static Google.Apis.Storage.v1.ObjectsResource.RewriteRequest; using Object = Google.Apis.Storage.v1.Data.Object; namespace Google.Cloud.Storage.V1 { /// <summary> /// Options for <c>CopyObject</c> operations. /// </summary> public sealed class CopyObjectOptions { // TODO: maxBytesRewrittenPerCall? Specific to rewrite... /// <summary> /// The generation of the object resource to copy. When not /// set, the latest generation will be copied. /// </summary> public long? SourceGeneration { get; set; } /// <summary> /// The projection to retrieve. /// </summary> public Projection? Projection { get; set; } /// <summary> /// A predefined set of ACLs for the new object. /// </summary> public PredefinedObjectAcl? DestinationPredefinedAcl { get; set; } /// <summary> /// Precondition for copying: the object is only copied if the existing destination object's /// generation matches the given value. /// </summary> public long? IfGenerationMatch { get; set; } /// <summary> /// Precondition for copying: the object is only copied if the existing destination object's /// generation does not match the given value. /// </summary> public long? IfGenerationNotMatch { get; set; } /// <summary> /// Precondition for copying: the object is only copied if the existing destination object's /// meta-generation matches the given value. /// </summary> public long? IfMetagenerationMatch { get; set; } /// <summary> /// Precondition for copying: the object is only copied if the existing destination object's /// meta-generation does not match the given value. /// </summary> public long? IfMetagenerationNotMatch { get; set; } /// <summary> /// Precondition for copying: the object is only copied if the source object's /// generation matches the given value. /// </summary> public long? IfSourceGenerationMatch { get; set; } /// <summary> /// Precondition for copying: the object is only copied if the source object's /// generation does not match the given value. /// </summary> public long? IfSourceGenerationNotMatch { get; set; } /// <summary> /// Precondition for copying: the object is only copied if the source object's /// meta-generation matches the given value. /// </summary> public long? IfSourceMetagenerationMatch { get; set; } /// <summary> /// Precondition for copying: the object is only copied if the source object's /// meta-generation does not match the given value. /// </summary> public long? IfSourceMetagenerationNotMatch { get; set; } /// <summary> /// Additional object metadata for the new object. This can be used to specify the storage /// class of the new object, the content type etc. If this property is not set, the existing /// object metadata will be used unchanged. /// </summary> public Object ExtraMetadata { get; set; } /// <summary> /// The encryption key to use for this operation. If this property is null, the <see cref="StorageClient.EncryptionKey"/> /// will be used instead. Use <see cref="EncryptionKey.None"/> to remove encryption headers from this request. /// </summary> public EncryptionKey EncryptionKey { get; set; } /// <summary> /// The encryption key to use for the source of the copy. If this property is null, the <see cref="StorageClient.EncryptionKey"/> /// will be used instead. Use <see cref="EncryptionKey.None"/> if the source is not encrypted. /// </summary> public EncryptionKey SourceEncryptionKey { get; set; } /// <summary> /// The name of the Cloud KMS key to use to encrypt the new object. /// </summary> /// <remarks> /// Currently, either customer-supplied encryption or a Cloud KMS key can be used, but not both. /// If this property is null and customer-supplied encryption is not being used, /// the bucket encryption defaults will be used to determine the encryption for the object. /// If this property is non-null and the client object has a default encryption key, the <see cref="EncryptionKey"/> property /// of this options object must be set to <see cref="EncryptionKey.None"/> to make the intention clear. /// </remarks> public string KmsKeyName { get; set; } /// <summary> /// If set, this is the ID of the project which will be billed for the request. /// The caller must have suitable permissions for the project being billed. /// </summary> public string UserProject { get; set; } internal void ModifyRequest(RewriteRequest request) { // Note the use of ArgumentException here, as this will basically be the result of invalid // options being passed to a public method. if (IfGenerationMatch != null && IfGenerationNotMatch != null) { throw new ArgumentException($"Cannot specify {nameof(IfGenerationMatch)} and {nameof(IfGenerationNotMatch)} in the same options", "options"); } if (IfMetagenerationMatch != null && IfMetagenerationNotMatch != null) { throw new ArgumentException($"Cannot specify {nameof(IfMetagenerationMatch)} and {nameof(IfMetagenerationNotMatch)} in the same options", "options"); } if (IfSourceGenerationMatch != null && IfSourceGenerationNotMatch != null) { throw new ArgumentException($"Cannot specify {nameof(IfSourceGenerationMatch)} and {nameof(IfSourceGenerationNotMatch)} in the same options", "options"); } if (IfSourceMetagenerationMatch != null && IfSourceMetagenerationNotMatch != null) { throw new ArgumentException($"Cannot specify {nameof(IfSourceMetagenerationMatch)} and {nameof(IfSourceMetagenerationNotMatch)} in the same options", "options"); } if (DestinationPredefinedAcl != null) { request.DestinationPredefinedAcl = GaxPreconditions.CheckEnumValue((DestinationPredefinedAclEnum) DestinationPredefinedAcl, nameof(DestinationPredefinedAcl)); } if (SourceGeneration != null) { request.SourceGeneration = SourceGeneration; } if (Projection != null) { request.Projection = GaxPreconditions.CheckEnumValue((ProjectionEnum) Projection, nameof(Projection)); } if (IfGenerationMatch != null) { request.IfGenerationMatch = IfGenerationMatch; } if (IfGenerationNotMatch != null) { request.IfGenerationNotMatch = IfGenerationNotMatch; } if (IfMetagenerationMatch != null) { request.IfMetagenerationMatch = IfMetagenerationMatch; } if (IfMetagenerationNotMatch != null) { request.IfMetagenerationNotMatch = IfMetagenerationNotMatch; } if (IfSourceGenerationMatch != null) { request.IfSourceGenerationMatch = IfSourceGenerationMatch; } if (IfSourceGenerationNotMatch != null) { request.IfSourceGenerationNotMatch = IfSourceGenerationNotMatch; } if (IfSourceMetagenerationMatch != null) { request.IfSourceMetagenerationMatch = IfSourceMetagenerationMatch; } if (IfSourceMetagenerationNotMatch != null) { request.IfSourceMetagenerationNotMatch = IfSourceMetagenerationNotMatch; } if (UserProject != null) { request.UserProject = UserProject; } // Note: specifying this and EncryptionKey as non-null/non-None is invalid, but that's checked in StorageClientImpl. if (KmsKeyName != null) { request.DestinationKmsKeyName = KmsKeyName; } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Linq; namespace System.Collections.Immutable { /// <summary> /// An immutable queue. /// </summary> /// <typeparam name="T">The type of elements stored in the queue.</typeparam> [DebuggerDisplay("IsEmpty = {IsEmpty}")] [DebuggerTypeProxy(typeof(ImmutableEnumerableDebuggerProxy<>))] [SuppressMessage("Microsoft.Naming", "CA1710:IdentifiersShouldHaveCorrectSuffix", Justification = "Ignored")] [SuppressMessage("Microsoft.Naming", "CA1711:IdentifiersShouldNotHaveIncorrectSuffix", Justification = "Ignored")] public sealed partial class ImmutableQueue<T> : IImmutableQueue<T> { /// <summary> /// The singleton empty queue. /// </summary> /// <remarks> /// Additional instances representing the empty queue may exist on deserialized instances. /// Actually since this queue is a struct, instances don't even apply and there are no singletons. /// </remarks> private static readonly ImmutableQueue<T> s_EmptyField = new ImmutableQueue<T>(ImmutableStack<T>.Empty, ImmutableStack<T>.Empty); /// <summary> /// The end of the queue that enqueued elements are pushed onto. /// </summary> private readonly ImmutableStack<T> _backwards; /// <summary> /// The end of the queue from which elements are dequeued. /// </summary> private readonly ImmutableStack<T> _forwards; /// <summary> /// Backing field for the <see cref="BackwardsReversed"/> property. /// </summary> private ImmutableStack<T> _backwardsReversed; /// <summary> /// Initializes a new instance of the <see cref="ImmutableQueue{T}"/> class. /// </summary> /// <param name="forwards">The forwards stack.</param> /// <param name="backwards">The backwards stack.</param> internal ImmutableQueue(ImmutableStack<T> forwards, ImmutableStack<T> backwards) { Debug.Assert(forwards != null); Debug.Assert(backwards != null); _forwards = forwards; _backwards = backwards; } /// <summary> /// Gets the empty queue. /// </summary> public ImmutableQueue<T> Clear() { Debug.Assert(s_EmptyField.IsEmpty); return Empty; } /// <summary> /// Gets a value indicating whether this instance is empty. /// </summary> /// <value> /// <c>true</c> if this instance is empty; otherwise, <c>false</c>. /// </value> public bool IsEmpty { get { Debug.Assert(!_forwards.IsEmpty || _backwards.IsEmpty); return _forwards.IsEmpty; } } /// <summary> /// Gets the empty queue. /// </summary> public static ImmutableQueue<T> Empty { get { Debug.Assert(s_EmptyField.IsEmpty); return s_EmptyField; } } /// <summary> /// Gets an empty queue. /// </summary> IImmutableQueue<T> IImmutableQueue<T>.Clear() { Debug.Assert(s_EmptyField.IsEmpty); return this.Clear(); } /// <summary> /// Gets the reversed <see cref="_backwards"/> stack. /// </summary> private ImmutableStack<T> BackwardsReversed { get { // Although this is a lazy-init pattern, no lock is required because // this instance is immutable otherwise, and a double-assignment from multiple // threads is harmless. if (_backwardsReversed == null) { _backwardsReversed = _backwards.Reverse(); } Debug.Assert(_backwardsReversed != null); return _backwardsReversed; } } /// <summary> /// Gets the element at the front of the queue. /// </summary> /// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception> [Pure] public T Peek() { if (this.IsEmpty) { throw new InvalidOperationException(SR.InvalidEmptyOperation); } return _forwards.Peek(); } #if !NETSTANDARD1_0 /// <summary> /// Gets a read-only reference to the element at the front of the queue. /// </summary> /// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception> [Pure] public ref readonly T PeekRef() { if (this.IsEmpty) { throw new InvalidOperationException(SR.InvalidEmptyOperation); } return ref _forwards.PeekRef(); } #endif /// <summary> /// Adds an element to the back of the queue. /// </summary> /// <param name="value">The value.</param> /// <returns> /// The new queue. /// </returns> [Pure] public ImmutableQueue<T> Enqueue(T value) { if (this.IsEmpty) { return new ImmutableQueue<T>(ImmutableStack.Create(value), ImmutableStack<T>.Empty); } else { return new ImmutableQueue<T>(_forwards, _backwards.Push(value)); } } /// <summary> /// Adds an element to the back of the queue. /// </summary> /// <param name="value">The value.</param> /// <returns> /// The new queue. /// </returns> [Pure] IImmutableQueue<T> IImmutableQueue<T>.Enqueue(T value) { return this.Enqueue(value); } /// <summary> /// Returns a queue that is missing the front element. /// </summary> /// <returns>A queue; never <c>null</c>.</returns> /// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception> [Pure] public ImmutableQueue<T> Dequeue() { if (this.IsEmpty) { throw new InvalidOperationException(SR.InvalidEmptyOperation); } ImmutableStack<T> f = _forwards.Pop(); if (!f.IsEmpty) { return new ImmutableQueue<T>(f, _backwards); } else if (_backwards.IsEmpty) { return ImmutableQueue<T>.Empty; } else { return new ImmutableQueue<T>(this.BackwardsReversed, ImmutableStack<T>.Empty); } } /// <summary> /// Retrieves the item at the head of the queue, and returns a queue with the head element removed. /// </summary> /// <param name="value">Receives the value from the head of the queue.</param> /// <returns>The new queue with the head element removed.</returns> /// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception> [SuppressMessage("Microsoft.Design", "CA1021:AvoidOutParameters", MessageId = "0#")] [Pure] public ImmutableQueue<T> Dequeue(out T value) { value = this.Peek(); return this.Dequeue(); } /// <summary> /// Returns a queue that is missing the front element. /// </summary> /// <returns>A queue; never <c>null</c>.</returns> /// <exception cref="InvalidOperationException">Thrown when the queue is empty.</exception> [Pure] IImmutableQueue<T> IImmutableQueue<T>.Dequeue() { return this.Dequeue(); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// An <see cref="Enumerator"/> that can be used to iterate through the collection. /// </returns> [Pure] public Enumerator GetEnumerator() { return new Enumerator(this); } /// <summary> /// Returns an enumerator that iterates through the collection. /// </summary> /// <returns> /// A <see cref="IEnumerator{T}"/> that can be used to iterate through the collection. /// </returns> [Pure] IEnumerator<T> IEnumerable<T>.GetEnumerator() { return this.IsEmpty ? Enumerable.Empty<T>().GetEnumerator() : new EnumeratorObject(this); } /// <summary> /// Returns an enumerator that iterates through a collection. /// </summary> /// <returns> /// An <see cref="IEnumerator"/> object that can be used to iterate through the collection. /// </returns> [Pure] IEnumerator IEnumerable.GetEnumerator() { return new EnumeratorObject(this); } } }
#region CopyrightHeader // // Copyright by Contributors // // 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.txt // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections.Generic; using System.Collections; using System.Collections.Specialized; using System.Text; using gov.va.medora.mdo; using gov.va.medora.utils; using gov.va.medora.mdo.exceptions; using gov.va.medora.mdo.src.mdo; namespace gov.va.medora.mdo.dao.vista { public class VistaNoteDao : INoteDao { AbstractConnection cxn = null; public VistaNoteDao(AbstractConnection cxn) { this.cxn = cxn; } #region Note Definitions public bool isNoteDefined(string noteDefinitionIen) { VistaUtils.CheckRpcParams(noteDefinitionIen); string arg = "$D(^TIU(8925.1," + noteDefinitionIen + ",0))"; MdoQuery request = VistaUtils.buildGetVariableValueRequest(arg); string response = (string)cxn.query(request); return response == "1"; } public Dictionary<string, ArrayList> getNoteTitles(string target, string direction) { MdoQuery request = buildGetNoteTitlesRequest(target.ToUpper(), direction); string response = (string)cxn.query(request); return toNoteTitles(response); } internal MdoQuery buildGetNoteTitlesRequest(string target, string direction) { VistaQuery vq = new VistaQuery("TIU LONG LIST OF TITLES"); vq.addParameter(vq.LITERAL, "3"); if (target == null || target == "") { vq.addParameter(vq.LITERAL, ""); } else { vq.addParameter(vq.LITERAL, VistaUtils.adjustForNameSearch(target)); } vq.addParameter(vq.LITERAL, VistaUtils.setDirectionParam(direction)); return vq; } internal Dictionary<string, ArrayList> toNoteTitles(string response) { if (response == "") { return null; } String[] lines = StringUtils.split(response, StringUtils.CRLF); Dictionary<string, ArrayList> result = new Dictionary<string, ArrayList>(lines.Length); for (int i = 0; i < lines.Length; i++) { if (lines[i] == "") { continue; } String[] flds = StringUtils.split(lines[i], StringUtils.CARET); if (result.ContainsKey(flds[0])) { ArrayList lst = result[flds[0]]; lst.Add(flds[1]); } else { ArrayList lst = new ArrayList(); lst.Add(flds[1]); result.Add(flds[0], lst); } } return result; } public StringDictionary getEnterpriseTitles() { return cxn.SystemFileHandler.getLookupTable(VistaConstants.TIU_VHA_ENTERPRISE); } public string getNoteDefinitionIen(string title) { if (String.IsNullOrEmpty(title)) { throw new NullOrEmptyParamException("title"); } string arg = "$O(^TIU(8925.1,\"B\",\"" + title + "\",0))"; string response = VistaUtils.getVariableValue(cxn, arg); return VistaUtils.errMsgOrIen(response); } public NoteDefinition getNationalNoteDefinition(string ien) { VistaUtils.CheckRpcParams(ien); string arg = "$G(^TIU(8926.1," + ien + ",0))_U_$G(^TIU(8926.1," + ien + ",\"VUID\"))"; string response = VistaUtils.getVariableValue(cxn, arg); NoteDefinition result = toNoteDefinition(response); result.Id = ien; return result; } internal NoteDefinition toNoteDefinition(string response) { if (response == "") { return null; } string[] flds = StringUtils.split(response, StringUtils.CARET); NoteDefinition result = new NoteDefinition(); result.StandardTitle = flds[0]; result.Vuid = flds[8]; return result; } #endregion #region Read Progress Notes internal Note[] getNotes(string fromDate, string toDate, int nNotes, string noteType) { return getNotes(cxn.Pid, fromDate, toDate, nNotes, noteType); } internal Note[] getNotes(string dfn, string fromDate, string toDate, int nNotes, string noteType) { MdoQuery request = buildGetNotesRequest(dfn, fromDate, toDate, nNotes, noteType); string response = (string)cxn.query(request); return toNotes(response); } internal MdoQuery buildGetNotesRequest(string dfn, string fromDate, string toDate, int nNotes, string noteType) { VistaUtils.CheckRpcParams(dfn, fromDate, toDate); VistaQuery vq = new VistaQuery("TIU DOCUMENTS BY CONTEXT"); vq.addParameter(vq.LITERAL, "3"); if (noteType == "1") { if (fromDate == "") { fromDate = "-1"; toDate = "-1"; vq.addParameter(vq.LITERAL, "1"); } else { if (toDate == "") { //Changed the call to be -1 and let the Vista Procedure change //it, this way we can test calls with blank/default dates, as the //call signature will be constant (b/w Mock XML Doc and the test //call) //VistaToolsDao toolsDao = new VistaToolsDao(cxn); //toDate = toolsDao.getTimestamp(); toDate = "-1"; } vq.addParameter(vq.LITERAL, "5"); } } else { vq.addParameter(vq.LITERAL, noteType); } vq.addParameter(vq.LITERAL, dfn); if (fromDate =="") {fromDate = "-1";}; if (toDate =="") {toDate = "-1";}; if (fromDate == "-1") {vq.addParameter(vq.LITERAL, fromDate); } else {vq.addParameter(vq.LITERAL, VistaTimestamp.fromUtcFromDate(fromDate)); } if (toDate == "-1") {vq.addParameter(vq.LITERAL,toDate); } else {vq.addParameter(vq.LITERAL, VistaTimestamp.fromUtcToDate(toDate));} vq.addParameter(vq.LITERAL, "0"); vq.addParameter(vq.LITERAL, nNotes.ToString()); vq.addParameter(vq.LITERAL, "D"); vq.addParameter(vq.LITERAL, "1"); return vq; } internal Note[] toNotes(string response) { if (response == "") { return null; } string[] rex = StringUtils.split(response, StringUtils.CRLF); ArrayList lst = new ArrayList(); for (int i = 0; i < rex.Length; i++) { if (rex[i] == "" || rex[i].StartsWith("^")) { continue; } string[] flds = StringUtils.split(rex[i], StringUtils.CARET); Note note = new Note(); note.Id = flds[0]; note.LocalTitle = flds[1]; note.Timestamp = VistaTimestamp.toUtcString(flds[2]); string[] authorFlds = StringUtils.split(flds[4], StringUtils.SEMICOLON); if (authorFlds[0] != "0") { note.Author = new Author(authorFlds[0], authorFlds[2], authorFlds[1]); } if (flds.Length > 5) { //[DP] 4/6/2011 Fixed the Location ID and Name fields on the //Location Object on the Note Object. //The location name was being put into the location id field. //The RPC returns the Name of the Location within the "Site" //(Hospital), this was putting it into the id field, it now //puts it into the name field, and gets the id with a get //variable value call to the Vista database. string noteLocationName = flds[5]; string locationId = ""; if ((noteLocationName != null) & (noteLocationName != "")) { //Get the ID from the Location Name string arg = "$O(^SC(\"B\",\"" + noteLocationName + "\",0))"; MdoQuery request = VistaUtils.buildGetVariableValueRequest(arg); locationId = (string)cxn.query(request); } note.Location = new HospitalLocation(locationId, noteLocationName); } if (flds.Length > 10) { note.HasImages = (flds[10] != "0"); } if (flds.Length > 12) { note.HasAddendum = (flds[12] == "+"); } if (flds.Length > 13) { if (flds[13].Length > 1) { note.OriginalNoteId = flds[13]; note.IsAddendum = true; } } note.SiteId = cxn.DataSource.SiteId; lst.Add(note); } return (Note[])lst.ToArray(typeof(Note)); } public string getNoteText(string noteIEN) { MdoQuery request = buildGetNoteTextRequest(noteIEN); string response = (string)cxn.query(request); return response; } internal MdoQuery buildGetNoteTextRequest(string noteIEN) { VistaUtils.CheckRpcParams(noteIEN); VistaQuery vq = new VistaQuery("TIU GET RECORD TEXT"); vq.addParameter(vq.LITERAL, noteIEN); return vq; } public Note[] getSignedNotes(String fromDate, String toDate, int nNotes) { return getNotes(fromDate, toDate, nNotes, "1"); } public Note[] getUnsignedNotes(String fromDate, String toDate, int nNotes) { return getNotes(fromDate, toDate, nNotes, "2"); } public Note[] getUncosignedNotes(String fromDate, String toDate, int nNotes) { return getNotes(fromDate, toDate, nNotes, "3"); } public Note[] getNotes(string fromDate, string toDate, int nNotes) { return getNotes(cxn.Pid, fromDate, toDate, nNotes); } public Note[] getNotes(string dfn, string fromDate, string toDate, int nNotes) { MdoQuery request = null; string response = ""; try { request = buildGetNotesRequest(dfn, fromDate, toDate, nNotes); response = (string)cxn.query(request); return toNotesFromRdv(response); } catch (Exception exc) { throw new MdoException(request, response, MdoExceptionCode.REQUEST_RESPONSE_ERROR, exc); } } internal MdoQuery buildGetNotesRequest(string dfn, string fromDate, string toDate, int nNotes) { return VistaUtils.buildReportTextRequest(dfn, fromDate, toDate, nNotes, "OR_PN:PROGRESS NOTES~TIUPRG;ORDV04;15;"); } internal Note[] toNotesFromRdv(string response) { if (String.IsNullOrEmpty(response)) { return null; } string[] lines = StringUtils.split(response, StringUtils.CRLF); ArrayList lst = new ArrayList(); Note note = null; string scannedDoc = ""; bool fInTextPortion = false; for (int i = 0; i < lines.Length; i++) { if (lines[i] == "") { continue; } string[] flds = StringUtils.split(lines[i], StringUtils.CARET); if (flds.Length == 1 && fInTextPortion) { scannedDoc += lines[i] + "\r\n"; continue; } if (flds[1] == "[+]") { note.Text = VistaUtils.removeCtlChars(note.Text); lst.Add(note); fInTextPortion = false; } else if (flds[0] == "1") { fInTextPortion = false; note = new Note(); string[] subflds = StringUtils.split(flds[1], StringUtils.SEMICOLON); if (subflds.Length == 2) { note.SiteId = new SiteId(subflds[1], subflds[0]); } else if (flds[1] != "") { note.SiteId = new SiteId(cxn.DataSource.SiteId.Id, flds[1]); } else { note.SiteId = cxn.DataSource.SiteId; } } else if (flds[0] == "2") { note.Id = flds[1]; } else if (flds[0] == "3") { note.Timestamp = VistaTimestamp.toUtcFromRdv(flds[1]); } else if (flds[0] == "4") { note.LocalTitle = flds[1]; } else if (flds[0] == "5") { note.Author = new Author("", flds[1], ""); } else if (flds[0] == "6") { fInTextPortion = true; if (!String.IsNullOrEmpty(scannedDoc)) { note.Text += scannedDoc + "\r\n"; scannedDoc = ""; } note.Text += flds[1] + "\r\n"; if (flds[1].StartsWith("STANDARD TITLE")) { string[] parts = StringUtils.split(flds[1], StringUtils.COLON); note.StandardTitle = parts[1].Trim(); } } } Note[] notes = (Note[])lst.ToArray(typeof(Note)); return notes; } internal void addEnterpriseTitles(Note[] notes) { StringDictionary enterpriseTitles = getEnterpriseTitles(); for (int i = 0; i < notes.Length; i++) { if (notes[i].DocumentDefinitionId != null && enterpriseTitles.ContainsKey(notes[i].DocumentDefinitionId)) { notes[i].StandardTitle = enterpriseTitles[notes[i].DocumentDefinitionId]; } } } #endregion #region Discharge Summaries public Note[] getDischargeSummaries(string fromDate, string toDate, int nNotes) { return getDischargeSummaries(cxn.Pid, fromDate, toDate, nNotes); } public Note[] getDischargeSummaries(string dfn, string fromDate, string toDate, int nNotes) { MdoQuery request = buildGetDischargeSummariesRequest(dfn, fromDate, toDate, nNotes); string response = StringUtils.stripInvalidXmlCharacters((string)cxn.query(request)); return toNotesFromDischargeSummaries(response); } internal MdoQuery buildGetDischargeSummariesRequest(string dfn, string fromDate, string toDate, int nNotes) { return VistaUtils.buildReportTextRequest(dfn, fromDate, toDate, nNotes, "OR_DS:DISCHARGE SUMMARY~TIUDCS;ORDV04;57;"); } internal Note[] toNotesFromDischargeSummaries(string response) { if (response == "") { return null; } string[] lines = StringUtils.split(response, StringUtils.CRLF); ArrayList lst = new ArrayList(); Note note = null; for (int i = 0; i < lines.Length; i++) { if (lines[i] == "") { continue; } string[] flds = StringUtils.split(lines[i], StringUtils.CARET); if (flds[1] == "[+]") { lst.Add(note); } else if (flds[0] == "1") { note = new Note(); note.StandardTitle = "DISCHARGE SUMMARY"; note.LocalTitle = "Discharge Summary"; note.Text = VistaUtils.removeCtlChars(note.Text); string[] subflds = StringUtils.split(flds[1], StringUtils.SEMICOLON); if (subflds.Length == 2) { note.SiteId = new SiteId(subflds[1], subflds[0]); } else if (flds[1] != "") { note.SiteId = new SiteId(cxn.DataSource.SiteId.Id, flds[1]); } else { note.SiteId = cxn.DataSource.SiteId; } } else if (flds[0] == "2") { note.AdmitTimestamp = VistaTimestamp.toUtcFromRdv(flds[1]); } else if (flds[0] == "3") { note.DischargeTimestamp = VistaTimestamp.toUtcFromRdv(flds[1]); } else if (flds[0] == "4") { note.Author = new Author("", flds[1], ""); } else if (flds[0] == "5") { note.ApprovedBy = new Author("", flds[1], ""); } else if (flds[0] == "6") { note.Status = flds[1]; } else if (flds[0] == "7") { note.Text += flds[1] + "\r\n"; } } Note[] notes = (Note[])lst.ToArray(typeof(Note)); return notes; } #endregion #region Other Notes public string getCrisisNotes(string fromDate, string toDate, int nrpts) { return getCrisisNotes(cxn.Pid, fromDate, toDate, nrpts); } public string getCrisisNotes(string dfn, string fromDate, string toDate, int nrpts) { MdoQuery request = buildGetCrisisNotesRequest(dfn, fromDate, toDate, nrpts); return (string)cxn.query(request); } public MdoQuery buildGetCrisisNotesRequest(string dfn, string fromDate, string toDate, int nrpts) { return VistaUtils.buildReportTextRequest(dfn, fromDate, toDate, nrpts, "OR_CN:CRISIS NOTES~;;5;"); } public string getAdvanceDirectives(string fromDate, string toDate, int nrpts) { return getAdvanceDirectives(cxn.Pid, fromDate, toDate, nrpts); } public string getAdvanceDirectives(string dfn, string fromDate, string toDate, int nrpts) { MdoQuery request = buildGetAdvanceDirectivesRequest(dfn, fromDate, toDate, nrpts); return (string)cxn.query(request); } public MdoQuery buildGetAdvanceDirectivesRequest(string dfn, string fromDate, string toDate, int nrpts) { return VistaUtils.buildReportTextRequest(dfn, fromDate, toDate, nrpts, "OR_CD:ADVANCE DIRECTIVE~;;25;"); } public string getClinicalWarnings(string fromDate, string toDate, int nrpts) { return getClinicalWarnings(cxn.Pid, fromDate, toDate, nrpts); } public string getClinicalWarnings(string dfn, string fromDate, string toDate, int nrpts) { MdoQuery request = buildGetClinicalWarningsRequest(dfn, fromDate, toDate, nrpts); return (string)cxn.query(request); } public MdoQuery buildGetClinicalWarningsRequest(string dfn, string fromDate, string toDate, int nrpts) { return VistaUtils.buildReportTextRequest(dfn, fromDate, toDate, nrpts, "OR_CW:CLINICAL WARNINGS~;;4;"); } public PatientRecordFlagNote[] getPatientRecordFlagLinkedNotes(string pid, string noteDefTitle, string titleIEN) { MdoQuery request = buildGetPrfLinkedNotes(pid, noteDefTitle, titleIEN); string response = (string)cxn.query(request); return toPrfNotes(response, pid); } internal MdoQuery buildGetPrfLinkedNotes(string pid, string noteDefTitle, string titleIEN) { VistaUtils.CheckRpcParams(pid); VistaUtils.CheckRpcParams(noteDefTitle); VistaUtils.CheckRpcParams(titleIEN); VistaQuery vq = new VistaQuery("TIU GET LINKED PRF NOTES"); vq.addParameter(vq.LITERAL, pid); vq.addParameter(vq.LITERAL, noteDefTitle); vq.addParameter(vq.LITERAL, titleIEN); return vq; } internal PatientRecordFlagNote[] toPrfNotes(string response, string noteIen) { if (StringUtils.isEmpty(response)) { return null; } string[] lines = StringUtils.split(response, StringUtils.CRLF); lines = StringUtils.trimArray(lines); PatientRecordFlagNote[] result = new PatientRecordFlagNote[lines.Length]; for (int i = 0; i < lines.Length; i++) { result[i] = toPrfNote(lines[i]); //result[i].NoteIen = noteIen; } return result; } internal PatientRecordFlagNote toPrfNote(string s) { string[] flds = StringUtils.split(s, StringUtils.CARET); if (flds.Length < 4) { return null; } PatientRecordFlagNote result = new PatientRecordFlagNote(); result.NoteIen = flds[0]; result.ActionName = flds[1]; result.ActionTimestamp = flds[2]; result.DoctorName = flds[3]; return result; } public PatientRecordFlag[] getPrfNoteActions(string ien) { return getPrfNoteActions(ien, cxn.Pid); } public PatientRecordFlag[] getPrfNoteActions(string ien, string dfn) { MdoQuery request = buildGetPrfNoteActions(ien, dfn); string response = (string)cxn.query(request); return toPrfs(response, ien); } internal MdoQuery buildGetPrfNoteActions(string ien, string dfn) { VistaUtils.CheckRpcParams(ien); VistaUtils.CheckRpcParams(dfn); VistaQuery vq = new VistaQuery("TIU GET PRF ACTIONS"); vq.addParameter(vq.LITERAL, ien); vq.addParameter(vq.LITERAL, dfn); return vq; } internal PatientRecordFlag[] toPrfs(string response, string noteIen) { if (StringUtils.isEmpty(response)) { return null; } string[] lines = StringUtils.split(response, StringUtils.CRLF); lines = StringUtils.trimArray(lines); PatientRecordFlag[] result = new PatientRecordFlag[lines.Length]; for (int i = 0; i < lines.Length; i++) { result[i] = toPrf(lines[i]); result[i].NoteId = noteIen; } return result; } internal PatientRecordFlag toPrf(string s) { string[] flds = StringUtils.split(s, StringUtils.CARET); if (flds.Length < 5) { return null; } PatientRecordFlag result = new PatientRecordFlag(); result.Id = flds[1]; result.Name = flds[0]; result.ActionId = flds[3]; result.ActionName = flds[2]; result.ActionTimestamp = VistaTimestamp.toUtcString(flds[4]); return result; } #endregion #region Write Note public bool isConsultNote(string ien) { MdoQuery request = buildIsConsultNoteRequest(ien); string response = (string)cxn.query(request); return (response == "1"); } internal MdoQuery buildIsConsultNoteRequest(string ien) { VistaUtils.CheckRpcParams(ien); VistaQuery vq = new VistaQuery("TIU IS THIS A CONSULT?"); vq.addParameter(vq.LITERAL, ien); return vq; } public bool isSurgeryNote(string ien) { MdoQuery request = buildIsSurgeryNoteRequest(ien); string response = (string)cxn.query(request); return (response == "1"); } internal MdoQuery buildIsSurgeryNoteRequest(string ien) { VistaUtils.CheckRpcParams(ien); VistaQuery vq = new VistaQuery("TIU IS THIS A SURGERY?"); vq.addParameter(vq.LITERAL, ien); return vq; } public bool isPrfNote(string ien) { MdoQuery request = buildIsPrfNoteRequest(ien); string response = (string)cxn.query(request); return (response == "1"); } internal MdoQuery buildIsPrfNoteRequest(string ien) { VistaUtils.CheckRpcParams(ien); VistaQuery vq = new VistaQuery("TIU ISPRF"); vq.addParameter(vq.LITERAL, ien); return vq; } public string getNotePrintName(string ien) { MdoQuery request = buildGetNotePrintNameRequest(ien); string response = (string)cxn.query(request); return response; } internal MdoQuery buildGetNotePrintNameRequest(string ien) { VistaUtils.CheckRpcParams(ien); VistaQuery vq = new VistaQuery("TIU GET PRINT NAME"); vq.addParameter(vq.LITERAL, ien); return vq; } // Why is this not in VistaConsultsDao? public Consult[] getConsultRequestsForPatient(string dfn) { MdoQuery request = buildGetConsultRequestsForPatientRequest(dfn); string response = (string)cxn.query(request); return toConsultsFromConsultRequestsForPatient(response); } internal MdoQuery buildGetConsultRequestsForPatientRequest(string dfn) { VistaUtils.CheckRpcParams(dfn); VistaQuery vq = new VistaQuery("GMRC LIST CONSULT REQUESTS"); vq.addParameter(vq.LITERAL, dfn); return vq; } internal Consult[] toConsultsFromConsultRequestsForPatient(string response) { if (response == "") { return null; } string[] rex = StringUtils.split(response, StringUtils.CRLF); rex = StringUtils.trimArray(rex); int nrex = Convert.ToInt32(rex[0]); Consult[] result = new Consult[nrex]; for (int rsltIdx = 0, rexIdx = 1; rexIdx < rex.Length; rsltIdx++, rexIdx++) { string[] flds = StringUtils.split(rex[rexIdx], StringUtils.CARET); Consult c = new Consult(); c.Id = flds[0]; c.Timestamp = VistaTimestamp.toDateTime(flds[1]); c.Title = flds[2]; c.RequestedProcedure = flds[3]; c.Status = flds[4]; //c.Service = new KeyValuePair<string, string>("", flds[2]); result[rsltIdx] = c; } return result; } public bool checkText(string noteIen) { MdoQuery request = buildCheckTextRequest(noteIen); string response = (string)cxn.query(request); return (response == "1"); } internal MdoQuery buildCheckTextRequest(string noteIen) { VistaUtils.CheckRpcParams(noteIen); VistaQuery vq = new VistaQuery("ORWTIU CHKTXT"); vq.addParameter(vq.LITERAL, noteIen); return vq; } public string wasNoteSaved(string noteIen) { MdoQuery request = buildWasNoteSavedRequest(noteIen); string response = (string)cxn.query(request); return (response == "1" ? "OK" : StringUtils.piece(response,StringUtils.CARET,2)); } internal MdoQuery buildWasNoteSavedRequest(string noteIen) { VistaUtils.CheckRpcParams(noteIen); VistaQuery vq = new VistaQuery("TIU WAS THIS SAVED?"); vq.addParameter(vq.LITERAL, noteIen); return vq; } public string whichSignatureAction(string noteIen) { MdoQuery request = buildWhichSignatureActionRequest(noteIen); string response = (string)cxn.query(request); return response; } internal MdoQuery buildWhichSignatureActionRequest(string noteIen) { VistaUtils.CheckRpcParams(noteIen); VistaQuery vq = new VistaQuery("TIU WHICH SIGNATURE ACTION"); vq.addParameter(vq.LITERAL, noteIen); return vq; } public string isUserAuthorized(string noteIen, string permission) { MdoQuery request = buildIsUserAuthorizedRequest(noteIen, permission); string response = (string)cxn.query(request); return (response == "1" ? "OK" : StringUtils.piece(response,StringUtils.CARET,2)); } internal MdoQuery buildIsUserAuthorizedRequest(string noteIen, string permission) { VistaUtils.CheckRpcParams(noteIen); if (String.IsNullOrEmpty(permission)) { throw new NullOrEmptyParamException("permission"); } VistaQuery vq = new VistaQuery("TIU AUTHORIZATION"); vq.addParameter(vq.LITERAL, noteIen); vq.addParameter(vq.LITERAL, permission); return vq; } public bool hasAuthorSignedNote(string noteIen, string duz) { MdoQuery request = buildAuthorSignedNoteRequest(noteIen, duz); string response = (string)cxn.query(request); return (response == "1"); } internal MdoQuery buildAuthorSignedNoteRequest(string noteIen, string duz) { VistaUtils.CheckRpcParams(noteIen); if (!VistaUtils.isWellFormedDuz(duz)) { throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "Invalid DUZ"); } VistaQuery vq = new VistaQuery("TIU HAS AUTHOR SIGNED?"); vq.addParameter(vq.LITERAL, noteIen); vq.addParameter(vq.LITERAL, duz); return vq; } internal string signNote(string noteIen, string esig) { MdoQuery request = buildSignNoteRequest(noteIen, esig); string response = (string)cxn.query(request); return (response == "0" ? "OK" : StringUtils.piece(response,StringUtils.CARET,2)); } internal MdoQuery buildSignNoteRequest(string noteIen, string esig) { VistaUtils.CheckRpcParams(noteIen); if (String.IsNullOrEmpty(esig)) { throw new NullOrEmptyParamException("esig"); } VistaQuery vq = new VistaQuery("TIU SIGN RECORD"); vq.addParameter(vq.LITERAL, noteIen); //DP 5/23/2011 Added guard clause to this query builder methods so it will not save an //encrypted string in the mock connection file. Console.WriteLine("VistaNoteDao buildSignNoteRequest " + esig); if (cxn.GetType().Name != "MockConnection") { vq.addEncryptedParameter(vq.LITERAL, esig); } else { vq.addParameter(vq.LITERAL, esig); } //vq.addParameter(vq.LITERAL, esig); return vq; } internal KeyValuePair<int, string> toSignedNoteResponse(string response) { if (response == "0") { return new KeyValuePair<int, string>(0, ""); } else { string[] flds = StringUtils.split(response, StringUtils.CARET); return new KeyValuePair<int, string>(Convert.ToInt32(flds[0]), flds[1].Trim()); } } internal bool userHasUnresolvedConsults(string dfn) { MdoQuery request = buildUserHasUnresolvedConsultsRequest(dfn); string response = (string)cxn.query(request); return (StringUtils.piece(response,StringUtils.CARET,1) == "1"); } internal MdoQuery buildUserHasUnresolvedConsultsRequest(string dfn) { VistaUtils.CheckRpcParams(dfn); VistaQuery vq = new VistaQuery("ORQQCN UNRESOLVED"); vq.addParameter(vq.LITERAL, dfn); return vq; } public bool isOneVisitNote(string docDefId, string dfn, Encounter encounter) { return isOneVisitNote(docDefId,dfn,VistaUtils.getVisitString(encounter)); } public bool isOneVisitNote(string docDefId, string dfn, string visitStr) { MdoQuery request = buildIsOneVisitNoteRequest(docDefId, dfn, visitStr); string response = (string)cxn.query(request); return (response == "1"); } internal MdoQuery buildIsOneVisitNoteRequest(string docDefId, string dfn, string visitStr) { VistaUtils.CheckRpcParams(docDefId); VistaUtils.CheckRpcParams(dfn); VistaUtils.CheckVisitString(visitStr); VistaQuery vq = new VistaQuery("TIU ONE VISIT NOTE?"); vq.addParameter(vq.LITERAL, docDefId); vq.addParameter(vq.LITERAL, dfn); vq.addParameter(vq.LITERAL, visitStr); return vq; } internal bool patch175Installed() { return cxn.hasPatch("TIU*1.0*175"); } public string getNoteEncounterString(string noteIEN) { MdoQuery request = buildGetNoteEncounterStringRequest(noteIEN); string response = (string)cxn.query(request); return response; } internal MdoQuery buildGetNoteEncounterStringRequest(string noteIEN) { VistaUtils.CheckRpcParams(noteIEN); VistaQuery vq = new VistaQuery("ORWPCE NOTEVSTR"); vq.addParameter(vq.LITERAL, noteIEN); return vq; } public string buildInpatientNoteEncounterString(Patient patient) { if (patient.Location == null || !VistaUtils.isWellFormedIen(patient.Location.Id)) { throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "Missing patient location data"); } if (!DateUtils.isWellFormedUtcDateTime(patient.AdmitTimestamp)) { throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, "Missing admit timestamp"); } return patient.Location.Id + ';' + VistaTimestamp.fromUtcString(patient.AdmitTimestamp) + ";H"; } internal bool userRequiresCosignature(string duz) { return userRequiresCosignatureForNote(duz, "3"); } internal bool userRequiresCosignatureForNote(string duz, string noteDefinitionIen) { MdoQuery request = buildRequiresCosignatureRequest(duz, noteDefinitionIen); string response = (string)cxn.query(request); return (response == "1"); } internal MdoQuery buildRequiresCosignatureRequest(string duz, string noteIEN) { VistaUtils.CheckRpcParams(duz); VistaUtils.CheckRpcParams(noteIEN); VistaQuery vq = new VistaQuery("TIU REQUIRES COSIGNATURE"); vq.addParameter(vq.LITERAL, noteIEN); vq.addParameter(vq.LITERAL, "0"); vq.addParameter(vq.LITERAL, duz); return vq; } /// <summary> /// Checks to see if this user needs a cosigner for this note. /// </summary> /// <param name="userDuz"></param> /// <param name="noteDefinitionIen"></param> /// <param name="authorDuz"></param> /// <returns></returns> public bool isCosignerRequired(string userDuz, string noteDefinitionIen, string authorDuz = null) { if (userRequiresCosignature(userDuz)) { return true; } if (userRequiresCosignatureForNote(userDuz, noteDefinitionIen)) { return true; } if (String.IsNullOrEmpty(authorDuz)) { return false; } if (userRequiresCosignature(authorDuz)) { return true; } if (userRequiresCosignatureForNote(authorDuz, noteDefinitionIen)) { return true; } return false; } internal string okToCreateNote(Note note, string dfn, Encounter encounter) { if (isSurgeryNote(note.DocumentDefinitionId)) { return "Cannot create new surgery note at this time"; } if (isOneVisitNote(note.DocumentDefinitionId, dfn, VistaUtils.getVisitString(encounter))) { string msg = "There is already a " + note.LocalTitle + " note for this visit. \r\n" + "Only ONE record of this type per Visit is allowed...\r\n\r\n" + "You can addend the existing record."; return msg; } if (isConsultNote(note.DocumentDefinitionId) && String.IsNullOrEmpty(note.ConsultId)) { return "Missing consult IEN"; } if (!note.IsAddendum) { if (isPrfNote(note.DocumentDefinitionId) && String.IsNullOrEmpty(note.PrfId)) { return "Missing PRF IEN"; } bool fCosigner = false; if (note.Author.Id == cxn.Uid) { fCosigner = isCosignerRequired(cxn.Uid, note.DocumentDefinitionId); } else { fCosigner = isCosignerRequired(cxn.Uid, note.DocumentDefinitionId, note.Author.Id); } if (fCosigner && (note.Cosigner == null || String.IsNullOrEmpty(note.Cosigner.Id))) { return "Missing cosigner"; } } return "OK"; } public string createNote(Encounter encounter, Note note) { return createNote(cxn.Pid, encounter, note); } internal string createNote(string dfn, Encounter encounter, Note note) { MdoQuery request = buildCreateNoteRequest(dfn, encounter, note); string response = (string)cxn.query(request); return response; } internal MdoQuery buildCreateNoteRequest(string dfn, Encounter encounter, Note note) { VistaQuery vq = new VistaQuery("TIU CREATE RECORD"); vq.addParameter(vq.LITERAL, dfn); vq.addParameter(vq.LITERAL, note.DocumentDefinitionId); //VistA documentation says it will accept an encounter timestamp here, but //CPRS hard codes a blank vq.addParameter(vq.LITERAL, ""); //VistA documentation says encounter location IEN next, but CPRS hard codes a blank vq.addParameter(vq.LITERAL, ""); //VistA documentation says encounter IEN next, but CPRS hard codes a blank vq.addParameter(vq.LITERAL, ""); string vistaTS = VistaTimestamp.Now; DictionaryHashList lst = new DictionaryHashList(); lst.Add("1202", note.Author.Id); lst.Add("1301", note.Timestamp); lst.Add("1205", encounter.LocationId); if (note.Cosigner != null) { lst.Add("1208", note.Cosigner.Id); } if (note.ConsultId != "") { lst.Add("1405", note.ConsultId + ";GMR(123,"); } string subject = (note.Subject == null) ? "" : note.Subject; if (subject.Length > 80) { subject = subject.Substring(0,80); } lst.Add("1701", subject); if (!StringUtils.isEmpty(note.ParentId)) { lst.Add("2101", note.ParentId); } vq.addParameter(vq.LIST, lst); string timestamp = VistaTimestamp.fromUtcString(encounter.Timestamp); timestamp = VistaTimestamp.trimZeroes(timestamp); string visitStr = encounter.LocationId + ';' + timestamp + ';' + encounter.Type; vq.addParameter(vq.LITERAL, visitStr); //Vista documentation says it accepts 1 or 0, but //CPRS hard codes a 1 to suppress commit logic vq.addParameter(vq.LITERAL, "1"); //Vista documentation adds this param, but CPRS omits it //if (noAsave) //{ // vq.addParameter(vq.LITERAL, "1"); //} return vq; } internal string updateNote(Note note) { return updateNote(cxn.Pid, note); } internal string updateNote(string dfn, Note note) { MdoQuery request = buildUpdateNoteRequest(dfn, note); string response = (string)cxn.query(request); return response; } internal MdoQuery buildUpdateNoteRequest(string dfn, Note note) { VistaQuery vq = new VistaQuery("TIU UPDATE RECORD"); vq.addParameter(vq.LITERAL, note.Id); DictionaryHashList lst = new DictionaryHashList(); lst.Add(".01", note.DocumentDefinitionId); lst.Add("1202", note.Author.Id); if (note.Cosigner != null) { lst.Add("1208", note.Cosigner.Id); } if (!StringUtils.isEmpty(note.ConsultId)) { lst.Add("1405", note.ConsultId + ";GMR(123,"); } lst.Add("1301", note.Timestamp); string subject = (note.Subject == null) ? "" : note.Subject; if (subject.Length > 80) { subject = subject.Substring(0, 80); } lst.Add("1701", subject); if (!StringUtils.isEmpty(note.ParentId)) { lst.Add("2101", note.ParentId); } if (!StringUtils.isEmpty(note.ProcId)) { lst.Add("70201", note.ProcId); } if (!StringUtils.isEmpty(note.ProcTimestamp)) { lst.Add("70202", VistaTimestamp.fromUtcString(note.ProcTimestamp)); } vq.addParameter(vq.LIST, lst); return vq; } internal string lockNote(string noteIEN) { MdoQuery request = buildLockNoteRequest(noteIEN); string response = (string)cxn.query(request); return VistaUtils.errMsgOrZero(response); } internal MdoQuery buildLockNoteRequest(string noteIEN) { VistaQuery vq = new VistaQuery("TIU LOCK RECORD"); vq.addParameter(vq.LITERAL, noteIEN); return vq; } internal void unlockNote(string noteIEN) { MdoQuery request = buildUnlockNoteRequest(noteIEN); string response = (string)cxn.query(request); } internal MdoQuery buildUnlockNoteRequest(string noteIEN) { VistaQuery vq = new VistaQuery("TIU UNLOCK RECORD"); vq.addParameter(vq.LITERAL, noteIEN); return vq; } internal ArrayList toLines(string text) { int maxCharsPerLine = 80; ArrayList lineLst = new ArrayList(); string[] lines = StringUtils.split(text, "|"); for (int i = 0; i < lines.Length; i++) { string thisLine = lines[i]; if (thisLine == "") { lineLst.Add(thisLine); continue; } while (thisLine.Length > maxCharsPerLine) { int idx = StringUtils.getFirstWhiteSpaceAfter(thisLine, maxCharsPerLine); if (idx == -1) { idx = maxCharsPerLine; } lineLst.Add(thisLine.Substring(0, idx)); while (StringUtils.isWhiteSpace(thisLine[idx])) { idx++; } thisLine = thisLine.Substring(idx); } if (thisLine.Length > 0) { lineLst.Add(thisLine); } } return lineLst; } internal NoteResult setNoteText(string noteIEN, string text, bool fSuppressCommit) { int maxCharsPerLine = 80; ArrayList lineLst = new ArrayList(); string[] lines = StringUtils.split(text, "|"); for (int i = 0; i < lines.Length; i++) { string thisLine = lines[i].TrimEnd(); if (thisLine == "") { lineLst.Add(thisLine); continue; } while (thisLine.Length > maxCharsPerLine) { int idx = StringUtils.getFirstWhiteSpaceAfter(thisLine, maxCharsPerLine); if (idx == -1) { idx = maxCharsPerLine; } lineLst.Add(thisLine.Substring(0, idx)); while (idx < thisLine.Length && StringUtils.isWhiteSpace(thisLine[idx])) { idx++; } thisLine = thisLine.Substring(idx); } if (thisLine.Length > 0) { lineLst.Add(thisLine); } } int npages = (lineLst.Count / 300) + 1; int nlinesPerPage = 0; int pagenum = 1; string key = ""; DictionaryHashList argList = new DictionaryHashList(); for (int linenum = 0; linenum < lineLst.Count; linenum++) { key = "\"TEXT\"," + (linenum + 1) + ",0"; string value = StringUtils.filteredString((string)lineLst[linenum]); argList.Add(key, value); nlinesPerPage++; if (nlinesPerPage == 300) { argList.Add("\"HDR\"", pagenum.ToString() + '^' + npages.ToString() + '^'); string rtn = writeText("TIU SET DOCUMENT TEXT", noteIEN, argList, fSuppressCommit); rtn = resultOK(rtn, noteIEN, pagenum, npages); if (rtn != "OK") { throw new Exception(rtn); } pagenum++; nlinesPerPage = 0; } } if (nlinesPerPage > 0) { argList.Add("\"HDR\"", pagenum.ToString() + '^' + npages.ToString()); string rtn = writeText("TIU SET DOCUMENT TEXT", noteIEN, argList, fSuppressCommit); rtn = resultOK(rtn, noteIEN, pagenum, npages); if (rtn != "OK") { throw new Exception(rtn); } pagenum++; } return new NoteResult(noteIEN, npages, pagenum); } internal string writeText(string rpcName, string noteIen, DictionaryHashList lst, bool fSuppressCommit) { MdoQuery request = buildWriteTextRequest(rpcName, noteIen, lst, fSuppressCommit); string response = (string)cxn.query(request); return response; } internal MdoQuery buildWriteTextRequest(string rpcName, string noteIEN, DictionaryHashList lst, bool fSuppressCommit) { VistaQuery vq = new VistaQuery(rpcName); vq.addParameter(vq.LITERAL, noteIEN); vq.addParameter(vq.LIST, lst); vq.addParameter(vq.LITERAL, "0"); return vq; } internal string resultOK(string s, string noteIEN, int lastPageSent, int totalPages) { try { string[] flds = StringUtils.split(s, StringUtils.CARET); if (flds[0] == "0") { return flds[3]; } if (flds[0] != noteIEN) { return "IEN mismatch"; } if (Convert.ToInt16(flds[1]) != lastPageSent) { return "Last page received not last page sent"; } if (Convert.ToInt16(flds[2]) != totalPages) { return "Total pages mismatch"; } } catch (Exception ex) { return ex.Message; } return "OK"; } public NoteResult writeNote( string noteDefinitionIen, Encounter encounter, string text, string authorDUZ, string cosignerDUZ = null, string consultIEN = null, string prfIEN = null) { return writeNote(cxn.Pid, noteDefinitionIen, encounter, text, authorDUZ, cosignerDUZ, consultIEN, prfIEN); } public NoteResult writeNote( string dfn, string noteDefinitionIen, Encounter encounter, string text, string authorDUZ, string cosignerDUZ = null, string consultIEN = null, string prfIEN = null) { VistaUtils.CheckRpcParams(dfn); VistaUtils.CheckRpcParams(noteDefinitionIen); if (encounter == null) { throw new NullOrEmptyParamException("encounter"); } if (String.IsNullOrEmpty(text)) { throw new NullOrEmptyParamException("text"); } if (!String.IsNullOrEmpty(consultIEN)) { VistaUtils.CheckRpcParams(consultIEN); } if (!String.IsNullOrEmpty(prfIEN)) { VistaUtils.CheckRpcParams(prfIEN); } Note note = new Note(); note.DocumentDefinitionId = noteDefinitionIen; note.Author = new Author(authorDUZ,"",""); VistaToolsDao toolsDao = new VistaToolsDao(cxn); note.Timestamp = VistaTimestamp.fromUtcString(toolsDao.getTimestamp()); note.ConsultId = consultIEN; note.IsAddendum = false; note.PrfId = prfIEN; if (!String.IsNullOrEmpty(cosignerDUZ)) { VistaUtils.CheckRpcParams(cosignerDUZ); note.Cosigner = new Author(cosignerDUZ, "", ""); } note.Text = text; string s = okToCreateNote(note, dfn, encounter); if (s != "OK") { throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, s); } if (!String.IsNullOrEmpty(consultIEN)) { VistaConsultDao consultDao = new VistaConsultDao(cxn); string orderIEN = consultDao.getOrderNumberForConsult(consultIEN); if (orderIEN == "") { // Do nothing - CPRS assumes it's an Interfacility Consult } else { VistaOrdersDao orderDao = new VistaOrdersDao(cxn); s = orderDao.lockOrder(orderIEN); if (s != "OK") { throw new RecordLockingException("Unable to lock order: " + s); } } } string noteIEN = createNote(dfn, encounter, note); if (noteIEN.StartsWith("0^")) { throw new MdoException(MdoExceptionCode.VISTA_FAULT, StringUtils.piece(noteIEN,StringUtils.CARET,2)); } s = lockNote(noteIEN); if (s != "OK") { throw new RecordLockingException("Unable to lock note: " + s); } note.Id = noteIEN; s = updateNote(dfn, note); if (s != noteIEN) { throw new MdoException(MdoExceptionCode.VISTA_FAULT, "Error updating note " + noteIEN + ": expected IEN, got " + s); } NoteResult result = null; try { result = setNoteText(noteIEN, text, false); } catch (IndexOutOfRangeException ie) { string msg = "setNoteText: " + ie.Message + "\r\n" + ie.StackTrace; throw new MdoException(MdoExceptionCode.ARGUMENT_INVALID, msg); } if (!String.IsNullOrEmpty(prfIEN)) { //Handle PRF PatientRecordFlag[] flags = getPrfNoteActions(noteIEN); PatientRecordFlag thisFlag = getFlag(flags, prfIEN); if (thisFlag == null) { throw new MdoException(MdoExceptionCode.DATA_INVALID, "Unable to link note " + noteIEN + " to PRF: invalid IEN (" + prfIEN + ")"); } s = linkNoteToFlag(noteIEN, thisFlag.Id, thisFlag.ActionId); if (s != "OK") { throw new MdoException(MdoExceptionCode.VISTA_FAULT, "Unable to link note " + noteIEN + " to PRF " + prfIEN); } } return result; } internal PatientRecordFlag getFlag(PatientRecordFlag[] flags, string prfIEN) { for (int i = 0; i < flags.Length; i++) { if (flags[i].Id == prfIEN) { return flags[i]; } } return null; } internal string linkNoteToFlag(string noteIEN, string flagIEN, string actionIEN) { MdoQuery request = buildLinkNoteToFlagRequest(noteIEN, flagIEN, actionIEN); string response = (string)cxn.query(request); return (response == "1" ? "OK" : StringUtils.piece(response,StringUtils.CARET,2)); } internal MdoQuery buildLinkNoteToFlagRequest(string noteIEN, string flagIEN, string actionIEN) { VistaQuery vq = new VistaQuery(); vq.addParameter(vq.LITERAL, noteIEN); vq.addParameter(vq.LITERAL, flagIEN); vq.addParameter(vq.LITERAL, actionIEN); vq.addParameter(vq.LITERAL, cxn.Pid); return vq; } public string signNote(string noteIEN, string DUZ, string esig) { VistaUtils.CheckRpcParams(noteIEN); VistaUtils.CheckRpcParams(DUZ); if (String.IsNullOrEmpty(esig)) { throw new NullOrEmptyParamException("esig"); } if (!checkText(noteIEN)) { return "Note contains no text"; } string s = wasNoteSaved(noteIEN); if (s != "OK") { return s; } string permission = whichSignatureAction(noteIEN); if (permission != "SIGNATURE") { return "Invalid signature action: expected SIGNATURE, got " + permission; } s = isUserAuthorized(noteIEN, permission); if (s != "OK") { return "User not authorized to sign note: " + s; } if (!hasAuthorSignedNote(noteIEN, DUZ)) { return "Author has not signed note"; } VistaUserDao userDao = new VistaUserDao(cxn); if (!userDao.isValidEsig(esig)) { return "Invalid signature"; } return signNote(noteIEN,esig); } public string closeNote(string noteIEN, string consultIEN) { VistaUtils.CheckRpcParams(noteIEN); unlockNote(noteIEN); string text = getNoteText(noteIEN); if (!String.IsNullOrEmpty(consultIEN)) { VistaUtils.CheckRpcParams(consultIEN); VistaConsultDao consultDao = new VistaConsultDao(cxn); string orderIEN = consultDao.getOrderNumberForConsult(consultIEN); if (orderIEN == "") { // Do nothing - CPRS assumes it's an Interfacility Consult } else { VistaOrdersDao ordersDao = new VistaOrdersDao(cxn); if (!ordersDao.unlockOrder(consultIEN)) { throw new RecordLockingException("Unable to unlock consult " + consultIEN); } } } string permission = isUserAuthorized(noteIEN, "VIEW"); if (permission != "OK") // Note is signed but unviewable (weird) { return "OK"; } return text; } #region HelperMethods public string getEnterpriseTitle(string id) { var result = getEnterpriseTitles(); return result[id]; } public string getEnterpriseId(string title) { String[] enterpriseTitles; var result = getEnterpriseTitles(); enterpriseTitles = new String[result.Count]; Dictionary<string, string> reverseDict = new Dictionary<string, string>(); foreach (DictionaryEntry kv in result) { reverseDict.Add(kv.Value.ToString(), kv.Key.ToString()); }; return reverseDict[title]; } #endregion //HelperMethods #endregion } }
// Copyright (c) 1995-2009 held by the author(s). 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 names of the Naval Postgraduate School (NPS) // Modeling Virtual Environments and Simulation (MOVES) Institute // (http://www.nps.edu and http://www.MovesInstitute.org) // nor the names of its contributors may be used to endorse or // promote products derived from this software without specific // prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS // AS IS AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS // FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE // COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, // INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, // BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; // LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT // LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN // ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE // POSSIBILITY OF SUCH DAMAGE. // // Copyright (c) 2008, MOVES Institute, Naval Postgraduate School. All // rights reserved. This work is licensed under the BSD open source license, // available at https://www.movesinstitute.org/licenses/bsd.html // // Author: DMcG // Modified for use with C#: // - Peter Smith (Naval Air Warfare Center - Training Systems Division) // - Zvonko Bostjancic (Blubit d.o.o. - zvonko.bostjancic@blubit.si) using System; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Text; using System.Xml.Serialization; using OpenDis.Core; namespace OpenDis.Dis1995 { /// <summary> /// Section 5.3.8.1. Detailed information about a radio transmitter. This PDU requires manually written code to complete. /// </summary> [Serializable] [XmlRoot] [XmlInclude(typeof(RadioEntityType))] [XmlInclude(typeof(Vector3Double))] [XmlInclude(typeof(ModulationType))] [XmlInclude(typeof(Vector3Float))] [XmlInclude(typeof(Vector3Float))] public partial class TransmitterPdu : RadioCommunicationsPdu, IEquatable<TransmitterPdu> { /// <summary> /// linear accelleration of entity /// </summary> private RadioEntityType _radioEntityType = new RadioEntityType(); /// <summary> /// transmit state /// </summary> private byte _transmitState; /// <summary> /// input source /// </summary> private byte _inputSource; /// <summary> /// padding /// </summary> private ushort _padding1; /// <summary> /// Location of antenna /// </summary> private Vector3Double _antennaLocation = new Vector3Double(); /// <summary> /// relative location of antenna /// </summary> private Vector3Double _relativeAntennaLocation = new Vector3Double(); /// <summary> /// atenna pattern type /// </summary> private ushort _antennaPatternType; /// <summary> /// atenna pattern length /// </summary> private ushort _antennaPatternCount; /// <summary> /// frequency /// </summary> private double _frequency; /// <summary> /// transmit frequency Bandwidth /// </summary> private float _transmitFrequencyBandwidth; /// <summary> /// transmission power /// </summary> private float _power; /// <summary> /// modulation /// </summary> private ModulationType _modulationType = new ModulationType(); /// <summary> /// crypto system enumeration /// </summary> private ushort _cryptoSystem; /// <summary> /// crypto system key identifer /// </summary> private ushort _cryptoKeyId; /// <summary> /// how many modulation parameters we have /// </summary> private byte _modulationParameterCount; /// <summary> /// padding2 /// </summary> private ushort _padding2; /// <summary> /// padding3 /// </summary> private byte _padding3; /// <summary> /// variable length list of modulation parameters /// </summary> private List<Vector3Float> _modulationParametersList = new List<Vector3Float>(); /// <summary> /// variable length list of antenna pattern records /// </summary> private List<Vector3Float> _antennaPatternList = new List<Vector3Float>(); /// <summary> /// Initializes a new instance of the <see cref="TransmitterPdu"/> class. /// </summary> public TransmitterPdu() { PduType = (byte)25; } /// <summary> /// Implements the operator !=. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if operands are not equal; otherwise, <c>false</c>. /// </returns> public static bool operator !=(TransmitterPdu left, TransmitterPdu right) { return !(left == right); } /// <summary> /// Implements the operator ==. /// </summary> /// <param name="left">The left operand.</param> /// <param name="right">The right operand.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public static bool operator ==(TransmitterPdu left, TransmitterPdu right) { if (object.ReferenceEquals(left, right)) { return true; } if (((object)left == null) || ((object)right == null)) { return false; } return left.Equals(right); } public override int GetMarshalledSize() { int marshalSize = 0; marshalSize = base.GetMarshalledSize(); marshalSize += this._radioEntityType.GetMarshalledSize(); // this._radioEntityType marshalSize += 1; // this._transmitState marshalSize += 1; // this._inputSource marshalSize += 2; // this._padding1 marshalSize += this._antennaLocation.GetMarshalledSize(); // this._antennaLocation marshalSize += this._relativeAntennaLocation.GetMarshalledSize(); // this._relativeAntennaLocation marshalSize += 2; // this._antennaPatternType marshalSize += 2; // this._antennaPatternCount marshalSize += 8; // this._frequency marshalSize += 4; // this._transmitFrequencyBandwidth marshalSize += 4; // this._power marshalSize += this._modulationType.GetMarshalledSize(); // this._modulationType marshalSize += 2; // this._cryptoSystem marshalSize += 2; // this._cryptoKeyId marshalSize += 1; // this._modulationParameterCount marshalSize += 2; // this._padding2 marshalSize += 1; // this._padding3 for (int idx = 0; idx < this._modulationParametersList.Count; idx++) { Vector3Float listElement = (Vector3Float)this._modulationParametersList[idx]; marshalSize += listElement.GetMarshalledSize(); } for (int idx = 0; idx < this._antennaPatternList.Count; idx++) { Vector3Float listElement = (Vector3Float)this._antennaPatternList[idx]; marshalSize += listElement.GetMarshalledSize(); } return marshalSize; } /// <summary> /// Gets or sets the linear accelleration of entity /// </summary> [XmlElement(Type = typeof(RadioEntityType), ElementName = "radioEntityType")] public RadioEntityType RadioEntityType { get { return this._radioEntityType; } set { this._radioEntityType = value; } } /// <summary> /// Gets or sets the transmit state /// </summary> [XmlElement(Type = typeof(byte), ElementName = "transmitState")] public byte TransmitState { get { return this._transmitState; } set { this._transmitState = value; } } /// <summary> /// Gets or sets the input source /// </summary> [XmlElement(Type = typeof(byte), ElementName = "inputSource")] public byte InputSource { get { return this._inputSource; } set { this._inputSource = value; } } /// <summary> /// Gets or sets the padding /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "padding1")] public ushort Padding1 { get { return this._padding1; } set { this._padding1 = value; } } /// <summary> /// Gets or sets the Location of antenna /// </summary> [XmlElement(Type = typeof(Vector3Double), ElementName = "antennaLocation")] public Vector3Double AntennaLocation { get { return this._antennaLocation; } set { this._antennaLocation = value; } } /// <summary> /// Gets or sets the relative location of antenna /// </summary> [XmlElement(Type = typeof(Vector3Double), ElementName = "relativeAntennaLocation")] public Vector3Double RelativeAntennaLocation { get { return this._relativeAntennaLocation; } set { this._relativeAntennaLocation = value; } } /// <summary> /// Gets or sets the atenna pattern type /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "antennaPatternType")] public ushort AntennaPatternType { get { return this._antennaPatternType; } set { this._antennaPatternType = value; } } /// <summary> /// Gets or sets the atenna pattern length /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getantennaPatternCount method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(ushort), ElementName = "antennaPatternCount")] public ushort AntennaPatternCount { get { return this._antennaPatternCount; } set { this._antennaPatternCount = value; } } /// <summary> /// Gets or sets the frequency /// </summary> [XmlElement(Type = typeof(double), ElementName = "frequency")] public double Frequency { get { return this._frequency; } set { this._frequency = value; } } /// <summary> /// Gets or sets the transmit frequency Bandwidth /// </summary> [XmlElement(Type = typeof(float), ElementName = "transmitFrequencyBandwidth")] public float TransmitFrequencyBandwidth { get { return this._transmitFrequencyBandwidth; } set { this._transmitFrequencyBandwidth = value; } } /// <summary> /// Gets or sets the transmission power /// </summary> [XmlElement(Type = typeof(float), ElementName = "power")] public float Power { get { return this._power; } set { this._power = value; } } /// <summary> /// Gets or sets the modulation /// </summary> [XmlElement(Type = typeof(ModulationType), ElementName = "modulationType")] public ModulationType ModulationType { get { return this._modulationType; } set { this._modulationType = value; } } /// <summary> /// Gets or sets the crypto system enumeration /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "cryptoSystem")] public ushort CryptoSystem { get { return this._cryptoSystem; } set { this._cryptoSystem = value; } } /// <summary> /// Gets or sets the crypto system key identifer /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "cryptoKeyId")] public ushort CryptoKeyId { get { return this._cryptoKeyId; } set { this._cryptoKeyId = value; } } /// <summary> /// Gets or sets the how many modulation parameters we have /// </summary> /// <remarks> /// Note that setting this value will not change the marshalled value. The list whose length this describes is used for that purpose. /// The getmodulationParameterCount method will also be based on the actual list length rather than this value. /// The method is simply here for completeness and should not be used for any computations. /// </remarks> [XmlElement(Type = typeof(byte), ElementName = "modulationParameterCount")] public byte ModulationParameterCount { get { return this._modulationParameterCount; } set { this._modulationParameterCount = value; } } /// <summary> /// Gets or sets the padding2 /// </summary> [XmlElement(Type = typeof(ushort), ElementName = "padding2")] public ushort Padding2 { get { return this._padding2; } set { this._padding2 = value; } } /// <summary> /// Gets or sets the padding3 /// </summary> [XmlElement(Type = typeof(byte), ElementName = "padding3")] public byte Padding3 { get { return this._padding3; } set { this._padding3 = value; } } /// <summary> /// Gets the variable length list of modulation parameters /// </summary> [XmlElement(ElementName = "modulationParametersListList", Type = typeof(List<Vector3Float>))] public List<Vector3Float> ModulationParametersList { get { return this._modulationParametersList; } } /// <summary> /// Gets the variable length list of antenna pattern records /// </summary> [XmlElement(ElementName = "antennaPatternListList", Type = typeof(List<Vector3Float>))] public List<Vector3Float> AntennaPatternList { get { return this._antennaPatternList; } } /// <summary> /// Automatically sets the length of the marshalled data, then calls the marshal method. /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> public override void MarshalAutoLengthSet(DataOutputStream dos) { // Set the length prior to marshalling data this.Length = (ushort)this.GetMarshalledSize(); this.Marshal(dos); } /// <summary> /// Marshal the data to the DataOutputStream. Note: Length needs to be set before calling this method /// </summary> /// <param name="dos">The DataOutputStream instance to which the PDU is marshaled.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Marshal(DataOutputStream dos) { base.Marshal(dos); if (dos != null) { try { this._radioEntityType.Marshal(dos); dos.WriteUnsignedByte((byte)this._transmitState); dos.WriteUnsignedByte((byte)this._inputSource); dos.WriteUnsignedShort((ushort)this._padding1); this._antennaLocation.Marshal(dos); this._relativeAntennaLocation.Marshal(dos); dos.WriteUnsignedShort((ushort)this._antennaPatternType); dos.WriteUnsignedShort((ushort)this._antennaPatternList.Count); dos.WriteDouble((double)this._frequency); dos.WriteFloat((float)this._transmitFrequencyBandwidth); dos.WriteFloat((float)this._power); this._modulationType.Marshal(dos); dos.WriteUnsignedShort((ushort)this._cryptoSystem); dos.WriteUnsignedShort((ushort)this._cryptoKeyId); dos.WriteUnsignedByte((byte)this._modulationParametersList.Count); dos.WriteUnsignedShort((ushort)this._padding2); dos.WriteUnsignedByte((byte)this._padding3); for (int idx = 0; idx < this._modulationParametersList.Count; idx++) { Vector3Float aVector3Float = (Vector3Float)this._modulationParametersList[idx]; aVector3Float.Marshal(dos); } for (int idx = 0; idx < this._antennaPatternList.Count; idx++) { Vector3Float aVector3Float = (Vector3Float)this._antennaPatternList[idx]; aVector3Float.Marshal(dos); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Unmarshal(DataInputStream dis) { base.Unmarshal(dis); if (dis != null) { try { this._radioEntityType.Unmarshal(dis); this._transmitState = dis.ReadUnsignedByte(); this._inputSource = dis.ReadUnsignedByte(); this._padding1 = dis.ReadUnsignedShort(); this._antennaLocation.Unmarshal(dis); this._relativeAntennaLocation.Unmarshal(dis); this._antennaPatternType = dis.ReadUnsignedShort(); this._antennaPatternCount = dis.ReadUnsignedShort(); this._frequency = dis.ReadDouble(); this._transmitFrequencyBandwidth = dis.ReadFloat(); this._power = dis.ReadFloat(); this._modulationType.Unmarshal(dis); this._cryptoSystem = dis.ReadUnsignedShort(); this._cryptoKeyId = dis.ReadUnsignedShort(); this._modulationParameterCount = dis.ReadUnsignedByte(); this._padding2 = dis.ReadUnsignedShort(); this._padding3 = dis.ReadUnsignedByte(); for (int idx = 0; idx < this.ModulationParameterCount; idx++) { Vector3Float anX = new Vector3Float(); anX.Unmarshal(dis); this._modulationParametersList.Add(anX); } for (int idx = 0; idx < this.AntennaPatternCount; idx++) { Vector3Float anX = new Vector3Float(); anX.Unmarshal(dis); this._antennaPatternList.Add(anX); } } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } } /// <summary> /// This allows for a quick display of PDU data. The current format is unacceptable and only used for debugging. /// This will be modified in the future to provide a better display. Usage: /// pdu.GetType().InvokeMember("Reflection", System.Reflection.BindingFlags.InvokeMethod, null, pdu, new object[] { sb }); /// where pdu is an object representing a single pdu and sb is a StringBuilder. /// Note: The supplied Utilities folder contains a method called 'DecodePDU' in the PDUProcessor Class that provides this functionality /// </summary> /// <param name="sb">The StringBuilder instance to which the PDU is written to.</param> [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Due to ignoring errors.")] public override void Reflection(StringBuilder sb) { sb.AppendLine("<TransmitterPdu>"); base.Reflection(sb); try { sb.AppendLine("<radioEntityType>"); this._radioEntityType.Reflection(sb); sb.AppendLine("</radioEntityType>"); sb.AppendLine("<transmitState type=\"byte\">" + this._transmitState.ToString(CultureInfo.InvariantCulture) + "</transmitState>"); sb.AppendLine("<inputSource type=\"byte\">" + this._inputSource.ToString(CultureInfo.InvariantCulture) + "</inputSource>"); sb.AppendLine("<padding1 type=\"ushort\">" + this._padding1.ToString(CultureInfo.InvariantCulture) + "</padding1>"); sb.AppendLine("<antennaLocation>"); this._antennaLocation.Reflection(sb); sb.AppendLine("</antennaLocation>"); sb.AppendLine("<relativeAntennaLocation>"); this._relativeAntennaLocation.Reflection(sb); sb.AppendLine("</relativeAntennaLocation>"); sb.AppendLine("<antennaPatternType type=\"ushort\">" + this._antennaPatternType.ToString(CultureInfo.InvariantCulture) + "</antennaPatternType>"); sb.AppendLine("<antennaPatternList type=\"ushort\">" + this._antennaPatternList.Count.ToString(CultureInfo.InvariantCulture) + "</antennaPatternList>"); sb.AppendLine("<frequency type=\"double\">" + this._frequency.ToString(CultureInfo.InvariantCulture) + "</frequency>"); sb.AppendLine("<transmitFrequencyBandwidth type=\"float\">" + this._transmitFrequencyBandwidth.ToString(CultureInfo.InvariantCulture) + "</transmitFrequencyBandwidth>"); sb.AppendLine("<power type=\"float\">" + this._power.ToString(CultureInfo.InvariantCulture) + "</power>"); sb.AppendLine("<modulationType>"); this._modulationType.Reflection(sb); sb.AppendLine("</modulationType>"); sb.AppendLine("<cryptoSystem type=\"ushort\">" + this._cryptoSystem.ToString(CultureInfo.InvariantCulture) + "</cryptoSystem>"); sb.AppendLine("<cryptoKeyId type=\"ushort\">" + this._cryptoKeyId.ToString(CultureInfo.InvariantCulture) + "</cryptoKeyId>"); sb.AppendLine("<modulationParametersList type=\"byte\">" + this._modulationParametersList.Count.ToString(CultureInfo.InvariantCulture) + "</modulationParametersList>"); sb.AppendLine("<padding2 type=\"ushort\">" + this._padding2.ToString(CultureInfo.InvariantCulture) + "</padding2>"); sb.AppendLine("<padding3 type=\"byte\">" + this._padding3.ToString(CultureInfo.InvariantCulture) + "</padding3>"); for (int idx = 0; idx < this._modulationParametersList.Count; idx++) { sb.AppendLine("<modulationParametersList" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"Vector3Float\">"); Vector3Float aVector3Float = (Vector3Float)this._modulationParametersList[idx]; aVector3Float.Reflection(sb); sb.AppendLine("</modulationParametersList" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } for (int idx = 0; idx < this._antennaPatternList.Count; idx++) { sb.AppendLine("<antennaPatternList" + idx.ToString(CultureInfo.InvariantCulture) + " type=\"Vector3Float\">"); Vector3Float aVector3Float = (Vector3Float)this._antennaPatternList[idx]; aVector3Float.Reflection(sb); sb.AppendLine("</antennaPatternList" + idx.ToString(CultureInfo.InvariantCulture) + ">"); } sb.AppendLine("</TransmitterPdu>"); } catch (Exception e) { if (PduBase.TraceExceptions) { Trace.WriteLine(e); Trace.Flush(); } this.RaiseExceptionOccured(e); if (PduBase.ThrowExceptions) { throw e; } } } /// <summary> /// Determines whether the specified <see cref="System.Object"/> is equal to this instance. /// </summary> /// <param name="obj">The <see cref="System.Object"/> to compare with this instance.</param> /// <returns> /// <c>true</c> if the specified <see cref="System.Object"/> is equal to this instance; otherwise, <c>false</c>. /// </returns> public override bool Equals(object obj) { return this == obj as TransmitterPdu; } /// <summary> /// Compares for reference AND value equality. /// </summary> /// <param name="obj">The object to compare with this instance.</param> /// <returns> /// <c>true</c> if both operands are equal; otherwise, <c>false</c>. /// </returns> public bool Equals(TransmitterPdu obj) { bool ivarsEqual = true; if (obj.GetType() != this.GetType()) { return false; } ivarsEqual = base.Equals(obj); if (!this._radioEntityType.Equals(obj._radioEntityType)) { ivarsEqual = false; } if (this._transmitState != obj._transmitState) { ivarsEqual = false; } if (this._inputSource != obj._inputSource) { ivarsEqual = false; } if (this._padding1 != obj._padding1) { ivarsEqual = false; } if (!this._antennaLocation.Equals(obj._antennaLocation)) { ivarsEqual = false; } if (!this._relativeAntennaLocation.Equals(obj._relativeAntennaLocation)) { ivarsEqual = false; } if (this._antennaPatternType != obj._antennaPatternType) { ivarsEqual = false; } if (this._antennaPatternCount != obj._antennaPatternCount) { ivarsEqual = false; } if (this._frequency != obj._frequency) { ivarsEqual = false; } if (this._transmitFrequencyBandwidth != obj._transmitFrequencyBandwidth) { ivarsEqual = false; } if (this._power != obj._power) { ivarsEqual = false; } if (!this._modulationType.Equals(obj._modulationType)) { ivarsEqual = false; } if (this._cryptoSystem != obj._cryptoSystem) { ivarsEqual = false; } if (this._cryptoKeyId != obj._cryptoKeyId) { ivarsEqual = false; } if (this._modulationParameterCount != obj._modulationParameterCount) { ivarsEqual = false; } if (this._padding2 != obj._padding2) { ivarsEqual = false; } if (this._padding3 != obj._padding3) { ivarsEqual = false; } if (this._modulationParametersList.Count != obj._modulationParametersList.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._modulationParametersList.Count; idx++) { if (!this._modulationParametersList[idx].Equals(obj._modulationParametersList[idx])) { ivarsEqual = false; } } } if (this._antennaPatternList.Count != obj._antennaPatternList.Count) { ivarsEqual = false; } if (ivarsEqual) { for (int idx = 0; idx < this._antennaPatternList.Count; idx++) { if (!this._antennaPatternList[idx].Equals(obj._antennaPatternList[idx])) { ivarsEqual = false; } } } return ivarsEqual; } /// <summary> /// HashCode Helper /// </summary> /// <param name="hash">The hash value.</param> /// <returns>The new hash value.</returns> private static int GenerateHash(int hash) { hash = hash << (5 + hash); return hash; } /// <summary> /// Gets the hash code. /// </summary> /// <returns>The hash code.</returns> public override int GetHashCode() { int result = 0; result = GenerateHash(result) ^ base.GetHashCode(); result = GenerateHash(result) ^ this._radioEntityType.GetHashCode(); result = GenerateHash(result) ^ this._transmitState.GetHashCode(); result = GenerateHash(result) ^ this._inputSource.GetHashCode(); result = GenerateHash(result) ^ this._padding1.GetHashCode(); result = GenerateHash(result) ^ this._antennaLocation.GetHashCode(); result = GenerateHash(result) ^ this._relativeAntennaLocation.GetHashCode(); result = GenerateHash(result) ^ this._antennaPatternType.GetHashCode(); result = GenerateHash(result) ^ this._antennaPatternCount.GetHashCode(); result = GenerateHash(result) ^ this._frequency.GetHashCode(); result = GenerateHash(result) ^ this._transmitFrequencyBandwidth.GetHashCode(); result = GenerateHash(result) ^ this._power.GetHashCode(); result = GenerateHash(result) ^ this._modulationType.GetHashCode(); result = GenerateHash(result) ^ this._cryptoSystem.GetHashCode(); result = GenerateHash(result) ^ this._cryptoKeyId.GetHashCode(); result = GenerateHash(result) ^ this._modulationParameterCount.GetHashCode(); result = GenerateHash(result) ^ this._padding2.GetHashCode(); result = GenerateHash(result) ^ this._padding3.GetHashCode(); if (this._modulationParametersList.Count > 0) { for (int idx = 0; idx < this._modulationParametersList.Count; idx++) { result = GenerateHash(result) ^ this._modulationParametersList[idx].GetHashCode(); } } if (this._antennaPatternList.Count > 0) { for (int idx = 0; idx < this._antennaPatternList.Count; idx++) { result = GenerateHash(result) ^ this._antennaPatternList[idx].GetHashCode(); } } return result; } } }
#region Namespaces using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Text; using Autodesk.Revit.ApplicationServices; using Autodesk.Revit.Attributes; using Autodesk.Revit.DB; using Autodesk.Revit.DB.Electrical; using Autodesk.Revit.DB.Mechanical; using Autodesk.Revit.DB.Plumbing; using Autodesk.Revit.UI; #endregion namespace TraverseAllSystems { [Transaction( TransactionMode.Manual )] public class Command : IExternalCommand { /// <summary> /// Return true to include this system in the /// exported system graphs. /// </summary> static bool IsDesirableSystemPredicate( MEPSystem s ) { return 1 < s.Elements.Size && !s.Name.Equals( "unassigned" ) && ( ( s is MechanicalSystem && ( (MechanicalSystem) s ).IsWellConnected ) || ( s is PipingSystem && ( (PipingSystem) s ).IsWellConnected ) || ( s is ElectricalSystem && ( (ElectricalSystem) s ).IsMultipleNetwork ) ); } /// <summary> /// The thee MEP disciplines /// </summary> public enum MepDomain { Invalid = -1, Mechanical = 0, Electrical = 1, Piping = 2, Count = 3 } MepDomain GetMepDomain( MEPSystem s ) { return ( s is MechanicalSystem ) ? MepDomain.Mechanical : (( s is ElectricalSystem ) ? MepDomain.Electrical : (( s is PipingSystem ) ? MepDomain.Piping : MepDomain.Invalid)); } /// <summary> /// Create a and return the path of a random temporary directory. /// </summary> static string GetTemporaryDirectory() { string tempDirectory = Path.Combine( Path.GetTempPath(), Path.GetRandomFileName() ); Directory.CreateDirectory( tempDirectory ); return tempDirectory; } public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements ) { UIApplication uiapp = commandData.Application; UIDocument uidoc = uiapp.ActiveUIDocument; Application app = uiapp.Application; Document doc = uidoc.Document; FilteredElementCollector allSystems = new FilteredElementCollector( doc ) .OfClass( typeof( MEPSystem ) ); int nAllSystems = allSystems.Count<Element>(); IEnumerable<MEPSystem> desirableSystems = allSystems.Cast<MEPSystem>().Where<MEPSystem>( s => IsDesirableSystemPredicate( s ) ); int nDesirableSystems = desirableSystems .Count<Element>(); // Check for shared parameter // to store graph information. // Determine element from which to retrieve // shared parameter definition. Element json_storage_element = Options.StoreSeparateJsonGraphOnEachSystem ? desirableSystems.First<MEPSystem>() : new FilteredElementCollector( doc ) .OfClass( typeof( ProjectInfo ) ) .FirstElement(); Definition def = SharedParameterMgr.GetDefinition( json_storage_element ); if( null == def ) { SharedParameterMgr.Create( doc ); def = SharedParameterMgr.GetDefinition( json_storage_element ); if( null == def ) { message = "Error creating the " + "storage shared parameter."; return Result.Failed; } } string outputFolder = GetTemporaryDirectory(); int nXmlFiles = 0; int nJsonGraphs = 0; int nJsonBytes = 0; // Collect one JSON string per system. string json; // Three separate collections for mechanical, // electrical and piping systems: List<string>[] json_collector = new List<string>[(int)MepDomain.Count] { new List<string>(), new List<string>(), new List<string>() }; using( Transaction t = new Transaction( doc ) ) { t.Start( "Determine MEP Graph Structure and Store in JSON Shared Parameter" ); StringBuilder[] sbs = new StringBuilder[3]; for( int i = 0; i < 3; ++i ) { sbs[i] = new StringBuilder(); sbs[i].Append( "[" ); } foreach( MEPSystem system in desirableSystems ) { Debug.Print( system.Name ); FamilyInstance root = system.BaseEquipment; // Traverse the system and dump the // traversal graph into an XML file TraversalTree tree = new TraversalTree( system ); if( tree.Traverse() ) { string filename = system.Id.IntegerValue.ToString(); filename = Path.ChangeExtension( Path.Combine( outputFolder, filename ), "xml" ); tree.DumpIntoXML( filename ); // Uncomment to preview the // resulting XML structure //Process.Start( fileName ); json = Options.StoreJsonGraphBottomUp ? tree.DumpToJsonBottomUp() : tree.DumpToJsonTopDown(); Debug.Assert( 2 < json.Length, "expected valid non-empty JSON graph data" ); Debug.Print( json ); // Save this system hierarchy JSON in the // appropriate domain specific collector. json_collector[(int)GetMepDomain(system)].Add( json ); if( Options.StoreSeparateJsonGraphOnEachSystem ) { Parameter p = system.get_Parameter( def ); p.Set( json ); } nJsonBytes += json.Length; ++nJsonGraphs; ++nXmlFiles; } tree.CollectUniqueIds( sbs ); } for( int i = 0; i < 3; ++i ) { if( sbs[i][sbs[i].Length - 1] == ',' ) { sbs[i].Remove( sbs[i].Length - 1, 1 ); } sbs[i].Append( "]" ); } StringBuilder sb = new StringBuilder(); sb.Append( "{\"id\": 1 , \"name\" : \"MEP Systems\" , \"children\" : [{\"id\": 2 , \"name\": \"Mechanical System\",\"children\":" ); sb.Append( sbs[0].ToString() ); sb.Append( "},{\"id\":3,\"name\":\"Electrical System\", \"children\":" ); sb.Append( sbs[1].ToString() ); sb.Append( "},{\"id\":4,\"name\":\"Piping System\", \"children\":" ); sb.Append( sbs[2].ToString() ); sb.Append( "}]}" ); StreamWriter file = new StreamWriter( Path.ChangeExtension( Path.Combine( outputFolder, "jsonData" ), "json" ) ); file.WriteLine( sb.ToString() ); file.Flush(); file.Close(); t.Commit(); } string msg = string.Format( "{0} XML files and {1} JSON graphs ({2} bytes) " + "generated in {3} ({4} total systems, {5} desirable):", nXmlFiles, nJsonGraphs, nJsonBytes, outputFolder, nAllSystems, nDesirableSystems ); List<string> system_list = desirableSystems .Select<Element, string>( e => string.Format( "{0}({1})", e.Id, e.Name ) ) .ToList<string>(); system_list.Sort(); string detail = string.Join( ", ", system_list.ToArray<string>() ); TaskDialog dlg = new TaskDialog( nXmlFiles.ToString() + " Systems" ); dlg.MainInstruction = msg; dlg.MainContent = detail; dlg.Show(); string[] json_systems = new string[3]; int id = doc.Title.GetHashCode(); for( MepDomain d = MepDomain.Mechanical; d < MepDomain.Count; ++d ) { // Compare the systems using the label value, // which comes after the first comma. json_collector[(int) d].Sort( (s,t) => string.Compare( s.Substring(s.IndexOf(",")), t.Substring( t.IndexOf( "," ) ) ) ); json_systems[(int)d] = TreeNode.CreateJsonParentNode( (++id).ToString(), d.ToString(), json_collector[(int) d].ToArray<string>() ); } json = TreeNode.CreateJsonParentNode( doc.Title.GetHashCode().ToString(), doc.Title, json_systems ); Debug.Print( json ); if( Options.StoreEntireJsonGraphOnProjectInfo ) { using( Transaction t = new Transaction( doc ) ) { t.Start( "Store MEP Graph Structure " + "in JSON Shared Parameter" ); Parameter p = json_storage_element .get_Parameter( def ); p.Set( json ); t.Commit(); } } return Result.Succeeded; } } }
// Window.cs // Script#/Libraries/Web // This source code is subject to terms and conditions of the Apache License, Version 2.0. // using System; using System.Html.Data; using System.Html.Data.Files; using System.Html.Data.IndexedDB; using System.Html.Data.Sql; using System.Runtime.CompilerServices; namespace System.Html { /// <summary> /// The window object represents the current browser window, and is the top-level /// scripting object. /// </summary> [ScriptIgnoreNamespace] [ScriptImport] [ScriptName("window")] public sealed class Window { private Window() { } [ScriptField] public static ApplicationCache ApplicationCache { get { return null; } } [ScriptField] public static Blob Blob { get { return null; } } /// <summary> /// IE only. /// </summary> [ScriptField] public static DataTransfer ClipboardData { get { return null; } } [ScriptField] public static bool Closed { get { return false; } } [ScriptField] public static string DefaultStatus { get { return null; } set { } } [ScriptField] public static object DialogArguments { get { return null; } } [ScriptField] public static DocumentInstance Document { get { return null; } } /// <summary> /// Provides information about the current event being handled. /// </summary> [ScriptField] public static ElementEvent Event { get { return null; } } [ScriptField] public static File File { get { return null; } } [ScriptField] public static FileList FileList { get { return null; } } [ScriptField] public static FileReader FileReader { get { return null; } } [ScriptField] public static IFrameElement FrameElement { get { return null; } } [ScriptField] public static History History { get { return null; } } [ScriptField] public static int InnerHeight { get { return 0; } } [ScriptField] public static int InnerWidth { get { return 0; } } [ScriptField] public static Storage LocalStorage { get { return null; } } [ScriptField] public static Location Location { get { return null; } } [ScriptField] public static Navigator Navigator { get { return null; } } [ScriptField] public static WindowInstance Parent { get { return null; } } [ScriptField] public static ErrorHandler Onerror { get { return null; } set { } } [ScriptField] public static WindowInstance Opener { get { return null; } } [ScriptField] public static Orientation Orientation { get { return Orientation.Portrait; } } [ScriptField] public static int OuterHeight { get { return 0; } } [ScriptField] public static int OuterWidth { get { return 0; } } [ScriptField] public static int PageXOffset { get { return 0; } } [ScriptField] public static int PageYOffset { get { return 0; } } [ScriptField] public static Screen Screen { get { return null; } } [ScriptField] public static WindowInstance Self { get { return null; } } [ScriptField] public static Storage SessionStorage { get { return null; } } [ScriptField] public static string Status { get { return null; } set { } } [ScriptField] public static WindowInstance Top { get { return null; } } [ScriptField] public static WindowInstance[] Frames { get { return null; } } /// <summary> /// Adds a listener for the specified event. /// </summary> /// <param name="eventName">The name of the event such as 'load'.</param> /// <param name="listener">The listener to be invoked in response to the event.</param> public static void AddEventListener(string eventName, ElementEventListener listener) { } /// <summary> /// Adds a listener for the specified event. /// </summary> /// <param name="eventName">The name of the event such as 'load'.</param> /// <param name="listener">The listener to be invoked in response to the event.</param> /// <param name="useCapture">Whether the listener wants to initiate capturing the event.</param> public static void AddEventListener(string eventName, ElementEventListener listener, bool useCapture) { } /// <summary> /// Displays a message box containing the specified message text. /// </summary> /// <param name="message">The text of the message.</param> [ScriptAlias("alert")] public static void Alert(string message) { } /// <summary> /// Displays a message box containing the specified value converted /// into a string. /// </summary> /// <param name="b">The boolean to display.</param> [ScriptAlias("alert")] public static void Alert(bool b) { } /// <summary> /// Displays a message box containing the specified value converted /// into a string. /// </summary> /// <param name="d">The date to display.</param> [ScriptAlias("alert")] public static void Alert(Date d) { } /// <summary> /// Displays a message box containing the specified value converted /// into a string. /// </summary> /// <param name="n">The number to display.</param> [ScriptAlias("alert")] public static void Alert(Number n) { } /// <summary> /// Displays a message box containing the specified value converted /// into a string. /// </summary> /// <param name="o">The object to display.</param> [ScriptAlias("alert")] public static void Alert(object o) { } public static void AttachEvent(string eventName, ElementEventHandler handler) { } /// <summary> /// Decodes a string of data which has been encoded using base-64 encoding. /// For use with Unicode or UTF-8 strings. /// </summary> /// <param name="base64EncodedData">Base64 encoded string</param> /// <returns>String of Binary data</returns> [ScriptName("atob")] public static string Base64ToBinary(string base64EncodedData) { return null; } /// <summary> /// Creates a base-64 encoded ASCII string from a "string" of binary data. /// Please note that this is not suitable for raw Unicode strings! /// </summary> /// <param name="stringToEncode">String of binary data</param> /// <returns>Base64 string</returns> [ScriptName("btoa")] public static string BinaryToBase64(string stringToEncode) { return null; } public static void Close() { } /// <summary> /// Prompts the user with a yes/no question. /// </summary> /// <param name="message">The text of the question.</param> /// <returns>true if the user chooses yes; false otherwise.</returns> [ScriptAlias("confirm")] public static bool Confirm(string message) { return false; } public static void DetachEvent(string eventName, ElementEventHandler handler) { } public static bool DispatchEvent(MutableEvent eventObject) { return false; } public static void Navigate(string url) { } public static WindowInstance Open(string url) { return null; } public static WindowInstance Open(string url, string targetName) { return null; } public static WindowInstance Open(string url, string targetName, string features) { return null; } public static WindowInstance Open(string url, string targetName, string features, bool replace) { return null; } public static void Print() { } /// <summary> /// Prompts the user to enter a value. /// </summary> /// <param name="message">The text of the prompt.</param> /// <returns>The value entered by the user.</returns> [ScriptAlias("prompt")] public static string Prompt(string message) { return null; } /// <summary> /// Prompts the user to enter a value. /// </summary> /// <param name="message">The text of the prompt.</param> /// <param name="defaultValue">The default value for the prompt.</param> /// <returns>The value entered by the user.</returns> [ScriptAlias("prompt")] public static string Prompt(string message, string defaultValue) { return null; } /// <summary> /// Removes a listener for the specified event. /// </summary> /// <param name="eventName">The name of the event such as 'load'.</param> /// <param name="listener">The listener to be invoked in response to the event.</param> public static void RemoveEventListener(string eventName, ElementEventListener listener) { } /// <summary> /// Removes a listener for the specified event. /// </summary> /// <param name="eventName">The name of the event such as 'load'.</param> /// <param name="listener">The listener to be invoked in response to the event.</param> /// <param name="useCapture">Whether the listener wants to initiate capturing the event.</param> public static void RemoveEventListener(string eventName, ElementEventListener listener, bool useCapture) { } [ScriptAlias("require")] public static void Require(string[] names, Action callback) { } [ScriptAlias("require")] public static void Require<T>(string name, Action<T> callback) { } [ScriptAlias("require")] public static void Require(string name, Action callback) { } public static void Scroll(int x, int y) { } public static void ScrollBy(int x, int y) { } public static void ScrollTo(int x, int y) { } public static SqlDatabase OpenDatabase(string name, string version) { return null; } public static SqlDatabase OpenDatabase(string name, string version, string displayName) { return null; } public static SqlDatabase OpenDatabase(string name, string version, string displayName, int estimatedSize) { return null; } public static SqlDatabase OpenDatabase(string name, string version, string displayName, int estimatedSize, SqlDatabaseCallback creationCallback) { return null; } [ScriptField] public static DBFactory IndexedDB { get { return null; } } public static void PostMessage(string message, string targetOrigin) { } /// <summary> /// Delegate that indicates the ability of the browser /// to show a modal dialog. /// </summary> /// <remarks> /// Not all browsers support this function, so code using /// this needs to check for existence of the feature or the browser. /// </remarks> public static WindowInstance ShowModalDialog(string url, object dialogArguments, string features) { return null; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Fixtures.AcceptanceTestsBodyString { using Microsoft.Rest; using Models; /// <summary> /// EnumModel operations. /// </summary> public partial class EnumModel : Microsoft.Rest.IServiceOperations<AutoRestSwaggerBATService>, IEnumModel { /// <summary> /// Initializes a new instance of the EnumModel class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> /// <exception cref="System.ArgumentNullException"> /// Thrown when a required parameter is null /// </exception> public EnumModel(AutoRestSwaggerBATService client) { if (client == null) { throw new System.ArgumentNullException("client"); } this.Client = client; } /// <summary> /// Gets a reference to the AutoRestSwaggerBATService /// </summary> public AutoRestSwaggerBATService Client { get; private set; } /// <summary> /// Get enum value 'red color' from enumeration of 'red color', 'green-color', /// 'blue_color'. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Colors?>> GetNotExpandableWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetNotExpandable", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/notExpandable").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<Colors?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Colors?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Sends value 'red color' from enumeration of 'red color', 'green-color', /// 'blue_color' /// </summary> /// <param name='stringBody'> /// Possible values include: 'red color', 'green-color', 'blue_color' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutNotExpandableWithHttpMessagesAsync(Colors stringBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("stringBody", stringBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutNotExpandable", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/notExpandable").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(stringBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get enum value 'red color' from enumeration of 'red color', 'green-color', /// 'blue_color'. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<Colors?>> GetReferencedWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetReferenced", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/Referenced").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<Colors?>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Colors?>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Sends value 'red color' from enumeration of 'red color', 'green-color', /// 'blue_color' /// </summary> /// <param name='enumStringBody'> /// Possible values include: 'red color', 'green-color', 'blue_color' /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutReferencedWithHttpMessagesAsync(Colors enumStringBody, System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("enumStringBody", enumStringBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutReferenced", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/Referenced").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(enumStringBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Get value 'green-color' from the constant. /// </summary> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse<RefColorConstant>> GetReferencedConstantWithHttpMessagesAsync(System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "GetReferencedConstant", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/ReferencedConstant").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("GET"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse<RefColorConstant>(); _result.Request = _httpRequest; _result.Response = _httpResponse; // Deserialize Response if ((int)_statusCode == 200) { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); try { _result.Body = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<RefColorConstant>(_responseContent, this.Client.DeserializationSettings); } catch (Newtonsoft.Json.JsonException ex) { _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw new Microsoft.Rest.SerializationException("Unable to deserialize the response.", _responseContent, ex); } } if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Sends value 'green-color' from a constant /// </summary> /// <param name='field1'> /// Sample string. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="ErrorException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async System.Threading.Tasks.Task<Microsoft.Rest.HttpOperationResponse> PutReferencedConstantWithHttpMessagesAsync(string field1 = default(string), System.Collections.Generic.Dictionary<string, System.Collections.Generic.List<string>> customHeaders = null, System.Threading.CancellationToken cancellationToken = default(System.Threading.CancellationToken)) { RefColorConstant enumStringBody = new RefColorConstant(); if (field1 != null) { enumStringBody.Field1 = field1; } // Tracing bool _shouldTrace = Microsoft.Rest.ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = Microsoft.Rest.ServiceClientTracing.NextInvocationId.ToString(); System.Collections.Generic.Dictionary<string, object> tracingParameters = new System.Collections.Generic.Dictionary<string, object>(); tracingParameters.Add("enumStringBody", enumStringBody); tracingParameters.Add("cancellationToken", cancellationToken); Microsoft.Rest.ServiceClientTracing.Enter(_invocationId, this, "PutReferencedConstant", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new System.Uri(new System.Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "string/enum/ReferencedConstant").ToString(); // Create HTTP transport objects System.Net.Http.HttpRequestMessage _httpRequest = new System.Net.Http.HttpRequestMessage(); System.Net.Http.HttpResponseMessage _httpResponse = null; _httpRequest.Method = new System.Net.Http.HttpMethod("PUT"); _httpRequest.RequestUri = new System.Uri(_url); // Set Headers if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; if(enumStringBody != null) { _requestContent = Microsoft.Rest.Serialization.SafeJsonConvert.SerializeObject(enumStringBody, this.Client.SerializationSettings); _httpRequest.Content = new System.Net.Http.StringContent(_requestContent, System.Text.Encoding.UTF8); _httpRequest.Content.Headers.ContentType =System.Net.Http.Headers.MediaTypeHeaderValue.Parse("application/json; charset=utf-8"); } // Send Request if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } System.Net.HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new ErrorException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); Error _errorBody = Microsoft.Rest.Serialization.SafeJsonConvert.DeserializeObject<Error>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex.Body = _errorBody; } } catch (Newtonsoft.Json.JsonException) { // Ignore the exception } ex.Request = new Microsoft.Rest.HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new Microsoft.Rest.HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new Microsoft.Rest.HttpOperationResponse(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_shouldTrace) { Microsoft.Rest.ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using System.Diagnostics; using IxMilia.BCad.Entities; using IxMilia.BCad.Extensions; using IxMilia.BCad.Helpers; namespace IxMilia.BCad.Primitives { public class PrimitiveEllipse : IPrimitive { public Point Center { get; private set; } public Vector MajorAxis { get; private set; } public Vector Normal { get; private set; } public double MinorAxisRatio { get; private set; } public double StartAngle { get; private set; } public double EndAngle { get; private set; } public CadColor? Color { get; private set; } public Matrix4 FromUnitCircle { get; private set; } public double Thickness { get; private set; } public PrimitiveKind Kind { get { return PrimitiveKind.Ellipse; } } public bool IsClosed { get { return MathHelper.CloseTo(0.0, StartAngle) && MathHelper.CloseTo(MathHelper.ThreeSixty, EndAngle); } } public bool IsCircle => MinorAxisRatio == 1.0 && IsClosed; /// <summary> /// Creates a new PrimitiveEllipse. /// </summary> public PrimitiveEllipse(Point center, Vector majorAxis, Vector normal, double minorAxisRatio, double startAngle, double endAngle, CadColor? color = null, double thickness = default(double)) { Debug.Assert(MathHelper.Between(0.0, 360.0, startAngle)); Debug.Assert(MathHelper.Between(0.0, 360.0, endAngle)); this.Center = center; this.MajorAxis = majorAxis; this.Normal = normal; this.MinorAxisRatio = minorAxisRatio; this.StartAngle = startAngle; this.EndAngle = endAngle; this.Color = color; this.Thickness = thickness; var right = majorAxis.Normalize(); var up = normal.Cross(right).Normalize(); var radiusX = majorAxis.Length; this.FromUnitCircle = Matrix4.FromUnitCircleProjection(normal.Normalize(), right, up, center, radiusX, radiusX * minorAxisRatio, 1.0); } /// <summary> /// Creates a new PrimitiveEllipse based on a circle. /// </summary> public PrimitiveEllipse(Point center, double radius, Vector normal, CadColor? color = null, double thickness = default(double)) : this(center, Vector.RightVectorFromNormal(normal) * radius, normal, 1.0, 0.0, 360.0, color, thickness) { } /// <summary> /// Creates a new PrimitiveEllipse based on an arc. /// </summary> public PrimitiveEllipse(Point center, double radius, double startAngle, double endAngle, Vector normal, CadColor? color = null, double thickness = default(double)) : this(center, Vector.RightVectorFromNormal(normal) * radius, normal, 1.0, startAngle, endAngle, color, thickness) { } /// <summary> /// Creates a circle that passes through the three specified points. Null if the points are co-linear /// </summary> /// <param name="a">The first point.</param> /// <param name="b">The second point.</param> /// <param name="c">The third point.</param> /// <param name="idealNormal">The ideal normal to normalize to if specified.</param> /// <returns>The resultant circle or null.</returns> public static PrimitiveEllipse ThreePointCircle(Point a, Point b, Point c, Optional<Vector> idealNormal = default(Optional<Vector>)) { var v1 = a - b; var v2 = c - b; var normal = v1.Cross(v2); if (normal.IsZeroVector) return null; normal = normal.Normalize(); var m1 = v1.Cross(normal); var m2 = v2.Cross(normal); var b1a = (a + b) / 2.0; var b2a = (c + b) / 2.0; var b1 = new PrimitiveLine(b1a, b1a + m1); var b2 = new PrimitiveLine(b2a, b2a + m2); var center = b1.IntersectionPoint(b2, false); if (center == null) return null; if (idealNormal.HasValue && idealNormal.Value == normal * -1.0) normal = idealNormal.Value; return new PrimitiveEllipse(center.Value, (a - center.Value).Length, normal); } /// <summary> /// Creates an arc that passes through the three specified points where the first and last /// points are the start and end points. Null if the points are co-linear. /// </summary> /// <param name="a">The first point.</param> /// <param name="b">The second point.</param> /// <param name="c">The third point.</param> /// <param name="idealNormal">The ideal normal to normalize to if specified.</param> /// <returns>The resultant arc or null.</returns> public static PrimitiveEllipse ThreePointArc(Point a, Point b, Point c, Optional<Vector> idealNormal = default(Optional<Vector>)) { var circle = ThreePointCircle(a, b, c, idealNormal); if (circle != null) { var toUnit = circle.FromUnitCircle.Inverse(); var startAngle = toUnit.Transform((Vector)a).ToAngle(); var midAngle = toUnit.Transform((Vector)b).ToAngle(); var endAngle = toUnit.Transform((Vector)c).ToAngle(); // normalize mid and end angles to be greater than the start angle var realMid = midAngle; while (realMid < startAngle) realMid += MathHelper.ThreeSixty; var realEnd = endAngle; while (realEnd < startAngle) realEnd += MathHelper.ThreeSixty; if (realMid > realEnd) { var temp = startAngle; startAngle = endAngle; endAngle = temp; } circle.StartAngle = startAngle; circle.EndAngle = endAngle; return circle; } return null; } /// <summary> /// Creates an arc with the specified endpoints and the resultant included angle and vertex direction. /// </summary> /// <param name="p1">The first point.</param> /// <param name="p2">The second point.</param> /// <param name="includedAngle">The included angle of the resultant arc in degrees.</param> /// <param name="vertexDirection">The direction of the vertices specifying the arc.</param> /// <returns>The resultant arc, or null if it couldn't be created.</returns> public static PrimitiveEllipse ArcFromPointsAndIncludedAngle(Point p1, Point p2, double includedAngle, VertexDirection vertexDirection) { if (p1.Z != p2.Z) { throw new InvalidOperationException("only simple planar arcs are currently supported"); } if (includedAngle < 0.0 || includedAngle >= MathHelper.ThreeSixty) { throw new ArgumentOutOfRangeException(nameof(includedAngle)); } // given the following diagram: // // p1 // -) // - | ) // - | ) // - | ) // O ------------|C----T // - | x ) // - | ) // - | ) // -) // p2 // // where O is the center of the circle, C is the midpoint between p1 and p2, the // distance x is the amount that C would have to be offset perpendicular to the // line p1p2 to find the third point T from which we can calculate the arcs // first, find the required radius // there is an isoceles triangle created between the two points and the center which means splitting that there's // a right triangle whose hypotenuse is a radius of the circle and the opposite side is half of the distance between // the points. var incAngleRad = includedAngle * MathHelper.DegreesToRadians; var halfAngle = incAngleRad / 2.0; var otherLength = (p2 - p1).Length / 2.0; // since sin(theta) = opposite / hypotenuse => opposite / sin(theta) = hypotenuse var radius = otherLength / Math.Sin(halfAngle); // hypotenuse length // then, given that Op1C is a right triangle and that the line OC has a length of r - x and assuming y is the distance // between the point C and p1, we get // r^2 = (r-x)^2 + y^2 => x = r - sqrt(r^2 - y^2) var midpoint = (p1 + p2) / 2.0; var y = otherLength; var xOffset = radius - Math.Sqrt((radius * radius) - (y * y)); // for angles greater than 180 degrees, the offset point is really much farther away if (includedAngle >= MathHelper.OneEighty) xOffset = radius + radius - xOffset; // now offset the midpoint by x (both directions) perpendicular to the line p1p2 and compute the arcs var chordVector = p2 - p1; var offsetVector = new Vector(-chordVector.Y, chordVector.X, chordVector.Z).Normalize() * xOffset; var possibleMidpoint1 = midpoint + offsetVector; var possibleMidpoint2 = midpoint - offsetVector; // now construct like normal var arc = ThreePointArc(p1, possibleMidpoint1, p2, idealNormal: Vector.ZAxis); var startPoint = arc.StartPoint(); if (startPoint.CloseTo(p1) ^ vertexDirection != VertexDirection.CounterClockwise) { // arc is correct } else { arc = ThreePointArc(p1, possibleMidpoint2, p2, idealNormal: Vector.ZAxis); } return arc; } /// <summary> /// Creates a 2-dimensional ellipse. /// </summary> /// <param name="center">The center of the ellipse.</param> /// <param name="a">The major radius.</param> /// <param name="b">The minor radius.</param> /// <returns>The PrimitiveEllipse object.</returns> public static PrimitiveEllipse Ellipse2d(Point center, double a, double b) { return new PrimitiveEllipse(center, new Vector(a, 0.0, 0.0), Vector.ZAxis, b / a, 0, 360); } } }
using System; using System.ComponentModel; using Eto.Drawing; using sd = System.Drawing; using sdd = System.Drawing.Drawing2D; using swf = System.Windows.Forms; using System.Collections.Generic; namespace Eto.WinForms.Drawing { /// <summary> /// Handler for <see cref="Graphics.IHandler"/> /// </summary> /// <copyright>(c) 2012-2014 by Curtis Wensley</copyright> /// <license type="BSD-3">See LICENSE for full terms</license> public class GraphicsHandler : WidgetHandler<System.Drawing.Graphics, Graphics>, Graphics.IHandler { Stack<sd.Drawing2D.Matrix> savedTransforms; /// <summary> /// Gets or sets a value indicating that the <see cref="DrawText"/> and <see cref="MeasureString"/> methods /// use compatible rendering (GDI+), or newer graphics-dependent (GDI) methods that have better cleartype rendering. /// Setting this to false will not allow the text to be fully transformed, so it is only recommended to turn /// off when rendering a custom control. /// Use via styles like so: /// <code> /// Eto.Style.Add&lt;GraphicsHandler&gt;(null, h => h.UseCompatibleTextRendering = false); /// </code> /// </summary> [DefaultValue(true)] public bool UseCompatibleTextRendering { get; set; } public bool IsRetained { get { return false; } } public static swf.TextFormatFlags DefaultTextFormat { get; private set; } public static sd.StringFormat DefaultStringFormat { get; private set; } static GraphicsHandler() { DefaultTextFormat = swf.TextFormatFlags.Left | swf.TextFormatFlags.NoPadding | swf.TextFormatFlags.NoClipping | swf.TextFormatFlags.PreserveGraphicsClipping | swf.TextFormatFlags.PreserveGraphicsTranslateTransform | swf.TextFormatFlags.NoPrefix; // Set the StringFormat DefaultStringFormat = new sd.StringFormat(sd.StringFormat.GenericTypographic); DefaultStringFormat.FormatFlags |= sd.StringFormatFlags.MeasureTrailingSpaces | sd.StringFormatFlags.NoWrap | sd.StringFormatFlags.NoClip; } ImageInterpolation imageInterpolation; public GraphicsHandler() { UseCompatibleTextRendering = true; } bool shouldDisposeGraphics = true; public GraphicsHandler(sd.Graphics graphics, bool shouldDisposeGraphics = true) : this() { this.Control = graphics; this.shouldDisposeGraphics = shouldDisposeGraphics; } protected override void Dispose(bool disposing) { if (!shouldDisposeGraphics) Control = null; base.Dispose(disposing); } public bool AntiAlias { get { return (this.Control.SmoothingMode == System.Drawing.Drawing2D.SmoothingMode.AntiAlias); } set { if (value) this.Control.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias; else this.Control.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.None; } } public ImageInterpolation ImageInterpolation { get { return imageInterpolation; } set { imageInterpolation = value; Control.InterpolationMode = value.ToSD(); } } static readonly object PixelOffsetMode_Key = new object(); public PixelOffsetMode PixelOffsetMode { get { return Widget.Properties.Get<PixelOffsetMode>(PixelOffsetMode_Key); } set { Widget.Properties.Set(PixelOffsetMode_Key, value); } } void SetOffset(bool fill) { var mode = sdd.PixelOffsetMode.Half; if (!fill && PixelOffsetMode == PixelOffsetMode.None) mode = sdd.PixelOffsetMode.None; Control.PixelOffsetMode = mode; } public float PointsPerPixel { get { return 72f / Control.DpiX; } } public void CreateFromImage(Bitmap image) { Control = sd.Graphics.FromImage((sd.Image)image.ControlObject); } protected override void Initialize() { base.Initialize(); SetInitialState(); } public void SetInitialState() { Control.PixelOffsetMode = sdd.PixelOffsetMode.None; Control.SmoothingMode = sdd.SmoothingMode.AntiAlias; Control.InterpolationMode = sdd.InterpolationMode.HighQualityBilinear; } public void Commit() { } public void DrawLine(Pen pen, float startx, float starty, float endx, float endy) { SetOffset(false); Control.DrawLine(pen.ToSD(), startx, starty, endx, endy); } public void DrawRectangle(Pen pen, float x, float y, float width, float height) { SetOffset(false); Control.DrawRectangle(pen.ToSD(), x, y, width, height); } public void FillRectangle(Brush brush, float x, float y, float width, float height) { SetOffset(true); Control.FillRectangle(brush.ToSD(new RectangleF(x, y, width, height)), x, y, width, height); } public void DrawEllipse(Pen pen, float x, float y, float width, float height) { SetOffset(false); Control.DrawEllipse(pen.ToSD(), x, y, width, height); } public void FillEllipse(Brush brush, float x, float y, float width, float height) { SetOffset(false); Control.FillEllipse(brush.ToSD(new RectangleF(x, y, width, height)), x, y, width, height); } public float GetConvertedAngle(float initialAngle, float majorRadius, float minorRadius, bool circularToElliptical) { var angle = initialAngle; while (angle < 0) angle += 360.0f; var modAngle = angle % 360.0f; angle %= 90.0f; if (angle == 0) return initialAngle; var quadrant2 = (modAngle > 90 && modAngle <= 180); var quadrant3 = (modAngle > 180 && modAngle <= 270); var quadrant4 = (modAngle > 270 && modAngle <= 360); if (quadrant2 || quadrant4) angle = 90.0f - angle; angle = DegreeToRadian(angle); double functionReturnValue = 0; double dTan = 0; dTan = Math.Tan(angle); if (Math.Abs(dTan) < 1E-10 | Math.Abs(dTan) > 10000000000.0) { functionReturnValue = angle; } else if (circularToElliptical) { functionReturnValue = Math.Atan(dTan * majorRadius / minorRadius); } else { functionReturnValue = Math.Atan(dTan * minorRadius / majorRadius); } if (functionReturnValue < 0) { functionReturnValue = functionReturnValue + 2 * Math.PI; } var ret = RadianToDegree((float)functionReturnValue); // convert back to right quadrant if (quadrant2) ret = 180.0f - ret; else if (quadrant4) ret = 360.0f - ret; else if (quadrant3) ret += 180.0f; // get in the same range while (initialAngle < 0) { initialAngle += 360.0f; ret -= 360.0f; } while (initialAngle > 360) { initialAngle -= 360.0f; ret += 360.0f; } return ret; } float DegreeToRadian(float angle) { return (float)Math.PI * angle / 180.0f; } float RadianToDegree(float radians) { return radians * 180.0f / (float)Math.PI; } public void DrawArc(Pen pen, float x, float y, float width, float height, float startAngle, float sweepAngle) { SetOffset(false); if (width != height) { var endAngle = startAngle + sweepAngle; startAngle = GetConvertedAngle(startAngle, width / 2, height / 2, false); endAngle = GetConvertedAngle(endAngle, width / 2, height / 2, false); sweepAngle = endAngle - startAngle; } Control.DrawArc(pen.ToSD(), x, y, width, height, startAngle, sweepAngle); } public void FillPie(Brush brush, float x, float y, float width, float height, float startAngle, float sweepAngle) { SetOffset(true); if (width != height) { var endAngle = startAngle + sweepAngle; startAngle = GetConvertedAngle(startAngle, width / 2, height / 2, false); endAngle = GetConvertedAngle(endAngle, width / 2, height / 2, false); sweepAngle = endAngle - startAngle; } Control.FillPie(brush.ToSD(new RectangleF(x, y, width, height)), x, y, width, height, startAngle, sweepAngle); } public void FillPath(Brush brush, IGraphicsPath path) { SetOffset(true); Control.FillPath(brush.ToSD(path.Bounds), path.ToSD()); } public void DrawPath(Pen pen, IGraphicsPath path) { SetOffset(false); Control.DrawPath(pen.ToSD(), path.ToSD()); } public void DrawImage(Image image, float x, float y) { SetOffset(true); var handler = image.Handler as IWindowsImage; handler.DrawImage(this, x, y); } public void DrawImage(Image image, float x, float y, float width, float height) { SetOffset(true); var handler = image.Handler as IWindowsImage; handler.DrawImage(this, x, y, width, height); } public void DrawImage(Image image, RectangleF source, RectangleF destination) { SetOffset(true); var handler = image.Handler as IWindowsImage; handler.DrawImage(this, source, destination); } public void DrawText(Font font, SolidBrush brush, float x, float y, string text) { SetOffset(false); if (UseCompatibleTextRendering) { Control.DrawString(text, (sd.Font)font.ControlObject, (sd.Brush)brush.ControlObject, x, y, DefaultStringFormat); } else { swf.TextRenderer.DrawText(Control, text, (sd.Font)font.ControlObject, new sd.Point((int)x, (int)y), brush.Color.ToSD(), DefaultTextFormat); } } public SizeF MeasureString(Font font, string text) { if (string.IsNullOrEmpty(text)) return Size.Empty; var sdFont = FontHandler.GetControl(font); if (UseCompatibleTextRendering) { sd.CharacterRange[] ranges = { new sd.CharacterRange(0, text.Length) }; DefaultStringFormat.SetMeasurableCharacterRanges(ranges); var regions = Control.MeasureCharacterRanges(text, sdFont, sd.RectangleF.Empty, DefaultStringFormat); var rect = regions[0].GetBounds(Control); return rect.Size.ToEto(); } var size = swf.TextRenderer.MeasureText(Control, text, sdFont, sd.Size.Empty, DefaultTextFormat); return size.ToEto(); } public void Flush() { Control.Flush(); } public void TranslateTransform(float offsetX, float offsetY) { this.Control.TranslateTransform(offsetX, offsetY); } public void RotateTransform(float angle) { this.Control.RotateTransform(angle); } public void ScaleTransform(float scaleX, float scaleY) { this.Control.ScaleTransform(scaleX, scaleY); } public void MultiplyTransform(IMatrix matrix) { this.Control.MultiplyTransform((sd.Drawing2D.Matrix)matrix.ControlObject); } public void SaveTransform() { if (savedTransforms == null) savedTransforms = new Stack<sd.Drawing2D.Matrix>(); savedTransforms.Push(Control.Transform); } public void RestoreTransform() { if (savedTransforms != null && savedTransforms.Count > 0) { var t = savedTransforms.Pop(); Control.Transform = t; t.Dispose(); } } public IMatrix CurrentTransform { get { return Control.Transform.ToEto(); } } public RectangleF ClipBounds { get { return this.Control.ClipBounds.ToEto(); } } public void SetClip(RectangleF rectangle) { this.Control.SetClip(rectangle.ToSD()); } public void SetClip(IGraphicsPath path) { this.Control.SetClip(path.ToSD()); } public void ResetClip() { this.Control.ResetClip(); } public void Clear(SolidBrush brush) { if (brush != null) Control.Clear(brush.Color.ToSD()); else Control.Clear(sd.Color.Transparent); } } }
using System; using System.Collections.Generic; using System.Data; using System.Linq; using NUnit.Framework; using Should; namespace AutoMapper.UnitTests { namespace DataReaderMapping { public class When_mapping_a_data_reader_to_a_dto : AutoMapperSpecBase { protected override void Establish_context() { Mapper.CreateMap<IDataReader, DTOObject>() .ForMember(dest => dest.Else, options => options.MapFrom(src => src.GetDateTime(10))); _dataReader = new DataBuilder().BuildDataReader(); _result = Mapper.Map<IDataReader, IEnumerable<DTOObject>>(_dataReader).FirstOrDefault(); } [Test] public void Then_a_column_containing_a_small_integer_should_be_read() { Assert.That(_result.SmallInteger, Is.EqualTo(_dataReader[FieldName.SmallInt])); } [Test] public void Then_a_column_containing_an_integer_should_be_read() { Assert.That(_result.Integer, Is.EqualTo(_dataReader[FieldName.Int])); } [Test] public void Then_a_column_containing_a_big_integer_should_be_read() { Assert.That(_result.BigInteger, Is.EqualTo(_dataReader[FieldName.BigInt])); } [Test] public void Then_a_column_containing_a_GUID_should_be_read() { Assert.That(_result.Guid, Is.EqualTo(_dataReader[FieldName.Guid])); } [Test] public void Then_a_column_containing_a_float_should_be_read() { Assert.That(_result.Float, Is.EqualTo(_dataReader[FieldName.Float])); } [Test] public void Then_a_column_containing_a_double_should_be_read() { Assert.That(_result.Double, Is.EqualTo(_dataReader[FieldName.Double])); } [Test] public void Then_a_column_containing_a_decimal_should_be_read() { Assert.That(_result.Decimal, Is.EqualTo(_dataReader[FieldName.Decimal])); } [Test] public void Then_a_column_containing_a_date_and_time_should_be_read() { Assert.That(_result.DateTime, Is.EqualTo(_dataReader[FieldName.DateTime])); } [Test] public void Then_a_column_containing_a_byte_should_be_read() { Assert.That(_result.Byte, Is.EqualTo(_dataReader[FieldName.Byte])); } [Test] public void Then_a_column_containing_a_boolean_should_be_read() { Assert.That(_result.Boolean, Is.EqualTo(_dataReader[FieldName.Boolean])); } [Test] public void Then_a_projected_column_should_be_read() { Assert.That(_result.Else, Is.EqualTo(_dataReader.GetDateTime(10))); } protected DTOObject _result; protected IDataReader _dataReader; } /// <summary> /// The purpose of this test is to exercise the internal caching logic of DataReaderMapper. /// </summary> public class When_mapping_a_data_reader_to_a_dto_twice : When_mapping_a_data_reader_to_a_dto { protected override void Establish_context() { base.Establish_context(); _dataReader = new DataBuilder().BuildDataReader(); _result = Mapper.Map<IDataReader, IEnumerable<DTOObject>>(_dataReader).FirstOrDefault(); } } public class When_mapping_a_data_reader_to_a_dto_and_the_map_does_not_exist : AutoMapperSpecBase { protected override void Establish_context() { _dataReader = new DataBuilder().BuildDataReader(); } [Test] public void Then_an_automapper_exception_should_be_thrown() { typeof (AutoMapperMappingException).ShouldBeThrownBy( () => Mapper.Map<IDataReader, IEnumerable<DTOObject>>(_dataReader).FirstOrDefault()); } private IDataReader _dataReader; } public class When_mapping_a_single_data_record_to_a_dto : AutoMapperSpecBase { protected override void Establish_context() { Mapper.CreateMap<IDataRecord, DTOObject>() .ForMember(dest => dest.Else, options => options.MapFrom(src => src.GetDateTime(src.GetOrdinal(FieldName.Something)))); _dataRecord = new DataBuilder().BuildDataRecord(); _result = Mapper.Map<IDataRecord, DTOObject>(_dataRecord); } [Test] public void Then_a_column_containing_a_small_integer_should_be_read() { Assert.That(_result.SmallInteger, Is.EqualTo(_dataRecord[FieldName.SmallInt])); } [Test] public void Then_a_column_containing_an_integer_should_be_read() { Assert.That(_result.Integer, Is.EqualTo(_dataRecord[FieldName.Int])); } [Test] public void Then_a_column_containing_a_big_integer_should_be_read() { Assert.That(_result.BigInteger, Is.EqualTo(_dataRecord[FieldName.BigInt])); } [Test] public void Then_a_column_containing_a_GUID_should_be_read() { Assert.That(_result.Guid, Is.EqualTo(_dataRecord[FieldName.Guid])); } [Test] public void Then_a_column_containing_a_float_should_be_read() { Assert.That(_result.Float, Is.EqualTo(_dataRecord[FieldName.Float])); } [Test] public void Then_a_column_containing_a_double_should_be_read() { Assert.That(_result.Double, Is.EqualTo(_dataRecord[FieldName.Double])); } [Test] public void Then_a_column_containing_a_decimal_should_be_read() { Assert.That(_result.Decimal, Is.EqualTo(_dataRecord[FieldName.Decimal])); } [Test] public void Then_a_column_containing_a_date_and_time_should_be_read() { Assert.That(_result.DateTime, Is.EqualTo(_dataRecord[FieldName.DateTime])); } [Test] public void Then_a_column_containing_a_byte_should_be_read() { Assert.That(_result.Byte, Is.EqualTo(_dataRecord[FieldName.Byte])); } [Test] public void Then_a_column_containing_a_boolean_should_be_read() { Assert.That(_result.Boolean, Is.EqualTo(_dataRecord[FieldName.Boolean])); } [Test] public void Then_a_projected_column_should_be_read() { Assert.That(_result.Else, Is.EqualTo(_dataRecord[FieldName.Something])); } private DTOObject _result; private IDataRecord _dataRecord; } public class When_mapping_a_data_reader_to_a_dto_with_nullable_field : AutoMapperSpecBase { internal const string FieldName = "Integer"; internal const int FieldValue = 7; internal class DtoWithSingleNullableField { public int? Integer { get; set; } } internal class DataBuilder { public IDataReader BuildDataReaderWithNullableField() { var table = new DataTable(); var col = table.Columns.Add(FieldName, typeof(int)); col.AllowDBNull = true; var row1 = table.NewRow(); row1[FieldName] = FieldValue; table.Rows.Add(row1); var row2 = table.NewRow(); row2[FieldName] = DBNull.Value; table.Rows.Add(row2); return table.CreateDataReader(); } } protected override void Establish_context() { Mapper.CreateMap<IDataReader, DtoWithSingleNullableField>(); _dataReader = new DataBuilder().BuildDataReaderWithNullableField(); } [Test] public void Then_results_should_be_as_expected() { while (_dataReader.Read()) { var dto = Mapper.Map<IDataReader, DtoWithSingleNullableField>(_dataReader); if (_dataReader.IsDBNull(0)) Assert.That(dto.Integer.HasValue, Is.EqualTo(false)); else { // uncomment the following line to see some strange fail message that might be the key to the problem Assert.That(dto.Integer.HasValue, Is.EqualTo(true)); Assert.That(dto.Integer.Value, Is.EqualTo(FieldValue)); } } } private IDataReader _dataReader; } public class When_mapping_a_data_reader_to_a_dto_with_nullable_enum : AutoMapperSpecBase { internal const string FieldName = "Value"; internal const int FieldValue = 3; public enum settlement_type { PreDelivery = 0, DVP = 1, FreeDelivery = 2, Prepayment = 3, Allocation = 4, SafeSettlement = 5, } internal class DtoWithSingleNullableField { public settlement_type? Value { get; set; } } internal class DataBuilder { public IDataReader BuildDataReaderWithNullableField() { var table = new DataTable(); var col = table.Columns.Add(FieldName, typeof(int)); col.AllowDBNull = true; var row1 = table.NewRow(); row1[FieldName] = FieldValue; table.Rows.Add(row1); var row2 = table.NewRow(); row2[FieldName] = DBNull.Value; table.Rows.Add(row2); return table.CreateDataReader(); } } protected override void Establish_context() { Mapper.CreateMap<IDataReader, DtoWithSingleNullableField>(); _dataReader = new DataBuilder().BuildDataReaderWithNullableField(); } [Test] public void Then_results_should_be_as_expected() { while (_dataReader.Read()) { //var dto = Mapper.Map<IDataReader, DtoWithSingleNullableField>(_dataReader); var dto = new DtoWithSingleNullableField(); object value = _dataReader[0]; if (!Equals(value, DBNull.Value)) dto.Value = (settlement_type)value; if (_dataReader.IsDBNull(0)) dto.Value.HasValue.ShouldBeFalse(); else { dto.Value.HasValue.ShouldBeTrue(); dto.Value.Value.ShouldEqual(settlement_type.Prepayment); } } } private IDataReader _dataReader; } internal class FieldName { public const String SmallInt = "SmallInteger"; public const String Int = "Integer"; public const String BigInt = "BigInteger"; public const String Guid = "Guid"; public const String Float = "Float"; public const String Double = "Double"; public const String Decimal = "Decimal"; public const String DateTime = "DateTime"; public const String Byte = "Byte"; public const String Boolean = "Boolean"; public const String Something = "Something"; } public class DataBuilder { public IDataReader BuildDataReader() { var authorizationSetDataTable = new DataTable(); authorizationSetDataTable.Columns.Add(FieldName.SmallInt, typeof(Int16)); authorizationSetDataTable.Columns.Add(FieldName.Int, typeof(Int32)); authorizationSetDataTable.Columns.Add(FieldName.BigInt, typeof(Int64)); authorizationSetDataTable.Columns.Add(FieldName.Guid, typeof(Guid)); authorizationSetDataTable.Columns.Add(FieldName.Float, typeof(float)); authorizationSetDataTable.Columns.Add(FieldName.Double, typeof(Double)); authorizationSetDataTable.Columns.Add(FieldName.Decimal, typeof(Decimal)); authorizationSetDataTable.Columns.Add(FieldName.DateTime, typeof(DateTime)); authorizationSetDataTable.Columns.Add(FieldName.Byte, typeof(Byte)); authorizationSetDataTable.Columns.Add(FieldName.Boolean, typeof(Boolean)); authorizationSetDataTable.Columns.Add(FieldName.Something, typeof(DateTime)); var authorizationSetDataRow = authorizationSetDataTable.NewRow(); authorizationSetDataRow[FieldName.SmallInt] = 22; authorizationSetDataRow[FieldName.Int] = 6134; authorizationSetDataRow[FieldName.BigInt] = 61346154; authorizationSetDataRow[FieldName.Guid] = Guid.NewGuid(); authorizationSetDataRow[FieldName.Float] = 642.61; authorizationSetDataRow[FieldName.Double] = 67164.64; authorizationSetDataRow[FieldName.Decimal] = 94341.61; authorizationSetDataRow[FieldName.DateTime] = DateTime.Now; authorizationSetDataRow[FieldName.Byte] = 0x12; authorizationSetDataRow[FieldName.Boolean] = true; authorizationSetDataRow[FieldName.Something] = DateTime.MaxValue; authorizationSetDataTable.Rows.Add(authorizationSetDataRow); return authorizationSetDataTable.CreateDataReader(); } public IDataRecord BuildDataRecord() { var dataReader = BuildDataReader(); dataReader.Read(); return dataReader; } } public class DTOObject { public Int16 SmallInteger { get; private set; } public Int32 Integer { get; private set; } public Int64 BigInteger { get; private set; } public Guid Guid { get; private set; } public float Float { get; private set; } public Double Double { get; private set; } public Decimal Decimal { get; private set; } public DateTime DateTime { get; private set; } public Byte Byte { get; private set; } public Boolean Boolean { get; private set; } public DateTime Else { get; private set; } } } }
/** * * Modifications by Simon Hewitt * - change constructors/methods to return byte[] * - append original source size at the end of the destination buffer * - add support for MemoryStream internal buffer usage * * * ManagedLZO.MiniLZO * * Minimalistic reimplementation of minilzo in C# * * @author Shane Eric Bryldt, Copyright (C) 2006, All Rights Reserved * @note Uses unsafe/fixed pointer contexts internally * @liscence Bound by same liscence as minilzo as below, see file COPYING */ /* Based on minilzo.c -- mini subset of the LZO real-time data compression library This file is part of the LZO real-time data compression library. Copyright (C) 2005 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2004 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2003 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2002 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2001 Markus Franz Xaver Johannes Oberhumer Copyright (C) 2000 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1999 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1998 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1997 Markus Franz Xaver Johannes Oberhumer Copyright (C) 1996 Markus Franz Xaver Johannes Oberhumer All Rights Reserved. The LZO library is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License, version 2, as published by the Free Software Foundation. The LZO library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with the LZO library; see the file COPYING. If not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. Markus F.X.J. Oberhumer <markus@oberhumer.com> http://www.oberhumer.com/opensource/lzo/ */ /* * NOTE: * the full LZO package can be found at * http://www.oberhumer.com/opensource/lzo/ */ using System; using System.IO; namespace RaptorDB { public class MiniLZO { private const uint M2_MAX_LEN = 8; private const uint M4_MAX_LEN = 9; private const byte M3_MARKER = 32; private const byte M4_MARKER = 16; private const uint M2_MAX_OFFSET = 0x0800; private const uint M3_MAX_OFFSET = 0x4000; private const uint M4_MAX_OFFSET = 0xbfff; private const byte BITS = 14; private const uint D_MASK = (1 << BITS) - 1; private static uint DICT_SIZE = 65536 + 3; static MiniLZO() { if (IntPtr.Size == 8) DICT_SIZE = (65536 + 3) * 2; } public static byte[] Compress(byte[] src) { return Compress(src, 0, src.Length); } public static byte[] Compress(byte[] src, int srcCount) { return Compress(src, 0, srcCount); } public static byte[] Compress(byte[] src, int srcStart, int srcLength) { byte[] workMem = new byte[DICT_SIZE]; uint dstlen = (uint)(srcLength + (srcLength / 16) + 64 + 3 + 4); byte[] dst = new byte[dstlen]; uint compressedSize = Compress(src, (uint)srcStart, (uint)srcLength, dst, 0, dstlen, workMem, 0); if (dst.Length != compressedSize) { byte[] final = new byte[compressedSize]; Buffer.BlockCopy(dst, 0, final, 0, (int)compressedSize); dst = final; } return dst; } public static byte[] Compress(MemoryStream source) { byte[] destinationBuffer; byte[] workspaceBuffer; uint sourceOffset; uint workspaceOffset; uint sourceLength; uint destinationLength; byte[] sourceBuffer = source.GetBuffer(); uint sourceCapacity = (uint)source.Capacity; sourceLength = (uint)source.Length; destinationLength = sourceLength + (sourceLength / 16) + 64 + 3 + 4; uint unusedSpace = sourceCapacity - sourceLength; uint inplaceOverhead = Math.Min(sourceLength, M4_MAX_OFFSET) + sourceLength / 64 + 16 + 3 + 4; if (unusedSpace < inplaceOverhead) { sourceOffset = 0; destinationBuffer = new byte[destinationLength]; } else { sourceOffset = inplaceOverhead; source.SetLength(sourceLength + inplaceOverhead); destinationBuffer = sourceBuffer; Buffer.BlockCopy(destinationBuffer, 0, destinationBuffer, (int)inplaceOverhead, (int)sourceLength); unusedSpace -= inplaceOverhead; } if (unusedSpace < DICT_SIZE) { workspaceBuffer = new byte[DICT_SIZE]; workspaceOffset = 0; } else { workspaceBuffer = sourceBuffer; workspaceOffset = sourceCapacity - DICT_SIZE; } uint compressedSize = Compress(sourceBuffer, sourceOffset, sourceLength, destinationBuffer, 0, destinationLength, workspaceBuffer, workspaceOffset); if (destinationBuffer == sourceBuffer) { source.SetLength(compressedSize); source.Capacity = (int)compressedSize; return source.GetBuffer(); } else { byte[] final = new byte[compressedSize]; Buffer.BlockCopy(destinationBuffer, 0, final, 0, (int)compressedSize); return final; } } private static unsafe uint Compress(byte[] src, uint srcstart, uint srcLength, byte[] dst, uint dststart, uint dstlen, byte[] workmem, uint workmemstart) { uint tmp; if (srcLength <= M2_MAX_LEN + 5) { tmp = (uint)srcLength; dstlen = 0; } else { fixed (byte* work = &workmem[workmemstart], input = &src[srcstart], output = &dst[dststart]) { byte** dict = (byte**)work; byte* in_end = input + srcLength; byte* ip_end = input + srcLength - M2_MAX_LEN - 5; byte* ii = input; byte* ip = input + 4; byte* op = output; bool literal = false; bool match = false; uint offset; uint length; uint index; byte* pos; for (; ; ) { offset = 0; index = D_INDEX1(ip); pos = ip - (ip - dict[index]); if (pos < input || (offset = (uint)(ip - pos)) <= 0 || offset > M4_MAX_OFFSET) literal = true; else if (offset <= M2_MAX_OFFSET || pos[3] == ip[3]) { } else { index = D_INDEX2(index); pos = ip - (ip - dict[index]); if (pos < input || (offset = (uint)(ip - pos)) <= 0 || offset > M4_MAX_OFFSET) literal = true; else if (offset <= M2_MAX_OFFSET || pos[3] == ip[3]) { } else literal = true; } if (!literal) { if (*((ushort*)pos) == *((ushort*)ip) && pos[2] == ip[2]) match = true; } literal = false; if (!match) { dict[index] = ip; ++ip; if (ip >= ip_end) break; continue; } match = false; dict[index] = ip; if (ip - ii > 0) { uint t = (uint)(ip - ii); if (t <= 3) { //Debug.Assert(op - 2 > output); op[-2] |= (byte)(t); } else if (t <= 18) *op++ = (byte)(t - 3); else { uint tt = t - 18; *op++ = 0; while (tt > 255) { tt -= 255; *op++ = 0; } //Debug.Assert(tt > 0); *op++ = (byte)(tt); } do { *op++ = *ii++; } while (--t > 0); } //Debug.Assert(ii == ip); ip += 3; if (pos[3] != *ip++ || pos[4] != *ip++ || pos[5] != *ip++ || pos[6] != *ip++ || pos[7] != *ip++ || pos[8] != *ip++) { --ip; length = (uint)(ip - ii); //Debug.Assert(length >= 3); //Debug.Assert(length <= M2_MAX_LEN); if (offset <= M2_MAX_OFFSET) { --offset; *op++ = (byte)(((length - 1) << 5) | ((offset & 7) << 2)); *op++ = (byte)(offset >> 3); } else if (offset <= M3_MAX_OFFSET) { --offset; *op++ = (byte)(M3_MARKER | (length - 2)); *op++ = (byte)((offset & 63) << 2); *op++ = (byte)(offset >> 6); } else { offset -= 0x4000; //Debug.Assert(offset > 0); //Debug.Assert(offset <= 0x7FFF); *op++ = (byte)(M4_MARKER | ((offset & 0x4000) >> 11) | (length - 2)); *op++ = (byte)((offset & 63) << 2); *op++ = (byte)(offset >> 6); } } else { byte* m = pos + M2_MAX_LEN + 1; while (ip < in_end && *m == *ip) { ++m; ++ip; } length = (uint)(ip - ii); //Debug.Assert(length > M2_MAX_LEN); if (offset <= M3_MAX_OFFSET) { --offset; if (length <= 33) *op++ = (byte)(M3_MARKER | (length - 2)); else { length -= 33; *op++ = M3_MARKER | 0; while (length > 255) { length -= 255; *op++ = 0; } //Debug.Assert(length > 0); *op++ = (byte)(length); } } else { offset -= 0x4000; //Debug.Assert(offset > 0); //Debug.Assert(offset <= 0x7FFF); if (length <= M4_MAX_LEN) *op++ = (byte)(M4_MARKER | ((offset & 0x4000) >> 11) | (length - 2)); else { length -= M4_MAX_LEN; *op++ = (byte)(M4_MARKER | ((offset & 0x4000) >> 11)); while (length > 255) { length -= 255; *op++ = 0; } //Debug.Assert(length > 0); *op++ = (byte)(length); } } *op++ = (byte)((offset & 63) << 2); *op++ = (byte)(offset >> 6); } ii = ip; if (ip >= ip_end) break; } dstlen = (uint)(op - output); tmp = (uint)(in_end - ii); } } if (tmp > 0) { uint ii = (uint)srcLength - tmp + srcstart; if (dstlen == 0 && tmp <= 238) { dst[dstlen++] = (byte)(17 + tmp); } else if (tmp <= 3) { dst[dstlen - 2] |= (byte)(tmp); } else if (tmp <= 18) { dst[dstlen++] = (byte)(tmp - 3); } else { uint tt = tmp - 18; dst[dstlen++] = 0; while (tt > 255) { tt -= 255; dst[dstlen++] = 0; } //Debug.Assert(tt > 0); dst[dstlen++] = (byte)(tt); } do { dst[dstlen++] = src[ii++]; } while (--tmp > 0); } dst[dstlen++] = M4_MARKER | 1; dst[dstlen++] = 0; dst[dstlen++] = 0; // Append the source count dst[dstlen++] = (byte)srcLength; dst[dstlen++] = (byte)(srcLength >> 8); dst[dstlen++] = (byte)(srcLength >> 16); dst[dstlen++] = (byte)(srcLength >> 24); return dstlen; } public static unsafe byte[] Decompress(byte[] src) { byte[] dst = new byte[(src[src.Length - 4] | (src[src.Length - 3] << 8) | (src[src.Length - 2] << 16 | src[src.Length - 1] << 24))]; uint t = 0; fixed (byte* input = src, output = dst) { byte* pos = null; byte* ip_end = input + src.Length - 4; byte* op_end = output + dst.Length; byte* ip = input; byte* op = output; bool match = false; bool match_next = false; bool match_done = false; bool copy_match = false; bool first_literal_run = false; bool eof_found = false; if (*ip > 17) { t = (uint)(*ip++ - 17); if (t < 4) match_next = true; else { //Debug.Assert(t > 0); if ((op_end - op) < t) throw new OverflowException("Output Overrun"); if ((ip_end - ip) < t + 1) throw new OverflowException("Input Overrun"); do { *op++ = *ip++; } while (--t > 0); first_literal_run = true; } } while (!eof_found && ip < ip_end) { if (!match_next && !first_literal_run) { t = *ip++; if (t >= 16) match = true; else { if (t == 0) { if ((ip_end - ip) < 1) throw new OverflowException("Input Overrun"); while (*ip == 0) { t += 255; ++ip; if ((ip_end - ip) < 1) throw new OverflowException("Input Overrun"); } t += (uint)(15 + *ip++); } //Debug.Assert(t > 0); if ((op_end - op) < t + 3) throw new OverflowException("Output Overrun"); if ((ip_end - ip) < t + 4) throw new OverflowException("Input Overrun"); for (int x = 0; x < 4; ++x, ++op, ++ip) *op = *ip; if (--t > 0) { if (t >= 4) { do { for (int x = 0; x < 4; ++x, ++op, ++ip) *op = *ip; t -= 4; } while (t >= 4); if (t > 0) { do { *op++ = *ip++; } while (--t > 0); } } else { do { *op++ = *ip++; } while (--t > 0); } } } } if (!match && !match_next) { first_literal_run = false; t = *ip++; if (t >= 16) match = true; else { pos = op - (1 + M2_MAX_OFFSET); pos -= t >> 2; pos -= *ip++ << 2; if (pos < output || pos >= op) throw new OverflowException("Lookbehind Overrun"); if ((op_end - op) < 3) throw new OverflowException("Output Overrun"); *op++ = *pos++; *op++ = *pos++; *op++ = *pos++; match_done = true; } } match = false; do { if (t >= 64) { pos = op - 1; pos -= (t >> 2) & 7; pos -= *ip++ << 3; t = (t >> 5) - 1; if (pos < output || pos >= op) throw new OverflowException("Lookbehind Overrun"); if ((op_end - op) < t + 2) throw new OverflowException("Output Overrun"); copy_match = true; } else if (t >= 32) { t &= 31; if (t == 0) { if ((ip_end - ip) < 1) throw new OverflowException("Input Overrun"); while (*ip == 0) { t += 255; ++ip; if ((ip_end - ip) < 1) throw new OverflowException("Input Overrun"); } t += (uint)(31 + *ip++); } pos = op - 1; pos -= (*(ushort*)ip) >> 2; ip += 2; } else if (t >= 16) { pos = op; pos -= (t & 8) << 11; t &= 7; if (t == 0) { if ((ip_end - ip) < 1) throw new OverflowException("Input Overrun"); while (*ip == 0) { t += 255; ++ip; if ((ip_end - ip) < 1) throw new OverflowException("Input Overrun"); } t += (uint)(7 + *ip++); } pos -= (*(ushort*)ip) >> 2; ip += 2; if (pos == op) eof_found = true; else pos -= 0x4000; } else { pos = op - 1; pos -= t >> 2; pos -= *ip++ << 2; if (pos < output || pos >= op) throw new OverflowException("Lookbehind Overrun"); if ((op_end - op) < 2) throw new OverflowException("Output Overrun"); *op++ = *pos++; *op++ = *pos++; match_done = true; } if (!eof_found && !match_done && !copy_match) { if (pos < output || pos >= op) throw new OverflowException("Lookbehind Overrun"); //Debug.Assert(t > 0); if ((op_end - op) < t + 2) throw new OverflowException("Output Overrun"); } if (!eof_found && t >= 2 * 4 - 2 && (op - pos) >= 4 && !match_done && !copy_match) { for (int x = 0; x < 4; ++x, ++op, ++pos) *op = *pos; t -= 2; do { for (int x = 0; x < 4; ++x, ++op, ++pos) *op = *pos; t -= 4; } while (t >= 4); if (t > 0) { do { *op++ = *pos++; } while (--t > 0); } } else if (!eof_found && !match_done) { copy_match = false; *op++ = *pos++; *op++ = *pos++; do { *op++ = *pos++; } while (--t > 0); } if (!eof_found && !match_next) { match_done = false; t = (uint)(ip[-2] & 3); if (t == 0) break; } if (!eof_found) { match_next = false; //Debug.Assert(t > 0); //Debug.Assert(t < 4); if ((op_end - op) < t) throw new OverflowException("Output Overrun"); if ((ip_end - ip) < t + 1) throw new OverflowException("Input Overrun"); *op++ = *ip++; if (t > 1) { *op++ = *ip++; if (t > 2) *op++ = *ip++; } t = *ip++; } } while (!eof_found && ip < ip_end); } if (!eof_found) throw new OverflowException("EOF Marker Not Found"); else { //Debug.Assert(t == 1); if (ip > ip_end) throw new OverflowException("Input Overrun"); else if (ip < ip_end) throw new OverflowException("Input Not Consumed"); } } return dst; } private unsafe static uint D_INDEX1(byte* input) { return D_MS(D_MUL(0x21, D_X3(input, 5, 5, 6)) >> 5, 0); } private static uint D_INDEX2(uint idx) { return (idx & (D_MASK & 0x7FF)) ^ (((D_MASK >> 1) + 1) | 0x1F); } private static uint D_MS(uint v, byte s) { return (v & (D_MASK >> s)) << s; } private static uint D_MUL(uint a, uint b) { return a * b; } private unsafe static uint D_X2(byte* input, byte s1, byte s2) { return (uint)((((input[2] << s2) ^ input[1]) << s1) ^ input[0]); } private unsafe static uint D_X3(byte* input, byte s1, byte s2, byte s3) { return (D_X2(input + 1, s2, s3) << s1) ^ input[0]; } } }
//------------------------------------------------------------------------------ // <copyright file="ReflectaClient.cs" company="Microsoft Corporation"> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> //------------------------------------------------------------------------------ namespace Microsoft.Robotics.Tests.Reflecta { using System; using System.Diagnostics; using System.IO.Ports; using System.Text; using System.Threading; using System.Threading.Tasks; public class ReflectaClient : IDisposable { private static readonly TraceSource traceSource = new TraceSource("ReflectaClient"); private readonly SerialPort _port; private readonly CancellationTokenSource _cts = new CancellationTokenSource(); private byte _writeChecksum; private byte _writeSequence; private bool _escaped; // protocol parser escape state private byte _readChecksum; private ReadState _state = ReadState.WaitingForSequence; // protocol parser state private byte? _readSequence; private byte[] _frameBuffer; private byte _frameIndex; public ReflectaClient(string portName) { _port = new SerialPort(portName, 19200); _port.Open(); Task.Factory.StartNew(() => { while (!_cts.IsCancellationRequested) { ReflectaLoop(); Thread.Sleep(0); } }, _cts.Token); } public event EventHandler<MessageEventArgs> ErrorReceived; public event EventHandler<MessageEventArgs> MessageReceived; public event EventHandler<FrameReceivedEventArgs> FrameReceived; public event EventHandler<ResponseReceivedEventArgs> ResponseReceived; public enum FunctionId : byte { PushArray = 0x00, QueryInterface = 0x01, Response = 0x7D, Message = 0x7E, Error = 0x7F } private enum ProtocolMessage : byte { OutOfSequence, UnexpectedEscape, CrcMismatch, UnexpectedEnd, BufferOverflow, FrameTooSmall, FunctionConflict, FunctionNotFound, ParameterMismatch, StackOverflow, StackUnderflow } // Packet format is: // Frame Sequence #, SLIP escaped // Byte(s) of Payload, SLIP escaped // CRC8 of Sequence # & Payload bytes, SLIP escaped // SLIP END (0xc0) private enum ReadState { /// <summary> /// Beginning of a new frame, waiting for the Sequence number /// </summary> WaitingForSequence, /// <summary> /// Reading data until an END character is found /// </summary> WaitingForBytecode, /// <summary> /// END character found, check CRC and deliver frame /// </summary> ProcessPayload, /// <summary> /// Current frame is invalid, wait for an END character and start parsing again /// </summary> WaitingForRecovery } /// <summary> /// Slip special characters /// </summary> private enum Slip : byte { /// <summary> /// Slip End /// </summary> End = 0xC0, /// <summary> /// Slip Escape /// </summary> Escape = 0xDB, /// <summary> /// Slip Escaped End /// </summary> EscapedEnd = 0xDC, /// <summary> /// Slip Escaped Escape /// </summary> EscapedEscape = 0xDD } public static TraceSource TraceSource { get { return traceSource; } } public void Dispose() { _cts.Cancel(); _port.Dispose(); _cts.Dispose(); } public void SendFrame(byte[] frame) { _writeChecksum = 0; WriteEscaped(_writeSequence++); for (byte index = 0; index < frame.Length; index++) { WriteEscaped(frame[index]); } WriteEscaped(_writeChecksum); Write((byte)Slip.End); } private byte _sequence; // Read the uncoming data stream, to be called inside Arduino loop() private void ReflectaLoop() { while (Available()) { byte b; if (ReadUnescaped(out b)) { switch (_state) { case ReadState.WaitingForRecovery: break; case ReadState.WaitingForSequence: _sequence = b; if (_readSequence == null) { _readSequence = _sequence; } else if (++_readSequence != _sequence) { Console.WriteLine("SEQ Expected {0} received {1}", _readSequence, _sequence); _readSequence = _sequence; if (ErrorReceived != null) { ErrorReceived(this, new MessageEventArgs("Out of Sequence")); } } _readChecksum = _sequence; _frameIndex = 0; // Reset the buffer pointer to beginning _frameBuffer = new byte[80]; _state = ReadState.WaitingForBytecode; break; case ReadState.WaitingForBytecode: if (_frameIndex == _frameBuffer.Length) { if (ErrorReceived != null) { ErrorReceived(this, new MessageEventArgs("Buffer Overflow")); } _state = ReadState.WaitingForRecovery; } else { _frameBuffer[_frameIndex++] = b; } break; case ReadState.ProcessPayload: // zero expected because finally XOR'd with itself if (_readChecksum == 0) { _frameIndex--; // Remove the checksum byte from the frame data if (_frameBuffer[0] == (byte)FunctionId.Error) { Debug.Assert(_frameIndex == 2); if (ErrorReceived != null) { string message = "Teensy Unknown"; switch (_frameBuffer[1]) { case (byte)ProtocolMessage.OutOfSequence: message = "Teensy Out Of Sequence"; break; case (byte)ProtocolMessage.UnexpectedEscape: message = "Teensy Unexpected Escape"; break; case (byte)ProtocolMessage.CrcMismatch: message = "Teensy Crc Mismatch"; break; case (byte)ProtocolMessage.UnexpectedEnd: message = "Teensy Unexpected End"; break; case (byte)ProtocolMessage.BufferOverflow: message = "Teensy Buffer Overflow"; break; case (byte)ProtocolMessage.FrameTooSmall: message = "Teensy Frame Too Small"; break; case (byte)ProtocolMessage.FunctionConflict: message = "Teensy Function Conflict"; break; case (byte)ProtocolMessage.FunctionNotFound: message = "Teensy Function Not Found"; break; case (byte)ProtocolMessage.ParameterMismatch: message = "Teensy Parameter Mismatch"; break; case (byte)ProtocolMessage.StackOverflow: message = "Teensy Stack Overflow"; break; case (byte)ProtocolMessage.StackUnderflow: message = "Teensy Stack Underflow"; break; default: break; } ErrorReceived(this, new MessageEventArgs(message)); } } else if (_frameIndex > 1 && _frameBuffer[0] == (byte)FunctionId.Message) { var messageLength = _frameBuffer[1]; var message = Encoding.UTF8.GetString(_frameBuffer, 2, messageLength); if (MessageReceived != null) { MessageReceived(this, new MessageEventArgs(message)); } } else if (_frameIndex > 2 && _frameBuffer[0] == (byte)FunctionId.Response) { var senderSequence = _frameBuffer[1]; var parameterLength = _frameBuffer[2]; var parameter = new byte[parameterLength]; Array.Copy(_frameBuffer, 3, parameter, 0, parameterLength); if (ResponseReceived != null) { ResponseReceived(this, new ResponseReceivedEventArgs(senderSequence, parameter)); } } else { if (FrameReceived != null) { var frame = new byte[_frameIndex]; Array.Copy(_frameBuffer, 0, frame, 0, _frameIndex); FrameReceived(this, new FrameReceivedEventArgs(_sequence, frame)); } } } else { if (ErrorReceived != null) { ErrorReceived(this, new MessageEventArgs("CRC Mismatch")); } _state = ReadState.WaitingForRecovery; } _state = ReadState.WaitingForSequence; break; } } } } private void WriteEscaped(byte b) { switch (b) { case (byte)Slip.End: Write((byte)Slip.Escape); Write((byte)Slip.EscapedEnd); break; case (byte)Slip.Escape: Write((byte)Slip.Escape); Write((byte)Slip.EscapedEscape); break; default: Write(b); break; } _writeChecksum ^= b; } private void Write(byte b) { _port.Write(new[] { b }, 0, 1); } private byte Read() { return (byte)_port.ReadByte(); } private bool Available() { return _port.BytesToRead > 0; } private bool ReadUnescaped(out byte b) { b = Read(); if (_escaped) { switch (b) { case (byte)Slip.EscapedEnd: b = (byte)Slip.End; break; case (byte)Slip.EscapedEscape: b = (byte)Slip.Escape; break; default: if (ErrorReceived != null) { ErrorReceived(this, new MessageEventArgs("Unexpected Escape")); } _state = ReadState.WaitingForRecovery; break; } _escaped = false; _readChecksum ^= b; } else { if (b == (byte)Slip.Escape) { _escaped = true; return false; // read escaped value on next pass } if (b == (byte)Slip.End) { switch (_state) { case ReadState.WaitingForRecovery: _readSequence = null; _state = ReadState.WaitingForSequence; break; case ReadState.WaitingForBytecode: _state = ReadState.ProcessPayload; break; default: if (ErrorReceived != null) { ErrorReceived(this, new MessageEventArgs("Unexpected End")); } _state = ReadState.WaitingForRecovery; break; } } else { _readChecksum ^= b; } } return true; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace Checky.Slack.TestEditor.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { internal const int DefaultCollectionSize = 2; private readonly SimpleTypeObjectGenerator SimpleObjectGenerator = new SimpleTypeObjectGenerator(); /// <summary> /// Generates an object for a given type. The type needs to be public, have a public default constructor and settable public properties/fields. Currently it supports the following types: /// Simple types: <see cref="int"/>, <see cref="string"/>, <see cref="Enum"/>, <see cref="DateTime"/>, <see cref="Uri"/>, etc. /// Complex types: POCO types. /// Nullables: <see cref="Nullable{T}"/>. /// Arrays: arrays of simple types or complex types. /// Key value pairs: <see cref="KeyValuePair{TKey,TValue}"/> /// Tuples: <see cref="Tuple{T1}"/>, <see cref="Tuple{T1,T2}"/>, etc /// Dictionaries: <see cref="IDictionary{TKey,TValue}"/> or anything deriving from <see cref="IDictionary{TKey,TValue}"/>. /// Collections: <see cref="IList{T}"/>, <see cref="IEnumerable{T}"/>, <see cref="ICollection{T}"/>, <see cref="IList"/>, <see cref="IEnumerable"/>, <see cref="ICollection"/> or anything deriving from <see cref="ICollection{T}"/> or <see cref="IList"/>. /// Queryables: <see cref="IQueryable"/>, <see cref="IQueryable{T}"/>. /// </summary> /// <param name="type">The type.</param> /// <returns>An object of the given type.</returns> public object GenerateObject(Type type) { return GenerateObject(type, new Dictionary<Type, object>()); } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "Here we just want to return null if anything goes wrong.")] private object GenerateObject(Type type, Dictionary<Type, object> createdObjectReferences) { try { if (SimpleTypeObjectGenerator.CanGenerateObject(type)) { return SimpleObjectGenerator.GenerateObject(type); } if (type.IsArray) { return GenerateArray(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsGenericType) { return GenerateGenericType(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IDictionary)) { return GenerateDictionary(typeof(Hashtable), DefaultCollectionSize, createdObjectReferences); } if (typeof(IDictionary).IsAssignableFrom(type)) { return GenerateDictionary(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IList) || type == typeof(IEnumerable) || type == typeof(ICollection)) { return GenerateCollection(typeof(ArrayList), DefaultCollectionSize, createdObjectReferences); } if (typeof(IList).IsAssignableFrom(type)) { return GenerateCollection(type, DefaultCollectionSize, createdObjectReferences); } if (type == typeof(IQueryable)) { return GenerateQueryable(type, DefaultCollectionSize, createdObjectReferences); } if (type.IsEnum) { return GenerateEnum(type); } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } } catch { // Returns null if anything fails return null; } return null; } private static object GenerateGenericType(Type type, int collectionSize, Dictionary<Type, object> createdObjectReferences) { Type genericTypeDefinition = type.GetGenericTypeDefinition(); if (genericTypeDefinition == typeof(Nullable<>)) { return GenerateNullable(type, createdObjectReferences); } if (genericTypeDefinition == typeof(KeyValuePair<,>)) { return GenerateKeyValuePair(type, createdObjectReferences); } if (IsTuple(genericTypeDefinition)) { return GenerateTuple(type, createdObjectReferences); } Type[] genericArguments = type.GetGenericArguments(); if (genericArguments.Length == 1) { if (genericTypeDefinition == typeof(IList<>) || genericTypeDefinition == typeof(IEnumerable<>) || genericTypeDefinition == typeof(ICollection<>)) { Type collectionType = typeof(List<>).MakeGenericType(genericArguments); return GenerateCollection(collectionType, collectionSize, createdObjectReferences); } if (genericTypeDefinition == typeof(IQueryable<>)) { return GenerateQueryable(type, collectionSize, createdObjectReferences); } Type closedCollectionType = typeof(ICollection<>).MakeGenericType(genericArguments[0]); if (closedCollectionType.IsAssignableFrom(type)) { return GenerateCollection(type, collectionSize, createdObjectReferences); } } if (genericArguments.Length == 2) { if (genericTypeDefinition == typeof(IDictionary<,>)) { Type dictionaryType = typeof(Dictionary<,>).MakeGenericType(genericArguments); return GenerateDictionary(dictionaryType, collectionSize, createdObjectReferences); } Type closedDictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments[0], genericArguments[1]); if (closedDictionaryType.IsAssignableFrom(type)) { return GenerateDictionary(type, collectionSize, createdObjectReferences); } } if (type.IsPublic || type.IsNestedPublic) { return GenerateComplexObject(type, createdObjectReferences); } return null; } private static object GenerateTuple(Type type, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = type.GetGenericArguments(); object[] parameterValues = new object[genericArgs.Length]; bool failedToCreateTuple = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < genericArgs.Length; i++) { parameterValues[i] = objectGenerator.GenerateObject(genericArgs[i], createdObjectReferences); failedToCreateTuple &= parameterValues[i] == null; } if (failedToCreateTuple) { return null; } object result = Activator.CreateInstance(type, parameterValues); return result; } private static bool IsTuple(Type genericTypeDefinition) { return genericTypeDefinition == typeof(Tuple<>) || genericTypeDefinition == typeof(Tuple<,>) || genericTypeDefinition == typeof(Tuple<,,>) || genericTypeDefinition == typeof(Tuple<,,,>) || genericTypeDefinition == typeof(Tuple<,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,>) || genericTypeDefinition == typeof(Tuple<,,,,,,,>); } private static object GenerateKeyValuePair(Type keyValuePairType, Dictionary<Type, object> createdObjectReferences) { Type[] genericArgs = keyValuePairType.GetGenericArguments(); Type typeK = genericArgs[0]; Type typeV = genericArgs[1]; ObjectGenerator objectGenerator = new ObjectGenerator(); object keyObject = objectGenerator.GenerateObject(typeK, createdObjectReferences); object valueObject = objectGenerator.GenerateObject(typeV, createdObjectReferences); if (keyObject == null && valueObject == null) { // Failed to create key and values return null; } object result = Activator.CreateInstance(keyValuePairType, keyObject, valueObject); return result; } private static object GenerateArray(Type arrayType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = arrayType.GetElementType(); Array result = Array.CreateInstance(type, size); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); result.SetValue(element, i); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateDictionary(Type dictionaryType, int size, Dictionary<Type, object> createdObjectReferences) { Type typeK = typeof(object); Type typeV = typeof(object); if (dictionaryType.IsGenericType) { Type[] genericArgs = dictionaryType.GetGenericArguments(); typeK = genericArgs[0]; typeV = genericArgs[1]; } object result = Activator.CreateInstance(dictionaryType); MethodInfo addMethod = dictionaryType.GetMethod("Add") ?? dictionaryType.GetMethod("TryAdd"); MethodInfo containsMethod = dictionaryType.GetMethod("Contains") ?? dictionaryType.GetMethod("ContainsKey"); ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object newKey = objectGenerator.GenerateObject(typeK, createdObjectReferences); if (newKey == null) { // Cannot generate a valid key return null; } bool containsKey = (bool)containsMethod.Invoke(result, new object[] { newKey }); if (!containsKey) { object newValue = objectGenerator.GenerateObject(typeV, createdObjectReferences); addMethod.Invoke(result, new object[] { newKey, newValue }); } } return result; } private static object GenerateEnum(Type enumType) { Array possibleValues = Enum.GetValues(enumType); if (possibleValues.Length > 0) { return possibleValues.GetValue(0); } return null; } private static object GenerateQueryable(Type queryableType, int size, Dictionary<Type, object> createdObjectReferences) { bool isGeneric = queryableType.IsGenericType; object list; if (isGeneric) { Type listType = typeof(List<>).MakeGenericType(queryableType.GetGenericArguments()); list = GenerateCollection(listType, size, createdObjectReferences); } else { list = GenerateArray(typeof(object[]), size, createdObjectReferences); } if (list == null) { return null; } if (isGeneric) { Type argumentType = typeof(IEnumerable<>).MakeGenericType(queryableType.GetGenericArguments()); MethodInfo asQueryableMethod = typeof(Queryable).GetMethod("AsQueryable", new[] { argumentType }); return asQueryableMethod.Invoke(null, new[] { list }); } return Queryable.AsQueryable((IEnumerable)list); } private static object GenerateCollection(Type collectionType, int size, Dictionary<Type, object> createdObjectReferences) { Type type = collectionType.IsGenericType ? collectionType.GetGenericArguments()[0] : typeof(object); object result = Activator.CreateInstance(collectionType); MethodInfo addMethod = collectionType.GetMethod("Add"); bool areAllElementsNull = true; ObjectGenerator objectGenerator = new ObjectGenerator(); for (int i = 0; i < size; i++) { object element = objectGenerator.GenerateObject(type, createdObjectReferences); addMethod.Invoke(result, new object[] { element }); areAllElementsNull &= element == null; } if (areAllElementsNull) { return null; } return result; } private static object GenerateNullable(Type nullableType, Dictionary<Type, object> createdObjectReferences) { Type type = nullableType.GetGenericArguments()[0]; ObjectGenerator objectGenerator = new ObjectGenerator(); return objectGenerator.GenerateObject(type, createdObjectReferences); } private static object GenerateComplexObject(Type type, Dictionary<Type, object> createdObjectReferences) { object result = null; if (createdObjectReferences.TryGetValue(type, out result)) { // The object has been created already, just return it. This will handle the circular reference case. return result; } if (type.IsValueType) { result = Activator.CreateInstance(type); } else { ConstructorInfo defaultCtor = type.GetConstructor(Type.EmptyTypes); if (defaultCtor == null) { // Cannot instantiate the type because it doesn't have a default constructor return null; } result = defaultCtor.Invoke(new object[0]); } createdObjectReferences.Add(type, result); SetPublicProperties(type, result, createdObjectReferences); SetPublicFields(type, result, createdObjectReferences); return result; } private static void SetPublicProperties(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { PropertyInfo[] properties = type.GetProperties(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (PropertyInfo property in properties) { if (property.CanWrite) { object propertyValue = objectGenerator.GenerateObject(property.PropertyType, createdObjectReferences); property.SetValue(obj, propertyValue, null); } } } private static void SetPublicFields(Type type, object obj, Dictionary<Type, object> createdObjectReferences) { FieldInfo[] fields = type.GetFields(BindingFlags.Public | BindingFlags.Instance); ObjectGenerator objectGenerator = new ObjectGenerator(); foreach (FieldInfo field in fields) { object fieldValue = objectGenerator.GenerateObject(field.FieldType, createdObjectReferences); field.SetValue(obj, fieldValue); } } private class SimpleTypeObjectGenerator { private long _index = 0; private static readonly Dictionary<Type, Func<long, object>> DefaultGenerators = InitializeGenerators(); [SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity", Justification = "These are simple type factories and cannot be split up.")] private static Dictionary<Type, Func<long, object>> InitializeGenerators() { return new Dictionary<Type, Func<long, object>> { { typeof(Boolean), index => true }, { typeof(Byte), index => (Byte)64 }, { typeof(Char), index => (Char)65 }, { typeof(DateTime), index => DateTime.Now }, { typeof(DateTimeOffset), index => new DateTimeOffset(DateTime.Now) }, { typeof(DBNull), index => DBNull.Value }, { typeof(Decimal), index => (Decimal)index }, { typeof(Double), index => (Double)(index + 0.1) }, { typeof(Guid), index => Guid.NewGuid() }, { typeof(Int16), index => (Int16)(index % Int16.MaxValue) }, { typeof(Int32), index => (Int32)(index % Int32.MaxValue) }, { typeof(Int64), index => (Int64)index }, { typeof(Object), index => new object() }, { typeof(SByte), index => (SByte)64 }, { typeof(Single), index => (Single)(index + 0.1) }, { typeof(String), index => { return String.Format(CultureInfo.CurrentCulture, "sample string {0}", index); } }, { typeof(TimeSpan), index => { return TimeSpan.FromTicks(1234567); } }, { typeof(UInt16), index => (UInt16)(index % UInt16.MaxValue) }, { typeof(UInt32), index => (UInt32)(index % UInt32.MaxValue) }, { typeof(UInt64), index => (UInt64)index }, { typeof(Uri), index => { return new Uri(String.Format(CultureInfo.CurrentCulture, "http://webapihelppage{0}.com", index)); } }, }; } public static bool CanGenerateObject(Type type) { return DefaultGenerators.ContainsKey(type); } public object GenerateObject(Type type) { return DefaultGenerators[type](++_index); } } } }