context
stringlengths
2.52k
185k
gt
stringclasses
1 value
using System; using System.IO; using System.Net; using System.Runtime.Serialization; using System.Text; using System.Threading; using Funq; using NUnit.Framework; using ServiceStack.Common.Web; using ServiceStack.Service; using ServiceStack.ServiceClient.Web; using ServiceStack.ServiceHost; using ServiceStack.ServiceInterface.ServiceModel; using ServiceStack.Text; using ServiceStack.WebHost.Endpoints.Support; using ServiceStack.WebHost.Endpoints.Tests.Support; using ServiceStack.WebHost.Endpoints.Tests.Support.Host; namespace ServiceStack.WebHost.Endpoints.Tests { [DataContract] [Route("/secure")] public class Secure { [DataMember] public string UserName { get; set; } } [DataContract] public class SecureResponse : IHasResponseStatus { [DataMember] public string Result { get; set; } [DataMember] public ResponseStatus ResponseStatus { get; set; } } public class SecureService : IService<Secure> { public object Execute(Secure request) { return new SecureResponse { Result = "Confidential" }; } } [DataContract] [Route("/insecure")] public class Insecure { [DataMember] public string UserName { get; set; } } [DataContract] public class InsecureResponse : IHasResponseStatus { [DataMember] public string Result { get; set; } [DataMember] public ResponseStatus ResponseStatus { get; set; } } public class InsecureService : IService<Insecure> { public object Execute(Insecure request) { return new InsecureResponse { Result = "Public" }; } } [TestFixture] public abstract class RequestFiltersTests { private const string ListeningOn = "http://localhost:82/"; private const string ServiceClientBaseUri = "http://localhost:82/"; private const string AllowedUser = "user"; private const string AllowedPass = "p@55word"; public class RequestFiltersAppHostHttpListener : AppHostHttpListenerBase { private Guid currentSessionGuid; public RequestFiltersAppHostHttpListener() : base("Request Filters Tests", typeof(GetFactorialService).Assembly) { } public override void Configure(Container container) { this.RequestFilters.Add((req, res, dto) => { var userPass = req.GetBasicAuthUserAndPassword(); if (userPass == null) { return; } var userName = userPass.Value.Key; if (userName == AllowedUser && userPass.Value.Value == AllowedPass) { currentSessionGuid = Guid.NewGuid(); var sessionKey = userName + "/" + currentSessionGuid.ToString("N"); //set session for this request (as no cookies will be set on this request) req.Items["ss-session"] = sessionKey; res.SetPermanentCookie("ss-session", sessionKey); } }); this.RequestFilters.Add((req, res, dto) => { if (dto is Secure) { var sessionId = req.GetItemOrCookie("ss-session") ?? string.Empty; var sessionIdParts = sessionId.SplitOnFirst('/'); if (sessionIdParts.Length < 2 || sessionIdParts[0] != AllowedUser || sessionIdParts[1] != currentSessionGuid.ToString("N")) { res.ReturnAuthRequired(); } } }); } } RequestFiltersAppHostHttpListener appHost; [TestFixtureSetUp] public void OnTestFixtureSetUp() { appHost = new RequestFiltersAppHostHttpListener(); appHost.Init(); appHost.Start(ListeningOn); } [TestFixtureTearDown] public void OnTestFixtureTearDown() { appHost.Dispose(); EndpointHandlerBase.ServiceManager = null; } protected abstract IServiceClient CreateNewServiceClient(); protected abstract IRestClientAsync CreateNewRestClientAsync(); protected virtual string GetFormat() { return null; } private static void Assert401(IServiceClient client, WebServiceException ex) { if (client is Soap11ServiceClient || client is Soap12ServiceClient) { if (ex.StatusCode != 401) { Console.WriteLine("WARNING: SOAP clients returning 500 instead of 401"); } return; } Console.WriteLine(ex); Assert.That(ex.StatusCode, Is.EqualTo(401)); } private static void FailOnAsyncError<T>(T response, Exception ex) { Assert.Fail(ex.Message); } private static bool Assert401(object response, Exception ex) { var webEx = (WebServiceException)ex; Assert.That(webEx.StatusCode, Is.EqualTo(401)); return true; } [Test] public void Can_login_with_Basic_auth_to_access_Secure_service() { var format = GetFormat(); if (format == null) return; var req = (HttpWebRequest)WebRequest.Create( string.Format("http://localhost:82/{0}/syncreply/Secure", format)); req.Headers[HttpHeaders.Authorization] = "basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(AllowedUser + ":" + AllowedPass)); var dtoString = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd(); Assert.That(dtoString.Contains("Confidential")); Console.WriteLine(dtoString); } [Test] public void Can_login_with_Basic_auth_to_access_Secure_service_using_ServiceClient() { var format = GetFormat(); if (format == null) return; var client = CreateNewServiceClient(); client.SetCredentials(AllowedUser, AllowedPass); var response = client.Send<SecureResponse>(new Secure()); Assert.That(response.Result, Is.EqualTo("Confidential")); } [Test] public void Can_login_with_Basic_auth_to_access_Secure_service_using_RestClientAsync() { var format = GetFormat(); if (format == null) return; var client = CreateNewRestClientAsync(); client.SetCredentials(AllowedUser, AllowedPass); SecureResponse response = null; client.GetAsync<SecureResponse>(ServiceClientBaseUri + "secure", r => response = r, FailOnAsyncError); Thread.Sleep(2000); Assert.That(response.Result, Is.EqualTo("Confidential")); } [Test] public void Can_login_without_authorization_to_access_Insecure_service() { var format = GetFormat(); if (format == null) return; var req = (HttpWebRequest)WebRequest.Create( string.Format("{0}{1}/syncreply/Insecure", ServiceClientBaseUri, format)); req.Headers[HttpHeaders.Authorization] = "basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(AllowedUser + ":" + AllowedPass)); var dtoString = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd(); Assert.That(dtoString.Contains("Public")); Console.WriteLine(dtoString); } [Test] public void Can_login_without_authorization_to_access_Insecure_service_using_ServiceClient() { var format = GetFormat(); if (format == null) return; var client = CreateNewServiceClient(); var response = client.Send<InsecureResponse>(new Insecure()); Assert.That(response.Result, Is.EqualTo("Public")); } [Test] public void Can_login_without_authorization_to_access_Insecure_service_using_RestClientAsync() { var format = GetFormat(); if (format == null) return; var client = CreateNewRestClientAsync(); InsecureResponse response = null; client.GetAsync<InsecureResponse>(ServiceClientBaseUri + "insecure", r => response = r, FailOnAsyncError); Thread.Sleep(2000); Assert.That(response.Result, Is.EqualTo("Public")); } [Test] public void Can_login_with_session_cookie_to_access_Secure_service() { var format = GetFormat(); if (format == null) return; var req = (HttpWebRequest)WebRequest.Create( string.Format("http://localhost:82/{0}/syncreply/Secure", format)); req.Headers[HttpHeaders.Authorization] = "basic " + Convert.ToBase64String(Encoding.UTF8.GetBytes(AllowedUser + ":" + AllowedPass)); var res = (HttpWebResponse)req.GetResponse(); var cookie = res.Cookies["ss-session"]; if (cookie != null) { req = (HttpWebRequest)WebRequest.Create( string.Format("http://localhost:82/{0}/syncreply/Secure", format)); req.CookieContainer.Add(new Cookie("ss-session", cookie.Value)); var dtoString = new StreamReader(req.GetResponse().GetResponseStream()).ReadToEnd(); Assert.That(dtoString.Contains("Confidential")); Console.WriteLine(dtoString); } } [Test] public void Get_401_When_accessing_Secure_using_fake_sessionid_cookie() { var format = GetFormat(); if (format == null) return; var req = (HttpWebRequest)WebRequest.Create( string.Format("http://localhost:82/{0}/syncreply/Secure", format)); req.CookieContainer = new CookieContainer(); req.CookieContainer.Add(new Cookie("ss-session", AllowedUser + "/" + Guid.NewGuid().ToString("N"), "/", "localhost")); try { var res = req.GetResponse(); } catch (WebException x) { Assert.That(((HttpWebResponse)x.Response).StatusCode, Is.EqualTo(HttpStatusCode.Unauthorized)); } } [Test] public void Get_401_When_accessing_Secure_using_ServiceClient_without_Authorization() { var client = CreateNewServiceClient(); try { var response = client.Send<SecureResponse>(new Secure()); Console.WriteLine(response.Dump()); } catch (WebServiceException ex) { Assert401(client, ex); return; } Assert.Fail("Should throw WebServiceException.StatusCode == 401"); } [Test] public void Get_401_When_accessing_Secure_using_RestClient_GET_without_Authorization() { var client = CreateNewRestClientAsync(); if (client == null) return; SecureResponse response = null; var wasError = false; client.GetAsync<SecureResponse>(ServiceClientBaseUri + "secure", r => response = r, (r, ex) => wasError = Assert401(r, ex)); Thread.Sleep(1000); Assert.That(wasError, Is.True, "Should throw WebServiceException.StatusCode == 401"); Assert.IsNull(response); } [Test] public void Get_401_When_accessing_Secure_using_RestClient_DELETE_without_Authorization() { var client = CreateNewRestClientAsync(); if (client == null) return; SecureResponse response = null; var wasError = false; client.DeleteAsync<SecureResponse>(ServiceClientBaseUri + "secure", r => response = r, (r, ex) => wasError = Assert401(r, ex)); Thread.Sleep(1000); Assert.That(wasError, Is.True, "Should throw WebServiceException.StatusCode == 401"); Assert.IsNull(response); } [Test] public void Get_401_When_accessing_Secure_using_RestClient_POST_without_Authorization() { var client = CreateNewRestClientAsync(); if (client == null) return; SecureResponse response = null; var wasError = false; client.PostAsync<SecureResponse>(ServiceClientBaseUri + "secure", new Secure(), r => response = r, (r, ex) => wasError = Assert401(r, ex)); Thread.Sleep(1000); Assert.That(wasError, Is.True, "Should throw WebServiceException.StatusCode == 401"); Assert.IsNull(response); } [Test] public void Get_401_When_accessing_Secure_using_RestClient_PUT_without_Authorization() { var client = CreateNewRestClientAsync(); if (client == null) return; SecureResponse response = null; var wasError = false; client.PutAsync<SecureResponse>(ServiceClientBaseUri + "secure", new Secure(), r => response = r, (r, ex) => wasError = Assert401(r, ex)); Thread.Sleep(1000); Assert.That(wasError, Is.True, "Should throw WebServiceException.StatusCode == 401"); Assert.IsNull(response); } public class UnitTests : RequestFiltersTests { protected override IServiceClient CreateNewServiceClient() { EndpointHandlerBase.ServiceManager = new ServiceManager(typeof(SecureService).Assembly).Init(); return new DirectServiceClient(EndpointHandlerBase.ServiceManager); } protected override IRestClientAsync CreateNewRestClientAsync() { return null; //TODO implement REST calls with DirectServiceClient (i.e. Unit Tests) //EndpointHandlerBase.ServiceManager = new ServiceManager(true, typeof(SecureService).Assembly); //return new DirectServiceClient(EndpointHandlerBase.ServiceManager); } } public class XmlIntegrationTests : RequestFiltersTests { protected override string GetFormat() { return "xml"; } protected override IServiceClient CreateNewServiceClient() { return new XmlServiceClient(ServiceClientBaseUri); } protected override IRestClientAsync CreateNewRestClientAsync() { return new XmlRestClientAsync(ServiceClientBaseUri); } } [TestFixture] public class JsonIntegrationTests : RequestFiltersTests { protected override string GetFormat() { return "json"; } protected override IServiceClient CreateNewServiceClient() { return new JsonServiceClient(ServiceClientBaseUri); } protected override IRestClientAsync CreateNewRestClientAsync() { return new JsonRestClientAsync(ServiceClientBaseUri); } } [TestFixture] public class JsvIntegrationTests : RequestFiltersTests { protected override string GetFormat() { return "jsv"; } protected override IServiceClient CreateNewServiceClient() { return new JsvServiceClient(ServiceClientBaseUri); } protected override IRestClientAsync CreateNewRestClientAsync() { return new JsvRestClientAsync(ServiceClientBaseUri); } } #if !MONOTOUCH [TestFixture] public class Soap11IntegrationTests : RequestFiltersTests { protected override IServiceClient CreateNewServiceClient() { return new Soap11ServiceClient(ServiceClientBaseUri); } protected override IRestClientAsync CreateNewRestClientAsync() { return null; } } [TestFixture] public class Soap12IntegrationTests : RequestFiltersTests { protected override IServiceClient CreateNewServiceClient() { return new Soap12ServiceClient(ServiceClientBaseUri); } protected override IRestClientAsync CreateNewRestClientAsync() { return null; } } #endif } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Text; using Microsoft.CodeAnalysis.Emit; using Microsoft.CodeAnalysis.Text; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { public class CSharpCommandLineParser : CommandLineParser { public static readonly CSharpCommandLineParser Default = new CSharpCommandLineParser(); public static readonly CSharpCommandLineParser Interactive = new CSharpCommandLineParser(isInteractive: true); internal CSharpCommandLineParser(bool isInteractive = false) : base(CSharp.MessageProvider.Instance, isInteractive) { } protected override string RegularFileExtension { get { return ".cs"; } } protected override string ScriptFileExtension { get { return ".csx"; } } internal sealed override CommandLineArguments CommonParse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories) { return Parse(args, baseDirectory, sdkDirectory, additionalReferenceDirectories); } /// <summary> /// Parses a command line. /// </summary> /// <param name="args">A collection of strings representing the command line arguments.</param> /// <param name="baseDirectory">The base directory used for qualifying file locations.</param> /// <param name="sdkDirectory">The directory to search for mscorlib.</param> /// <param name="additionalReferenceDirectories">A string representing additional reference paths.</param> /// <returns>a commandlinearguments object representing the parsed command line.</returns> public new CSharpCommandLineArguments Parse(IEnumerable<string> args, string baseDirectory, string sdkDirectory, string additionalReferenceDirectories = null) { List<Diagnostic> diagnostics = new List<Diagnostic>(); List<string> flattenedArgs = new List<string>(); List<string> scriptArgs = IsInteractive ? new List<string>() : null; FlattenArgs(args, diagnostics, flattenedArgs, scriptArgs, baseDirectory); string appConfigPath = null; bool displayLogo = true; bool displayHelp = false; bool optimize = false; bool checkOverflow = false; bool allowUnsafe = false; bool concurrentBuild = true; bool emitPdb = false; string pdbPath = null; bool noStdLib = false; string outputDirectory = baseDirectory; string outputFileName = null; string documentationPath = null; string errorLogPath = null; bool parseDocumentationComments = false; //Don't just null check documentationFileName because we want to do this even if the file name is invalid. bool utf8output = false; OutputKind outputKind = OutputKind.ConsoleApplication; SubsystemVersion subsystemVersion = SubsystemVersion.None; LanguageVersion languageVersion = CSharpParseOptions.Default.LanguageVersion; string mainTypeName = null; string win32ManifestFile = null; string win32ResourceFile = null; string win32IconFile = null; bool noWin32Manifest = false; Platform platform = Platform.AnyCpu; ulong baseAddress = 0; int fileAlignment = 0; bool? delaySignSetting = null; string keyFileSetting = null; string keyContainerSetting = null; List<ResourceDescription> managedResources = new List<ResourceDescription>(); List<CommandLineSourceFile> sourceFiles = new List<CommandLineSourceFile>(); List<CommandLineSourceFile> additionalFiles = new List<CommandLineSourceFile>(); bool sourceFilesSpecified = false; bool resourcesOrModulesSpecified = false; Encoding codepage = null; var checksumAlgorithm = SourceHashAlgorithm.Sha1; var defines = ArrayBuilder<string>.GetInstance(); List<CommandLineReference> metadataReferences = new List<CommandLineReference>(); List<CommandLineAnalyzerReference> analyzers = new List<CommandLineAnalyzerReference>(); List<string> libPaths = new List<string>(); List<string> keyFileSearchPaths = new List<string>(); List<string> usings = new List<string>(); var generalDiagnosticOption = ReportDiagnostic.Default; var diagnosticOptions = new Dictionary<string, ReportDiagnostic>(); var noWarns = new Dictionary<string, ReportDiagnostic>(); var warnAsErrors = new Dictionary<string, ReportDiagnostic>(); int warningLevel = 4; bool highEntropyVA = false; bool printFullPaths = false; string moduleAssemblyName = null; string moduleName = null; List<string> features = new List<string>(); string runtimeMetadataVersion = null; bool errorEndLocation = false; CultureInfo preferredUILang = null; string touchedFilesPath = null; var sqmSessionGuid = Guid.Empty; // Process ruleset files first so that diagnostic severity settings specified on the command line via // /nowarn and /warnaserror can override diagnostic severity settings specified in the ruleset file. if (!IsInteractive) { foreach (string arg in flattenedArgs) { string name, value; if (TryParseOption(arg, out name, out value) && (name == "ruleset")) { var unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); } else { generalDiagnosticOption = GetDiagnosticOptionsFromRulesetFile(diagnosticOptions, diagnostics, unquoted, baseDirectory); } } } } foreach (string arg in flattenedArgs) { Debug.Assert(!arg.StartsWith("@", StringComparison.Ordinal)); string name, value; if (!TryParseOption(arg, out name, out value)) { sourceFiles.AddRange(ParseFileArgument(arg, baseDirectory, diagnostics)); sourceFilesSpecified = true; continue; } switch (name) { case "?": case "help": displayHelp = true; continue; case "r": case "reference": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: false)); continue; case "a": case "analyzer": analyzers.AddRange(ParseAnalyzers(arg, value, diagnostics)); continue; case "d": case "define": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } IEnumerable<Diagnostic> defineDiagnostics; defines.AddRange(ParseConditionalCompilationSymbols(value, out defineDiagnostics)); diagnostics.AddRange(defineDiagnostics); continue; case "codepage": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var encoding = TryParseEncodingName(value); if (encoding == null) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadCodepage, value); continue; } codepage = encoding; continue; case "checksumalgorithm": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } var newChecksumAlgorithm = TryParseHashAlgorithmName(value); if (newChecksumAlgorithm == SourceHashAlgorithm.None) { AddDiagnostic(diagnostics, ErrorCode.FTL_BadChecksumAlgorithm, value); continue; } checksumAlgorithm = newChecksumAlgorithm; continue; case "checked": case "checked+": if (value != null) { break; } checkOverflow = true; continue; case "checked-": if (value != null) break; checkOverflow = false; continue; case "features": if (value == null) { features.Clear(); } else { features.Add(value); } continue; case "noconfig": // It is already handled (see CommonCommandLineCompiler.cs). continue; case "sqmsessionguid": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_MissingGuidForOption, "<text>", name); } else { if (!Guid.TryParse(value, out sqmSessionGuid)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFormatForGuidForOption, value, name); } } continue; case "preferreduilang": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); continue; } try { preferredUILang = new CultureInfo(value); } catch (CultureNotFoundException) { AddDiagnostic(diagnostics, ErrorCode.WRN_BadUILang, value); } continue; #if DEBUG case "attachdebugger": Debugger.Launch(); continue; #endif } if (IsInteractive) { switch (name) { // interactive: case "rp": case "referencepath": // TODO: should it really go to libPaths? ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_REFERENCEPATH_OPTION, diagnostics); continue; case "u": case "using": usings.AddRange(ParseUsings(arg, value, diagnostics)); continue; } } else { switch (name) { case "out": if (string.IsNullOrWhiteSpace(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { ParseOutputFile(value, diagnostics, baseDirectory, out outputFileName, out outputDirectory); } continue; case "t": case "target": if (value == null) { break; // force 'unrecognized option' } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); } else { outputKind = ParseTarget(value, diagnostics); } continue; case "moduleassemblyname": value = value != null ? value.Unquote() : null; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", arg); } else if (!MetadataHelpers.IsValidAssemblyOrModuleName(value)) { // Dev11 C# doesn't check the name (VB does) AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidAssemblyName, "<text>", arg); } else { moduleAssemblyName = value; } continue; case "modulename": var unquotedModuleName = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquotedModuleName)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "modulename"); continue; } else { moduleName = unquotedModuleName; } continue; case "platform": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<string>", arg); } else { platform = ParsePlatform(value, diagnostics); } continue; case "recurse": if (value == null) { break; // force 'unrecognized option' } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { int before = sourceFiles.Count; sourceFiles.AddRange(ParseRecurseArgument(value, baseDirectory, diagnostics)); if (sourceFiles.Count > before) { sourceFilesSpecified = true; } } continue; case "doc": parseDocumentationComments = true; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); continue; } string unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { // CONSIDER: This diagnostic exactly matches dev11, but it would be simpler (and more consistent with /out) // if we just let the next case handle /doc:"". AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/doc:"); // Different argument. } else { documentationPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "addmodule": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/addmodule:"); } else if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. // An error will be reported by the assembly manager anyways. metadataReferences.AddRange(ParseSeparatedPaths(value).Select(path => new CommandLineReference(path, MetadataReferenceProperties.Module))); resourcesOrModulesSpecified = true; } continue; case "l": case "link": metadataReferences.AddRange(ParseAssemblyReferences(arg, value, diagnostics, embedInteropTypes: true)); continue; case "win32res": win32ResourceFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32icon": win32IconFile = GetWin32Setting(arg, value, diagnostics); continue; case "win32manifest": win32ManifestFile = GetWin32Setting(arg, value, diagnostics); noWin32Manifest = false; continue; case "nowin32manifest": noWin32Manifest = true; win32ManifestFile = null; continue; case "res": case "resource": if (value == null) { break; // Dev11 reports inrecognized option } var embeddedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: true); if (embeddedResource != null) { managedResources.Add(embeddedResource); resourcesOrModulesSpecified = true; } continue; case "linkres": case "linkresource": if (value == null) { break; // Dev11 reports inrecognized option } var linkedResource = ParseResourceDescription(arg, value, baseDirectory, diagnostics, embedded: false); if (linkedResource != null) { managedResources.Add(linkedResource); resourcesOrModulesSpecified = true; } continue; case "debug": emitPdb = true; // unused, parsed for backward compat only if (value != null) { if (value.IsEmpty()) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), name); } else if (!string.Equals(value, "full", StringComparison.OrdinalIgnoreCase) && !string.Equals(value, "pdbonly", StringComparison.OrdinalIgnoreCase)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadDebugType, value); } } continue; case "debug+": //guard against "debug+:xx" if (value != null) break; emitPdb = true; continue; case "debug-": if (value != null) break; emitPdb = false; continue; case "o": case "optimize": case "o+": case "optimize+": if (value != null) break; optimize = true; continue; case "o-": case "optimize-": if (value != null) break; optimize = false; continue; case "p": case "parallel": case "p+": case "parallel+": if (value != null) break; concurrentBuild = true; continue; case "p-": case "parallel-": if (value != null) break; concurrentBuild = false; continue; case "warnaserror": case "warnaserror+": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Error; // Reset specific warnaserror options (since last /warnaserror flag on the command line always wins), // and bump warnings to errors. warnAsErrors.Clear(); foreach (var key in diagnosticOptions.Keys) { if (diagnosticOptions[key] == ReportDiagnostic.Warn) { warnAsErrors[key] = ReportDiagnostic.Error; } } continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(warnAsErrors, ReportDiagnostic.Error, ParseWarnings(value)); } continue; case "warnaserror-": if (value == null) { generalDiagnosticOption = ReportDiagnostic.Default; // Clear specific warnaserror options (since last /warnaserror flag on the command line always wins). warnAsErrors.Clear(); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { foreach (var id in ParseWarnings(value)) { ReportDiagnostic ruleSetValue; if (diagnosticOptions.TryGetValue(id, out ruleSetValue)) { warnAsErrors[id] = ruleSetValue; } else { warnAsErrors[id] = ReportDiagnostic.Default; } } } continue; case "w": case "warn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } int newWarningLevel; if (string.IsNullOrEmpty(value) || !int.TryParse(value, NumberStyles.Integer, CultureInfo.InvariantCulture, out newWarningLevel)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (newWarningLevel < 0 || newWarningLevel > 4) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadWarningLevel, name); } else { warningLevel = newWarningLevel; } continue; case "nowarn": if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); continue; } if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddWarnings(noWarns, ReportDiagnostic.Suppress, ParseWarnings(value)); } continue; case "unsafe": case "unsafe+": if (value != null) break; allowUnsafe = true; continue; case "unsafe-": if (value != null) break; allowUnsafe = false; continue; case "langversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "/langversion:"); } else if (!TryParseLanguageVersion(value, CSharpParseOptions.Default.LanguageVersion, out languageVersion)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadCompatMode, value); } continue; case "delaysign": case "delaysign+": if (value != null) { break; } delaySignSetting = true; continue; case "delaysign-": if (value != null) { break; } delaySignSetting = false; continue; case "keyfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, "keyfile"); } else { keyFileSetting = RemoveAllQuotes(value); } // NOTE: Dev11/VB also clears "keycontainer", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "keycontainer": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "keycontainer"); } else { keyContainerSetting = value; } // NOTE: Dev11/VB also clears "keyfile", see also: // // MSDN: In case both /keyfile and /keycontainer are specified (either by command line option or by // MSDN: custom attribute) in the same compilation, the compiler will first try the key container. // MSDN: If that succeeds, then the assembly is signed with the information in the key container. // MSDN: If the compiler does not find the key container, it will try the file specified with /keyfile. // MSDN: If that succeeds, the assembly is signed with the information in the key file and the key // MSDN: information will be installed in the key container (similar to sn -i) so that on the next // MSDN: compilation, the key container will be valid. continue; case "highentropyva": case "highentropyva+": if (value != null) break; highEntropyVA = true; continue; case "highentropyva-": if (value != null) break; highEntropyVA = false; continue; case "nologo": displayLogo = false; continue; case "baseaddress": ulong newBaseAddress; if (string.IsNullOrEmpty(value) || !TryParseUInt64(value, out newBaseAddress)) { if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, value); } } else { baseAddress = newBaseAddress; } continue; case "subsystemversion": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "subsystemversion"); continue; } // It seems VS 2012 just silently corrects invalid values and suppresses the error message SubsystemVersion version = SubsystemVersion.None; if (SubsystemVersion.TryParse(value, out version)) { subsystemVersion = version; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidSubsystemVersion, value); } continue; case "touchedfiles": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), "touchedfiles"); continue; } else { touchedFilesPath = unquoted; } continue; case "bugreport": UnimplementedSwitch(diagnostics, name); continue; case "utf8output": if (value != null) break; utf8output = true; continue; case "m": case "main": // Remove any quotes for consistent behaviour as MSBuild can return quoted or // unquoted main. unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } mainTypeName = unquoted; continue; case "fullpaths": if (value != null) break; printFullPaths = true; continue; case "filealign": ushort newAlignment; if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsNumber, name); } else if (!TryParseUInt16(value, out newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else if (!CompilationOptions.IsValidFileAlignment(newAlignment)) { AddDiagnostic(diagnostics, ErrorCode.ERR_InvalidFileAlignment, value); } else { fileAlignment = newAlignment; } continue; case "pdb": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { pdbPath = ParsePdbPath(value, diagnostics, baseDirectory); } continue; case "errorendlocation": errorEndLocation = true; continue; case "nostdlib": case "nostdlib+": if (value != null) break; noStdLib = true; continue; case "lib": ParseAndResolveReferencePaths(name, value, baseDirectory, libPaths, MessageID.IDS_LIB_OPTION, diagnostics); continue; case "nostdlib-": if (value != null) break; noStdLib = false; continue; case "errorreport": continue; case "errorlog": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<file>", RemoveAllQuotes(arg)); } else { errorLogPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "appconfig": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, ":<text>", RemoveAllQuotes(arg)); } else { appConfigPath = ParseGenericPathToFile(unquoted, diagnostics, baseDirectory); } continue; case "runtimemetadataversion": unquoted = RemoveAllQuotes(value); if (string.IsNullOrEmpty(unquoted)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<text>", name); continue; } runtimeMetadataVersion = unquoted; continue; case "ruleset": // The ruleset arg has already been processed in a separate pass above. continue; case "additionalfile": if (string.IsNullOrEmpty(value)) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, "<file list>", name); continue; } additionalFiles.AddRange(ParseAdditionalFileArgument(value, baseDirectory, diagnostics)); continue; } } AddDiagnostic(diagnostics, ErrorCode.ERR_BadSwitch, arg); } foreach (var o in warnAsErrors) { diagnosticOptions[o.Key] = o.Value; } // Specific nowarn options always override specific warnaserror options. foreach (var o in noWarns) { diagnosticOptions[o.Key] = o.Value; } if (!IsInteractive && !sourceFilesSpecified && (outputKind.IsNetModule() || !resourcesOrModulesSpecified)) { AddDiagnostic(diagnostics, diagnosticOptions, ErrorCode.WRN_NoSources); } if (!noStdLib) { metadataReferences.Insert(0, new CommandLineReference(Path.Combine(sdkDirectory, "mscorlib.dll"), MetadataReferenceProperties.Assembly)); } if (!platform.Requires64Bit()) { if (baseAddress > uint.MaxValue - 0x8000) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadBaseNumber, string.Format("0x{0:X}", baseAddress)); baseAddress = 0; } } // add additional reference paths if specified if (!string.IsNullOrWhiteSpace(additionalReferenceDirectories)) { ParseAndResolveReferencePaths(null, additionalReferenceDirectories, baseDirectory, libPaths, MessageID.IDS_LIB_ENV, diagnostics); } ImmutableArray<string> referencePaths = BuildSearchPaths(sdkDirectory, libPaths); ValidateWin32Settings(win32ResourceFile, win32IconFile, win32ManifestFile, outputKind, diagnostics); // Dev11 searches for the key file in the current directory and assembly output directory. // We always look to base directory and then examine the search paths. keyFileSearchPaths.Add(baseDirectory); if (baseDirectory != outputDirectory) { keyFileSearchPaths.Add(outputDirectory); } if (!emitPdb) { if (pdbPath != null) { // Can't give a PDB file name and turn off debug information AddDiagnostic(diagnostics, ErrorCode.ERR_MissingDebugSwitch); } } string compilationName; GetCompilationAndModuleNames(diagnostics, outputKind, sourceFiles, sourceFilesSpecified, moduleAssemblyName, ref outputFileName, ref moduleName, out compilationName); var parseOptions = new CSharpParseOptions ( languageVersion: languageVersion, preprocessorSymbols: defines.ToImmutableAndFree(), documentationMode: parseDocumentationComments ? DocumentationMode.Diagnose : DocumentationMode.None, kind: SourceCodeKind.Regular ); var scriptParseOptions = parseOptions.WithKind(SourceCodeKind.Script); var options = new CSharpCompilationOptions ( outputKind: outputKind, moduleName: moduleName, mainTypeName: mainTypeName, scriptClassName: WellKnownMemberNames.DefaultScriptClassName, usings: usings, optimizationLevel: optimize ? OptimizationLevel.Release : OptimizationLevel.Debug, checkOverflow: checkOverflow, allowUnsafe: allowUnsafe, concurrentBuild: concurrentBuild, cryptoKeyContainer: keyContainerSetting, cryptoKeyFile: keyFileSetting, delaySign: delaySignSetting, platform: platform, generalDiagnosticOption: generalDiagnosticOption, warningLevel: warningLevel, specificDiagnosticOptions: diagnosticOptions ).WithFeatures(features.AsImmutable()); var emitOptions = new EmitOptions ( metadataOnly: false, debugInformationFormat: DebugInformationFormat.Pdb, pdbFilePath: null, // to be determined later outputNameOverride: null, // to be determined later baseAddress: baseAddress, highEntropyVirtualAddressSpace: highEntropyVA, fileAlignment: fileAlignment, subsystemVersion: subsystemVersion, runtimeMetadataVersion: runtimeMetadataVersion ); // add option incompatibility errors if any diagnostics.AddRange(options.Errors); return new CSharpCommandLineArguments { IsInteractive = IsInteractive, BaseDirectory = baseDirectory, Errors = diagnostics.AsImmutable(), Utf8Output = utf8output, CompilationName = compilationName, OutputFileName = outputFileName, PdbPath = pdbPath, EmitPdb = emitPdb, OutputDirectory = outputDirectory, DocumentationPath = documentationPath, ErrorLogPath = errorLogPath, AppConfigPath = appConfigPath, SourceFiles = sourceFiles.AsImmutable(), Encoding = codepage, ChecksumAlgorithm = checksumAlgorithm, MetadataReferences = metadataReferences.AsImmutable(), AnalyzerReferences = analyzers.AsImmutable(), AdditionalFiles = additionalFiles.AsImmutable(), ReferencePaths = referencePaths, KeyFileSearchPaths = keyFileSearchPaths.AsImmutable(), Win32ResourceFile = win32ResourceFile, Win32Icon = win32IconFile, Win32Manifest = win32ManifestFile, NoWin32Manifest = noWin32Manifest, DisplayLogo = displayLogo, DisplayHelp = displayHelp, ManifestResources = managedResources.AsImmutable(), CompilationOptions = options, ParseOptions = IsInteractive ? scriptParseOptions : parseOptions, EmitOptions = emitOptions, ScriptArguments = scriptArgs.AsImmutableOrEmpty(), TouchedFilesPath = touchedFilesPath, PrintFullPaths = printFullPaths, ShouldIncludeErrorEndLocation = errorEndLocation, PreferredUILang = preferredUILang, SqmSessionGuid = sqmSessionGuid }; } private static void ParseAndResolveReferencePaths(string switchName, string switchValue, string baseDirectory, List<string> builder, MessageID origin, List<Diagnostic> diagnostics) { if (string.IsNullOrEmpty(switchValue)) { Debug.Assert(!string.IsNullOrEmpty(switchName)); AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_PathList.Localize(), switchName); return; } foreach (string path in ParseSeparatedPaths(switchValue)) { string resolvedPath = FileUtilities.ResolveRelativePath(path, baseDirectory); if (resolvedPath == null) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryHasInvalidPath.Localize()); } else if (!Directory.Exists(resolvedPath)) { AddDiagnostic(diagnostics, ErrorCode.WRN_InvalidSearchPathDir, path, origin.Localize(), MessageID.IDS_DirectoryDoesNotExist.Localize()); } else { builder.Add(resolvedPath); } } } private static string GetWin32Setting(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { string noQuotes = RemoveAllQuotes(value); if (string.IsNullOrWhiteSpace(noQuotes)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); } else { return noQuotes; } } return null; } private void GetCompilationAndModuleNames( List<Diagnostic> diagnostics, OutputKind outputKind, List<CommandLineSourceFile> sourceFiles, bool sourceFilesSpecified, string moduleAssemblyName, ref string outputFileName, ref string moduleName, out string compilationName) { string simpleName; if (outputFileName == null) { // In C#, if the output file name isn't specified explicitly, then executables take their // names from the files containing their entrypoints and libraries derive their names from // their first input files. if (!IsInteractive && !sourceFilesSpecified) { AddDiagnostic(diagnostics, ErrorCode.ERR_OutputNeedsName); simpleName = null; } else if (outputKind.IsApplication()) { simpleName = null; } else { simpleName = PathUtilities.RemoveExtension(PathUtilities.GetFileName(sourceFiles.FirstOrDefault().Path)); outputFileName = simpleName + outputKind.GetDefaultExtension(); if (simpleName.Length == 0 && !outputKind.IsNetModule()) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } } else { simpleName = PathUtilities.RemoveExtension(outputFileName); if (simpleName.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, outputFileName); outputFileName = simpleName = null; } } if (outputKind.IsNetModule()) { Debug.Assert(!IsInteractive); compilationName = moduleAssemblyName; } else { if (moduleAssemblyName != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_AssemblyNameOnNonModule); } compilationName = simpleName; } if (moduleName == null) { moduleName = outputFileName; } } private static ImmutableArray<string> BuildSearchPaths(string sdkDirectory, List<string> libPaths) { var builder = ArrayBuilder<string>.GetInstance(); // Match how Dev11 builds the list of search paths // see PCWSTR LangCompiler::GetSearchPath() // current folder first -- base directory is searched by default // SDK path is specified or current runtime directory builder.Add(sdkDirectory); // libpath builder.AddRange(libPaths); return builder.ToImmutableAndFree(); } public static IEnumerable<string> ParseConditionalCompilationSymbols(string value, out IEnumerable<Diagnostic> diagnostics) { Diagnostic myDiagnostic = null; value = value.TrimEnd(null); // Allow a trailing semicolon or comma in the options if (!value.IsEmpty() && (value.Last() == ';' || value.Last() == ',')) { value = value.Substring(0, value.Length - 1); } string[] values = value.Split(new char[] { ';', ',' } /*, StringSplitOptions.RemoveEmptyEntries*/); var defines = new ArrayBuilder<string>(values.Length); foreach (string id in values) { string trimmedId = id.Trim(); if (SyntaxFacts.IsValidIdentifier(trimmedId)) { defines.Add(trimmedId); } else if (myDiagnostic == null) { myDiagnostic = Diagnostic.Create(CSharp.MessageProvider.Instance, (int)ErrorCode.WRN_DefineIdentifierRequired, trimmedId); } } diagnostics = myDiagnostic == null ? SpecializedCollections.EmptyEnumerable<Diagnostic>() : SpecializedCollections.SingletonEnumerable(myDiagnostic); return defines.AsEnumerable(); } private static Platform ParsePlatform(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "x86": return Platform.X86; case "x64": return Platform.X64; case "itanium": return Platform.Itanium; case "anycpu": return Platform.AnyCpu; case "anycpu32bitpreferred": return Platform.AnyCpu32BitPreferred; case "arm": return Platform.Arm; default: AddDiagnostic(diagnostics, ErrorCode.ERR_BadPlatformType, value); return Platform.AnyCpu; } } private static OutputKind ParseTarget(string value, IList<Diagnostic> diagnostics) { switch (value.ToLowerInvariant()) { case "exe": return OutputKind.ConsoleApplication; case "winexe": return OutputKind.WindowsApplication; case "library": return OutputKind.DynamicallyLinkedLibrary; case "module": return OutputKind.NetModule; case "appcontainerexe": return OutputKind.WindowsRuntimeApplication; case "winmdobj": return OutputKind.WindowsRuntimeMetadata; default: AddDiagnostic(diagnostics, ErrorCode.FTL_InvalidTarget); return OutputKind.ConsoleApplication; } } private static IEnumerable<string> ParseUsings(string arg, string value, IList<Diagnostic> diagnostics) { if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Namespace1.Localize(), arg); yield break; } foreach (var u in value.Split(new[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { yield return u; } } private IEnumerable<CommandLineAnalyzerReference> ParseAnalyzers(string arg, string value, List<Diagnostic> diagnostics) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); foreach (string path in paths) { yield return new CommandLineAnalyzerReference(path); } } private IEnumerable<CommandLineReference> ParseAssemblyReferences(string arg, string value, IList<Diagnostic> diagnostics, bool embedInteropTypes) { if (value == null) { AddDiagnostic(diagnostics, ErrorCode.ERR_SwitchNeedsString, MessageID.IDS_Text.Localize(), arg); yield break; } else if (value.Length == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); yield break; } // /r:"reference" // /r:alias=reference // /r:alias="reference" // /r:reference;reference // /r:"path;containing;semicolons" // /r:"unterminated_quotes // /r:"quotes"in"the"middle // /r:alias=reference;reference ... error 2034 // /r:nonidf=reference ... error 1679 int eqlOrQuote = value.IndexOfAny(new[] { '"', '=' }); string alias; if (eqlOrQuote >= 0 && value[eqlOrQuote] == '=') { alias = value.Substring(0, eqlOrQuote); value = value.Substring(eqlOrQuote + 1); if (!SyntaxFacts.IsValidIdentifier(alias)) { AddDiagnostic(diagnostics, ErrorCode.ERR_BadExternIdentifier, alias); yield break; } } else { alias = null; } List<string> paths = ParseSeparatedPaths(value).Where((path) => !string.IsNullOrWhiteSpace(path)).ToList(); if (alias != null) { if (paths.Count > 1) { AddDiagnostic(diagnostics, ErrorCode.ERR_OneAliasPerReference, value); yield break; } if (paths.Count == 0) { AddDiagnostic(diagnostics, ErrorCode.ERR_AliasMissingFile, alias); yield break; } } foreach (string path in paths) { // NOTE(tomat): Dev10 used to report CS1541: ERR_CantIncludeDirectory if the path was a directory. // Since we now support /referencePaths option we would need to search them to see if the resolved path is a directory. var aliases = (alias != null) ? ImmutableArray.Create(alias) : ImmutableArray<string>.Empty; var properties = new MetadataReferenceProperties(MetadataImageKind.Assembly, aliases, embedInteropTypes); yield return new CommandLineReference(path, properties); } } private static void ValidateWin32Settings(string win32ResourceFile, string win32IconResourceFile, string win32ManifestFile, OutputKind outputKind, IList<Diagnostic> diagnostics) { if (win32ResourceFile != null) { if (win32IconResourceFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndIcon); } if (win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.ERR_CantHaveWin32ResAndManifest); } } if (outputKind.IsNetModule() && win32ManifestFile != null) { AddDiagnostic(diagnostics, ErrorCode.WRN_CantHaveManifestForModule); } } internal static ResourceDescription ParseResourceDescription( string arg, string resourceDescriptor, string baseDirectory, IList<Diagnostic> diagnostics, bool embedded) { string filePath; string fullPath; string fileName; string resourceName; string accessibility; ParseResourceDescription( resourceDescriptor, baseDirectory, false, out filePath, out fullPath, out fileName, out resourceName, out accessibility); bool isPublic; if (accessibility == null) { // If no accessibility is given, we default to "public". // NOTE: Dev10 distinguishes between null and empty/whitespace-only. isPublic = true; } else if (string.Equals(accessibility, "public", StringComparison.OrdinalIgnoreCase)) { isPublic = true; } else if (string.Equals(accessibility, "private", StringComparison.OrdinalIgnoreCase)) { isPublic = false; } else { AddDiagnostic(diagnostics, ErrorCode.ERR_BadResourceVis, accessibility); return null; } if (string.IsNullOrEmpty(filePath)) { AddDiagnostic(diagnostics, ErrorCode.ERR_NoFileSpec, arg); return null; } if (fullPath == null || string.IsNullOrWhiteSpace(fileName) || fileName.IndexOfAny(Path.GetInvalidFileNameChars()) >= 0) { AddDiagnostic(diagnostics, ErrorCode.FTL_InputFileNameTooLong, filePath); return null; } Func<Stream> dataProvider = () => { // Use FileShare.ReadWrite because the file could be opened by the current process. // For example, it is an XML doc file produced by the build. return new FileStream(fullPath, FileMode.Open, FileAccess.Read, FileShare.ReadWrite); }; return new ResourceDescription(resourceName, fileName, dataProvider, isPublic, embedded, checkArgs: false); } private static bool TryParseLanguageVersion(string str, LanguageVersion defaultVersion, out LanguageVersion version) { if (str == null) { version = defaultVersion; return true; } switch (str.ToLowerInvariant()) { case "iso-1": version = LanguageVersion.CSharp1; return true; case "iso-2": version = LanguageVersion.CSharp2; return true; case "default": version = defaultVersion; return true; default: int versionNumber; if (int.TryParse(str, NumberStyles.None, CultureInfo.InvariantCulture, out versionNumber) && ((LanguageVersion)versionNumber).IsValid()) { version = (LanguageVersion)versionNumber; return true; } version = defaultVersion; return false; } } private static IEnumerable<string> ParseWarnings(string value) { value = value.Unquote(); string[] values = value.Split(new char[] { ',', ';', ' ' }, StringSplitOptions.RemoveEmptyEntries); foreach (string id in values) { ushort number; if (ushort.TryParse(id, NumberStyles.Integer, CultureInfo.InvariantCulture, out number) && ErrorFacts.IsWarning((ErrorCode)number)) { // The id refers to a compiler warning. yield return CSharp.MessageProvider.Instance.GetIdForErrorCode(number); } else { // Previous versions of the compiler used to report a warning (CS1691) // whenever an unrecognized warning code was supplied in /nowarn or // /warnaserror. We no longer generate a warning in such cases. // Instead we assume that the unrecognized id refers to a custom diagnostic. yield return id; } } } private static void AddWarnings(Dictionary<string, ReportDiagnostic> d, ReportDiagnostic kind, IEnumerable<string> items) { foreach (var id in items) { ReportDiagnostic existing; if (d.TryGetValue(id, out existing)) { // Rewrite the existing value with the latest one unless it is for /nowarn. if (existing != ReportDiagnostic.Suppress) d[id] = kind; } else { d.Add(id, kind); } } } private static void UnimplementedSwitch(IList<Diagnostic> diagnostics, string switchName) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName); } private static void UnimplementedSwitchValue(IList<Diagnostic> diagnostics, string switchName, string value) { AddDiagnostic(diagnostics, ErrorCode.WRN_UnimplementedCommandLineSwitch, "/" + switchName + ":" + value); } internal override void GenerateErrorForNoFilesFoundInRecurse(string path, IList<Diagnostic> diagnostics) { // no error in csc.exe } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode)); } private static void AddDiagnostic(IList<Diagnostic> diagnostics, ErrorCode errorCode, params object[] arguments) { diagnostics.Add(Diagnostic.Create(CSharp.MessageProvider.Instance, (int)errorCode, arguments)); } /// <summary> /// Diagnostic for the errorCode added if the warningOptions does not mention suppressed for the errorCode. /// </summary> private static void AddDiagnostic(IList<Diagnostic> diagnostics, Dictionary<string, ReportDiagnostic> warningOptions, ErrorCode errorCode, params object[] arguments) { int code = (int)errorCode; ReportDiagnostic value; warningOptions.TryGetValue(CSharp.MessageProvider.Instance.GetIdForErrorCode(code), out value); if (value != ReportDiagnostic.Suppress) { AddDiagnostic(diagnostics, errorCode, arguments); } } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using Nini.Config; using log4net; using System; using System.Reflection; using System.IO; using System.Net; using System.Text; using System.Text.RegularExpressions; using System.Xml; using System.Xml.Serialization; using System.Collections.Generic; using OpenSim.Server.Base; using OpenSim.Services.Interfaces; using GridRegion = OpenSim.Services.Interfaces.GridRegion; using OpenSim.Framework; using OpenSim.Framework.Servers.HttpServer; using OpenMetaverse; namespace OpenSim.Server.Handlers.Grid { public class GridServerPostHandler : BaseStreamHandler { private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType); private IGridService m_GridService; public GridServerPostHandler(IGridService service) : base("POST", "/grid") { m_GridService = service; } protected override byte[] ProcessRequest(string path, Stream requestData, IOSHttpRequest httpRequest, IOSHttpResponse httpResponse) { StreamReader sr = new StreamReader(requestData); string body = sr.ReadToEnd(); sr.Close(); body = body.Trim(); //m_log.DebugFormat("[XXX]: query String: {0}", body); try { Dictionary<string, object> request = ServerUtils.ParseQueryString(body); if (!request.ContainsKey("METHOD")) return FailureResult(); string method = request["METHOD"].ToString(); switch (method) { case "register": return Register(request); case "deregister": return Deregister(request); case "get_neighbours": return GetNeighbours(request); case "get_region_by_uuid": return GetRegionByUUID(request); case "get_region_by_position": return GetRegionByPosition(request); case "get_region_by_name": return GetRegionByName(request); case "get_regions_by_name": return GetRegionsByName(request); case "get_region_range": return GetRegionRange(request); case "get_default_regions": return GetDefaultRegions(request); case "get_default_hypergrid_regions": return GetDefaultHypergridRegions(request); case "get_fallback_regions": return GetFallbackRegions(request); case "get_hyperlinks": return GetHyperlinks(request); case "get_region_flags": return GetRegionFlags(request); } m_log.DebugFormat("[GRID HANDLER]: unknown method request {0}", method); } catch (Exception e) { m_log.ErrorFormat("[GRID HANDLER]: Exception {0} {1}", e.Message, e.StackTrace); } return FailureResult(); } #region Method-specific handlers byte[] Register(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to register region"); int versionNumberMin = 0, versionNumberMax = 0; if (request.ContainsKey("VERSIONMIN")) Int32.TryParse(request["VERSIONMIN"].ToString(), out versionNumberMin); else m_log.WarnFormat("[GRID HANDLER]: no minimum protocol version in request to register region"); if (request.ContainsKey("VERSIONMAX")) Int32.TryParse(request["VERSIONMAX"].ToString(), out versionNumberMax); else m_log.WarnFormat("[GRID HANDLER]: no maximum protocol version in request to register region"); // Check the protocol version if ((versionNumberMin > ProtocolVersions.ServerProtocolVersionMax && versionNumberMax < ProtocolVersions.ServerProtocolVersionMax)) { // Can't do, there is no overlap in the acceptable ranges return FailureResult(); } Dictionary<string, object> rinfoData = new Dictionary<string, object>(); GridRegion rinfo = null; try { foreach (KeyValuePair<string, object> kvp in request) rinfoData[kvp.Key] = kvp.Value.ToString(); rinfo = new GridRegion(rinfoData); } catch (Exception e) { m_log.DebugFormat("[GRID HANDLER]: exception unpacking region data: {0}", e); } string result = "Error communicating with grid service"; if (rinfo != null) result = m_GridService.RegisterRegion(scopeID, rinfo); if (result == String.Empty) return SuccessResult(); else return FailureResult(result); } byte[] Deregister(Dictionary<string, object> request) { UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to deregister region"); bool result = m_GridService.DeregisterRegion(regionID); if (result) return SuccessResult(); else return FailureResult(); } byte[] GetNeighbours(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours"); UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours"); List<GridRegion> rinfos = m_GridService.GetNeighbours(scopeID, regionID); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionByUUID(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours"); UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours"); GridRegion rinfo = m_GridService.GetRegionByUUID(scopeID, regionID); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionByPosition(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by position"); int x = 0, y = 0; if (request.ContainsKey("X")) Int32.TryParse(request["X"].ToString(), out x); else m_log.WarnFormat("[GRID HANDLER]: no X in request to get region by position"); if (request.ContainsKey("Y")) Int32.TryParse(request["Y"].ToString(), out y); else m_log.WarnFormat("[GRID HANDLER]: no Y in request to get region by position"); GridRegion rinfo = m_GridService.GetRegionByPosition(scopeID, x, y); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionByName(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region by name"); string regionName = string.Empty; if (request.ContainsKey("NAME")) regionName = request["NAME"].ToString(); else m_log.WarnFormat("[GRID HANDLER]: no name in request to get region by name"); GridRegion rinfo = m_GridService.GetRegionByName(scopeID, regionName); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if (rinfo == null) result["result"] = "null"; else result["result"] = rinfo.ToKeyValuePairs(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionsByName(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get regions by name"); string regionName = string.Empty; if (request.ContainsKey("NAME")) regionName = request["NAME"].ToString(); else m_log.WarnFormat("[GRID HANDLER]: no NAME in request to get regions by name"); int max = 0; if (request.ContainsKey("MAX")) Int32.TryParse(request["MAX"].ToString(), out max); else m_log.WarnFormat("[GRID HANDLER]: no MAX in request to get regions by name"); List<GridRegion> rinfos = m_GridService.GetRegionsByName(scopeID, regionName, max); //m_log.DebugFormat("[GRID HANDLER]: neighbours for region {0}: {1}", regionID, rinfos.Count); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionRange(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetRegionRange"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); int xmin = 0, xmax = 0, ymin = 0, ymax = 0; if (request.ContainsKey("XMIN")) Int32.TryParse(request["XMIN"].ToString(), out xmin); else m_log.WarnFormat("[GRID HANDLER]: no XMIN in request to get region range"); if (request.ContainsKey("XMAX")) Int32.TryParse(request["XMAX"].ToString(), out xmax); else m_log.WarnFormat("[GRID HANDLER]: no XMAX in request to get region range"); if (request.ContainsKey("YMIN")) Int32.TryParse(request["YMIN"].ToString(), out ymin); else m_log.WarnFormat("[GRID HANDLER]: no YMIN in request to get region range"); if (request.ContainsKey("YMAX")) Int32.TryParse(request["YMAX"].ToString(), out ymax); else m_log.WarnFormat("[GRID HANDLER]: no YMAX in request to get region range"); List<GridRegion> rinfos = m_GridService.GetRegionRange(scopeID, xmin, xmax, ymin, ymax); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetDefaultRegions(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetDefaultRegions"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); List<GridRegion> rinfos = m_GridService.GetDefaultRegions(scopeID); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetDefaultHypergridRegions(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetDefaultRegions"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get region range"); List<GridRegion> rinfos = m_GridService.GetDefaultHypergridRegions(scopeID); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetFallbackRegions(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetRegionRange"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get fallback regions"); int x = 0, y = 0; if (request.ContainsKey("X")) Int32.TryParse(request["X"].ToString(), out x); else m_log.WarnFormat("[GRID HANDLER]: no X in request to get fallback regions"); if (request.ContainsKey("Y")) Int32.TryParse(request["Y"].ToString(), out y); else m_log.WarnFormat("[GRID HANDLER]: no Y in request to get fallback regions"); List<GridRegion> rinfos = m_GridService.GetFallbackRegions(scopeID, x, y); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetHyperlinks(Dictionary<string, object> request) { //m_log.DebugFormat("[GRID HANDLER]: GetHyperlinks"); UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get linked regions"); List<GridRegion> rinfos = m_GridService.GetHyperlinks(scopeID); Dictionary<string, object> result = new Dictionary<string, object>(); if ((rinfos == null) || ((rinfos != null) && (rinfos.Count == 0))) result["result"] = "null"; else { int i = 0; foreach (GridRegion rinfo in rinfos) { Dictionary<string, object> rinfoDict = rinfo.ToKeyValuePairs(); result["region" + i] = rinfoDict; i++; } } string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } byte[] GetRegionFlags(Dictionary<string, object> request) { UUID scopeID = UUID.Zero; if (request.ContainsKey("SCOPEID")) UUID.TryParse(request["SCOPEID"].ToString(), out scopeID); else m_log.WarnFormat("[GRID HANDLER]: no scopeID in request to get neighbours"); UUID regionID = UUID.Zero; if (request.ContainsKey("REGIONID")) UUID.TryParse(request["REGIONID"].ToString(), out regionID); else m_log.WarnFormat("[GRID HANDLER]: no regionID in request to get neighbours"); int flags = m_GridService.GetRegionFlags(scopeID, regionID); // m_log.DebugFormat("[GRID HANDLER]: flags for region {0}: {1}", regionID, flags); Dictionary<string, object> result = new Dictionary<string, object>(); result["result"] = flags.ToString(); string xmlString = ServerUtils.BuildXmlResponse(result); //m_log.DebugFormat("[GRID HANDLER]: resp string: {0}", xmlString); return Util.UTF8NoBomEncoding.GetBytes(xmlString); } #endregion #region Misc private byte[] SuccessResult() { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Success")); rootElement.AppendChild(result); return DocToBytes(doc); } private byte[] FailureResult() { return FailureResult(String.Empty); } private byte[] FailureResult(string msg) { XmlDocument doc = new XmlDocument(); XmlNode xmlnode = doc.CreateNode(XmlNodeType.XmlDeclaration, "", ""); doc.AppendChild(xmlnode); XmlElement rootElement = doc.CreateElement("", "ServerResponse", ""); doc.AppendChild(rootElement); XmlElement result = doc.CreateElement("", "Result", ""); result.AppendChild(doc.CreateTextNode("Failure")); rootElement.AppendChild(result); XmlElement message = doc.CreateElement("", "Message", ""); message.AppendChild(doc.CreateTextNode(msg)); rootElement.AppendChild(message); return DocToBytes(doc); } private byte[] DocToBytes(XmlDocument doc) { MemoryStream ms = new MemoryStream(); XmlTextWriter xw = new XmlTextWriter(ms, null); xw.Formatting = Formatting.Indented; doc.WriteTo(xw); xw.Flush(); return ms.ToArray(); } #endregion } }
using System; using System.Runtime.InteropServices; using System.Windows.Interop; using Vlc.DotNet.Core.Interops; using System.Windows.Forms.Integration; using System.ComponentModel; using System.Runtime.CompilerServices; using Vlc.DotNet.Core; using System.IO; using System.Windows.Threading; using Vlc.DotNet.Core.Interops.Signatures; namespace WpfVlc { public class VlcControl : WindowsFormsHost, INotifyPropertyChanged { #region interface INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; // This method is called by the Set accessor of each property. // The CallerMemberName attribute that is applied to the optional propertyName // parameter causes the property name of the caller to be substituted as an argument. private void RaisePropertyChanged([CallerMemberName] String propertyName = "") { if (PropertyChanged != null) { PropertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } #endregion private Vlc.DotNet.Forms.VlcControl MediaPlayer; public VlcControl() { MediaPlayer = new Vlc.DotNet.Forms.VlcControl(); this.Child = MediaPlayer; RegistCallback(); RaisePropertyChanged("Rate"); RaisePropertyChanged("Volume"); /* * set a timer */ timer = new DispatcherTimer(DispatcherPriority.Render); timer.Interval = TimeSpan.FromMilliseconds(17); timer.Tick += timer_Tick; old_time = DateTime.UtcNow; } #region timer callback DispatcherTimer timer; DateTime old_time; DateTime now; long delta; public delegate void TimeCallbackDemo(long time); public event TimeCallbackDemo TimeCallback; void timer_Tick(object sender, EventArgs e) { // calc delta now = DateTime.UtcNow; delta = (long)((now - old_time).Milliseconds * MediaPlayer.Rate); old_time = now; if (wait_for_update) return; this.time.time +=delta; if (TimeCallback != null) TimeCallback(this.time.time); RaisePropertyChanged("Time"); //timeFPS = (int)((1000 / delta) + timeFPS) / 2; //RaisePropertyChanged("TimeFPS"); } #endregion #region vlc callback void RegistCallback() { MediaPlayer.BackColor = System.Drawing.ColorTranslator.FromHtml(background); MediaPlayer.VlcLibDirectoryNeeded += VlcLibDirectoryNeeded; MediaPlayer.PositionChanged += PlayerPositionChanged; MediaPlayer.TimeChanged += TimeChanged; MediaPlayer.LengthChanged += LengthChanged; MediaPlayer.EndReached += MediaPlayer_EndReached; } void VlcLibDirectoryNeeded(object sender, Vlc.DotNet.Forms.VlcLibDirectoryNeededEventArgs e) { if (LibVlcPath != null) { e.VlcLibDirectory = new DirectoryInfo(LibVlcPath); vlc_ok = true; return; } // set the vlc path to current direction var currentAssembly = System.Reflection.Assembly.GetEntryAssembly(); var currentDirectory = new FileInfo(currentAssembly.Location).DirectoryName; if (currentDirectory == null) throw new Exception("Can't get Current Direction."); // test is libvlc.dll is exist if (!File.Exists(Path.Combine(currentDirectory,"libvlc.dll"))) throw new FileNotFoundException("LibVlc not found."); // lib vlc is ok vlc_ok = true; e.VlcLibDirectory = new DirectoryInfo(currentDirectory); } public delegate void VideoReachEndDemo(); public event VideoReachEndDemo EndReached; void MediaPlayer_EndReached(object sender, VlcMediaPlayerEndReachedEventArgs e) { this.Dispatcher.BeginInvoke(new Action(delegate { is_end = true; // set to start this.position = 0; RaisePropertyChanged("Position"); this.isPlay = false; if (EndReached != null) EndReached(); })); } void TimeChanged(object sender, VlcMediaPlayerTimeChangedEventArgs e) { this.Dispatcher.BeginInvoke(new Action(delegate { if (MediaPlayer.Time < this.time.time) return; time = MediaPlayer.Time; second = time; wait_for_update = false; RaisePropertyChanged("Second"); })); } void PlayerPositionChanged(object sender, VlcMediaPlayerPositionChangedEventArgs e) { this.Dispatcher.BeginInvoke(new Action(delegate { position = MediaPlayer.Position; RaisePropertyChanged("Position"); RaisePropertyChanged("FPS"); })); } public delegate void TotalTimeChangedDemo(long total_time); public event TotalTimeChangedDemo TotalTimeChanged; void LengthChanged(object sender, VlcMediaPlayerLengthChangedEventArgs e) { this.Dispatcher.BeginInvoke(new Action(delegate { //totalTime = (long)e.NewLength; // this lenght is error if (TotalTimeChanged != null) TotalTimeChanged(MediaPlayer.Length); totalTime = MediaPlayer.Length; RaisePropertyChanged("TotalTime"); })); } #endregion #region property #region time /* * current time for media * as 1ms * // read only */ private Time totalTime = 0; public Time TotalTime { get { return totalTime; } } /* * current time for media * as 1ms */ private Time time = 0; public Time Time { get { return time; } set { if (!MediaPlayer.IsPlaying) return; wait_for_update = true; if (value == time) return; time = value; MediaPlayer.Time = value; } } public Time second; public Time Second { get { return second;} } /* * the media current position * between 0 and 1 */ private double position; public double Position { get { return position; } set { // this only for control video position out side of class if (!is_open) return; if (value < 0) return; if (value == position) return; wait_for_update = true; position = value; MediaPlayer.Position = (float)value; } } #endregion public string LibVlcPath { get; set; } private string source; public string Source { get { return source; } set { if (value == null) return; source = value; this.Open(source); RaisePropertyChanged(); } } #region vidoe or audio control public int Volume { get { return MediaPlayer.Audio.Volume; } set { if (value < 0) return; MediaPlayer.Audio.Volume = value; RaisePropertyChanged(); } } public float Rate { get { return MediaPlayer.Rate; } set { if (value < 0) return; MediaPlayer.Rate = value; RaisePropertyChanged(); } } private string subFile; public string SubFile { get { return subFile; } set { subFile = value; MediaPlayer.SetSubTitle(value); } } private bool mutex; public bool Mutex { get { return mutex; } set { mutex = value; if(mutex && ! MediaPlayer.Audio.IsMute) MediaPlayer.Audio.ToggleMute(); if(!mutex && MediaPlayer.Audio.IsMute) MediaPlayer.Audio.ToggleMute(); } } private bool isPlay; public bool IsPlay { get { return isPlay; } set { if (!vlc_ok || !is_open) { isPlay = false; return; } isPlay = value; wait_for_update = true; if (value) Play(); else Pause(); RaisePropertyChanged(); } } #endregion #region other public string BackColor { get; set; } public float FPS { get { return MediaPlayer.FPS; } } private int timeFPS; public int TimeFPS { get{return timeFPS;} } #endregion #endregion #region local var bool is_end = false; bool vlc_ok = false; bool is_open = false; bool wait_for_update = true; public string background = "#FF252525"; #endregion #region function public void Play() { if (!vlc_ok) return; if (is_end) { MediaPlayer.Play(new FileInfo(source)); is_end = false; } old_time = DateTime.UtcNow; timer.Start(); MediaPlayer.Play(); // set position if need MediaPlayer.Position = (float)this.position; } public void Pause() { if (!vlc_ok || !is_open) return; timer.Stop(); MediaPlayer.Pause(); } void Reset() { // is already open or play a media IsPlay = false; // go to start position = 0; time = 0; RaisePropertyChanged("Position"); RaisePropertyChanged("Time"); } public void Open(string path) { this.source = path; is_open = true; timer.Stop(); MediaPlayer.Pause(); //detect path format if (path.Contains("http") || path.Contains("https")) MediaPlayer.SetMedia(new Uri(source)); else MediaPlayer.SetMedia(new FileInfo(source), null); Reset(); MediaPlayer.Preview(); // call function if need if (EndReached != null) EndReached(); } public void EndInit() { MediaPlayer.EndInit(); } #endregion } }
// **************************************************************** // Copyright 2007, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Drawing; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using NUnit.Core; using NUnit.Core.Extensibility; namespace NUnit.Gui { /// <summary> /// Summary description for AddinDialog. /// </summary> public class AddinDialog : System.Windows.Forms.Form { private IList addins; private System.Windows.Forms.TextBox descriptionTextBox; private System.Windows.Forms.Label label1; private System.Windows.Forms.Button button1; private System.Windows.Forms.ListView addinListView; private System.Windows.Forms.ColumnHeader addinNameColumn; private System.Windows.Forms.ColumnHeader addinStatusColumn; private System.Windows.Forms.Label label2; private System.Windows.Forms.TextBox messageTextBox; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; public AddinDialog() { // // Required for Windows Form Designer support // InitializeComponent(); // // TODO: Add any constructor code after InitializeComponent call // } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose( bool disposing ) { if( disposing ) { if(components != null) { components.Dispose(); } } base.Dispose( disposing ); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(AddinDialog)); this.addinListView = new System.Windows.Forms.ListView(); this.addinNameColumn = new System.Windows.Forms.ColumnHeader(); this.addinStatusColumn = new System.Windows.Forms.ColumnHeader(); this.descriptionTextBox = new System.Windows.Forms.TextBox(); this.label1 = new System.Windows.Forms.Label(); this.button1 = new System.Windows.Forms.Button(); this.label2 = new System.Windows.Forms.Label(); this.messageTextBox = new System.Windows.Forms.TextBox(); this.SuspendLayout(); // // addinListView // this.addinListView.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.addinListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.addinNameColumn, this.addinStatusColumn}); this.addinListView.FullRowSelect = true; this.addinListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.Nonclickable; this.addinListView.Location = new System.Drawing.Point(8, 8); this.addinListView.MultiSelect = false; this.addinListView.Name = "addinListView"; this.addinListView.Size = new System.Drawing.Size(448, 136); this.addinListView.TabIndex = 0; this.addinListView.View = System.Windows.Forms.View.Details; this.addinListView.Resize += new System.EventHandler(this.addinListView_Resize); this.addinListView.SelectedIndexChanged += new System.EventHandler(this.addinListView_SelectedIndexChanged); // // addinNameColumn // this.addinNameColumn.Text = "Addin"; this.addinNameColumn.Width = 352; // // addinStatusColumn // this.addinStatusColumn.Text = "Status"; this.addinStatusColumn.Width = 89; // // descriptionTextBox // this.descriptionTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.descriptionTextBox.Location = new System.Drawing.Point(8, 184); this.descriptionTextBox.Multiline = true; this.descriptionTextBox.Name = "descriptionTextBox"; this.descriptionTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.descriptionTextBox.Size = new System.Drawing.Size(448, 56); this.descriptionTextBox.TabIndex = 1; this.descriptionTextBox.Text = ""; // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label1.Location = new System.Drawing.Point(8, 160); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(304, 16); this.label1.TabIndex = 2; this.label1.Text = "Description:"; // // button1 // this.button1.Anchor = System.Windows.Forms.AnchorStyles.Bottom; this.button1.Location = new System.Drawing.Point(192, 344); this.button1.Name = "button1"; this.button1.TabIndex = 3; this.button1.Text = "OK"; this.button1.Click += new System.EventHandler(this.button1_Click); // // label2 // this.label2.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left))); this.label2.Location = new System.Drawing.Point(8, 256); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(304, 16); this.label2.TabIndex = 5; this.label2.Text = " Message:"; // // messageTextBox // this.messageTextBox.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.messageTextBox.Location = new System.Drawing.Point(8, 280); this.messageTextBox.Multiline = true; this.messageTextBox.Name = "messageTextBox"; this.messageTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical; this.messageTextBox.Size = new System.Drawing.Size(448, 56); this.messageTextBox.TabIndex = 4; this.messageTextBox.Text = ""; // // AddinDialog // this.ClientSize = new System.Drawing.Size(464, 376); this.Controls.Add(this.label2); this.Controls.Add(this.messageTextBox); this.Controls.Add(this.button1); this.Controls.Add(this.label1); this.Controls.Add(this.descriptionTextBox); this.Controls.Add(this.addinListView); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "AddinDialog"; this.ShowInTaskbar = false; this.Text = "Registered Addins"; this.Load += new System.EventHandler(this.AddinDialog_Load); this.ResumeLayout(false); } #endregion private void AddinDialog_Load(object sender, System.EventArgs e) { this.addins = NUnit.Util.Services.AddinRegistry.Addins; foreach( Addin addin in addins ) { ListViewItem item = new ListViewItem( new string[] { addin.Name, addin.Status.ToString() } ); addinListView.Items.Add( item ); } if ( addinListView.Items.Count > 0 ) addinListView.Items[0].Selected = true; AutoSizeFirstColumnOfListView(); } private void button1_Click(object sender, System.EventArgs e) { this.Close(); } private void addinListView_SelectedIndexChanged(object sender, System.EventArgs e) { if ( addinListView.SelectedIndices.Count > 0 ) { int index = addinListView.SelectedIndices[0]; Addin addin = (Addin)addins[index]; this.descriptionTextBox.Text = addin.Description; this.messageTextBox.Text = addin.Message; } } private void addinListView_Resize(object sender, System.EventArgs e) { AutoSizeFirstColumnOfListView(); } private void AutoSizeFirstColumnOfListView() { int width = addinListView.ClientSize.Width; for( int i = 1; i < addinListView.Columns.Count; i++ ) width -= addinListView.Columns[i].Width; addinListView.Columns[0].Width = width; } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.IO; using System.Net.Http.Headers; using System.ServiceModel.Diagnostics; using System.Runtime; using System.Threading; using System.Threading.Tasks; namespace System.ServiceModel.Channels { public abstract class MessageEncoder { public abstract string ContentType { get; } public abstract string MediaType { get; } public abstract MessageVersion MessageVersion { get; } public virtual T GetProperty<T>() where T : class { if (typeof(T) == typeof(FaultConverter)) { return (T)(object)FaultConverter.GetDefaultFaultConverter(this.MessageVersion); } return null; } public Message ReadMessage(Stream stream, int maxSizeOfHeaders) { return ReadMessage(stream, maxSizeOfHeaders, null); } public virtual Task<Message> ReadMessageAsync(Stream stream, int maxSizeOfHeaders, string contentType) { return Task.FromResult(ReadMessage(stream, maxSizeOfHeaders, contentType)); } public virtual Task<Message> ReadMessageAsync(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType) { return Task.FromResult(ReadMessage(buffer, bufferManager, contentType)); } public abstract Message ReadMessage(Stream stream, int maxSizeOfHeaders, string contentType); public Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager) { Message message = ReadMessage(buffer, bufferManager, null); return message; } public abstract Message ReadMessage(ArraySegment<byte> buffer, BufferManager bufferManager, string contentType); // used for buffered streaming internal async Task<ArraySegment<byte>> BufferMessageStreamAsync(Stream stream, BufferManager bufferManager, int maxBufferSize, CancellationToken cancellationToken) { byte[] buffer = bufferManager.TakeBuffer(ConnectionOrientedTransportDefaults.ConnectionBufferSize); int offset = 0; int currentBufferSize = Math.Min(buffer.Length, maxBufferSize); while (offset < currentBufferSize) { int count = await stream.ReadAsync(buffer, offset, currentBufferSize - offset, cancellationToken); if (count == 0) { stream.Dispose(); break; } offset += count; if (offset == currentBufferSize) { if (currentBufferSize >= maxBufferSize) { throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(MaxMessageSizeStream.CreateMaxReceivedMessageSizeExceededException(maxBufferSize)); } currentBufferSize = Math.Min(currentBufferSize * 2, maxBufferSize); byte[] temp = bufferManager.TakeBuffer(currentBufferSize); Buffer.BlockCopy(buffer, 0, temp, 0, offset); bufferManager.ReturnBuffer(buffer); buffer = temp; } } return new ArraySegment<byte>(buffer, 0, offset); } // used for buffered streaming internal virtual async Task<Message> ReadMessageAsync(Stream stream, BufferManager bufferManager, int maxBufferSize, string contentType, CancellationToken cancellationToken) { return ReadMessage(await BufferMessageStreamAsync(stream, bufferManager, maxBufferSize, cancellationToken), bufferManager, contentType); } public override string ToString() { return ContentType; } public abstract void WriteMessage(Message message, Stream stream); public virtual IAsyncResult BeginWriteMessage(Message message, Stream stream, AsyncCallback callback, object state) { return this.WriteMessageAsync(message, stream).ToApm(callback, state); } public virtual void EndWriteMessage(IAsyncResult result) { result.ToApmEnd(); } public ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager) { ArraySegment<byte> arraySegment = WriteMessage(message, maxMessageSize, bufferManager, 0); return arraySegment; } public abstract ArraySegment<byte> WriteMessage(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset); public virtual Task WriteMessageAsync(Message message, Stream stream) { WriteMessage(message, stream); return TaskHelpers.CompletedTask(); } public virtual Task<ArraySegment<byte>> WriteMessageAsync(Message message, int maxMessageSize, BufferManager bufferManager, int messageOffset) { return Task.FromResult(WriteMessage(message, maxMessageSize, bufferManager, messageOffset)); } public virtual bool IsContentTypeSupported(string contentType) { if (contentType == null) throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(new ArgumentNullException("contentType")); return IsContentTypeSupported(contentType, this.ContentType, this.MediaType); } internal bool IsContentTypeSupported(string contentType, string supportedContentType, string supportedMediaType) { if (supportedContentType == contentType) return true; if (contentType.Length > supportedContentType.Length && contentType.StartsWith(supportedContentType, StringComparison.Ordinal) && contentType[supportedContentType.Length] == ';') return true; // now check case-insensitively if (contentType.StartsWith(supportedContentType, StringComparison.OrdinalIgnoreCase)) { if (contentType.Length == supportedContentType.Length) { return true; } else if (contentType.Length > supportedContentType.Length) { char ch = contentType[supportedContentType.Length]; // Linear Whitespace is allowed to appear between the end of one property and the semicolon. // LWS = [CRLF]? (SP | HT)+ if (ch == ';') { return true; } // Consume the [CRLF]? int i = supportedContentType.Length; if (ch == '\r' && contentType.Length > supportedContentType.Length + 1 && contentType[i + 1] == '\n') { i += 2; ch = contentType[i]; } // Look for a ';' or nothing after (SP | HT)+ if (ch == ' ' || ch == '\t') { i++; while (i < contentType.Length) { ch = contentType[i]; if (ch != ' ' && ch != '\t') break; ++i; } } if (ch == ';' || i == contentType.Length) return true; } } // sometimes we get a contentType that has parameters, but our encoders // merely expose the base content-type, so we will check a stripped version try { MediaTypeHeaderValue parsedContentType = MediaTypeHeaderValue.Parse(contentType); if (supportedMediaType.Length > 0 && !supportedMediaType.Equals(parsedContentType.MediaType, StringComparison.OrdinalIgnoreCase)) return false; if (!IsCharSetSupported(parsedContentType.CharSet)) return false; } catch (FormatException) { // bad content type, so we definitely don't support it! return false; } return true; } internal virtual bool IsCharSetSupported(string charset) { return false; } internal void ThrowIfMismatchedMessageVersion(Message message) { if (message.Version != MessageVersion) { throw TraceUtility.ThrowHelperError( new ProtocolException(SR.Format(SR.EncoderMessageVersionMismatch, message.Version, MessageVersion)), message); } } } }
// // Mono.Data.TdsClient.TdsConnection.cs // // Authors: // Tim Coleman (tim@timcoleman.com) // Daniel Morgan (danmorg@sc.rr.com) // // Copyright (C) Tim Coleman, 2002, 2003 // Copyright (C) Daniel Morgan, 2003 // // // 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 Mono.Data.Tds.Protocol; using System; using System.Collections; using System.Collections.Specialized; using System.ComponentModel; using System.Data; using System.Data.Common; using System.EnterpriseServices; using System.Net; using System.Net.Sockets; using System.Text; namespace Mono.Data.TdsClient { public sealed class TdsConnection : Component, IDbConnection, ICloneable { #region Fields bool disposed = false; // The set of SQL connection pools static TdsConnectionPoolManager tdsConnectionPools = new TdsConnectionPoolManager (TdsVersion.tds42); // The current connection pool TdsConnectionPool pool; // The connection string that identifies this connection string connectionString = null; // The transaction object for the current transaction TdsTransaction transaction = null; // Connection parameters TdsConnectionParameters parms = new TdsConnectionParameters (); bool connectionReset; bool pooling; string dataSource; int connectionTimeout; int minPoolSize; int maxPoolSize; int packetSize; int port = 1533; // The current state ConnectionState state = ConnectionState.Closed; TdsDataReader dataReader = null; // The TDS object ITds tds; #endregion // Fields #region Constructors public TdsConnection () : this (String.Empty) { } public TdsConnection (string connectionString) { ConnectionString = connectionString; } #endregion // Constructors #region Properties public string ConnectionString { get { return connectionString; } set { SetConnectionString (value); } } public int ConnectionTimeout { get { return connectionTimeout; } } public string Database { get { return tds.Database; } } internal TdsDataReader DataReader { get { return dataReader; } set { dataReader = value; } } public string DataSource { get { return dataSource; } } public int PacketSize { get { return packetSize; } } public string ServerVersion { get { return tds.ServerVersion; } } public ConnectionState State { get { return state; } } internal ITds Tds { get { return tds; } } internal TdsTransaction Transaction { get { return transaction; } set { transaction = value; } } public string WorkstationId { get { return parms.Hostname; } } #endregion // Properties #region Events and Delegates public event TdsInfoMessageEventHandler InfoMessage; public event StateChangeEventHandler StateChange; private void ErrorHandler (object sender, TdsInternalErrorMessageEventArgs e) { throw new TdsException (e.Class, e.LineNumber, e.Message, e.Number, e.Procedure, e.Server, "Mono TdsClient Data Provider", e.State); } private void MessageHandler (object sender, TdsInternalInfoMessageEventArgs e) { OnTdsInfoMessage (CreateTdsInfoMessageEvent (e.Errors)); } #endregion // Events and Delegates #region Methods public TdsTransaction BeginTransaction () { return BeginTransaction (IsolationLevel.ReadCommitted, String.Empty); } public TdsTransaction BeginTransaction (IsolationLevel iso) { return BeginTransaction (iso, String.Empty); } public TdsTransaction BeginTransaction (string transactionName) { return BeginTransaction (IsolationLevel.ReadCommitted, transactionName); } public TdsTransaction BeginTransaction (IsolationLevel iso, string transactionName) { if (State == ConnectionState.Closed) throw new InvalidOperationException ("The connection is not open."); if (Transaction != null) throw new InvalidOperationException ("TdsConnection does not support parallel transactions."); string isolevel = String.Empty; switch (iso) { case IsolationLevel.Chaos: isolevel = "CHAOS"; break; case IsolationLevel.ReadCommitted: isolevel = "READ COMMITTED"; break; case IsolationLevel.ReadUncommitted: isolevel = "READ UNCOMMITTED"; break; case IsolationLevel.RepeatableRead: isolevel = "REPEATABLE READ"; break; case IsolationLevel.Serializable: isolevel = "SERIALIZABLE"; break; } tds.Execute (String.Format ("SET TRANSACTION ISOLATION LEVEL {0}\nBEGIN TRANSACTION {1}", isolevel, transactionName)); transaction = new TdsTransaction (this, iso); return transaction; } public void ChangeDatabase (string database) { if (!IsValidDatabaseName (database)) throw new ArgumentException (String.Format ("The database name {0} is not valid.")); if (State != ConnectionState.Open) throw new InvalidOperationException ("The connection is not open"); tds.Execute (String.Format ("use {0}", database)); } private void ChangeState (ConnectionState currentState) { ConnectionState originalState = state; state = currentState; OnStateChange (CreateStateChangeEvent (originalState, currentState)); } public void Close () { if (Transaction != null && Transaction.IsOpen) Transaction.Rollback (); if (pooling) pool.ReleaseConnection (tds); else tds.Disconnect (); tds.TdsErrorMessage -= new TdsInternalErrorMessageEventHandler (ErrorHandler); tds.TdsInfoMessage -= new TdsInternalInfoMessageEventHandler (MessageHandler); ChangeState (ConnectionState.Closed); } public TdsCommand CreateCommand () { TdsCommand command = new TdsCommand (); command.Connection = this; return command; } private StateChangeEventArgs CreateStateChangeEvent (ConnectionState originalState, ConnectionState currentState) { return new StateChangeEventArgs (originalState, currentState); } private TdsInfoMessageEventArgs CreateTdsInfoMessageEvent (TdsInternalErrorCollection errors) { return new TdsInfoMessageEventArgs (errors); } protected override void Dispose (bool disposing) { if (!disposed) { if (disposing) { if (State == ConnectionState.Open) Close (); parms = null; dataSource = null; } base.Dispose (disposing); disposed = true; } } [MonoTODO] public void EnlistDistributedTransaction (ITransaction transaction) { throw new NotImplementedException (); } object ICloneable.Clone () { return new TdsConnection (ConnectionString); } IDbTransaction IDbConnection.BeginTransaction () { return BeginTransaction (); } IDbTransaction IDbConnection.BeginTransaction (IsolationLevel iso) { return BeginTransaction (iso); } IDbCommand IDbConnection.CreateCommand () { return CreateCommand (); } void IDisposable.Dispose () { Dispose (true); GC.SuppressFinalize (this); } [MonoTODO ("Figure out the Tds way to reset the connection.")] public void Open () { string serverName = ""; if (connectionString == null) throw new InvalidOperationException ("Connection string has not been initialized."); try { if (!pooling) { ParseDataSource (dataSource, out port, out serverName); tds = new Tds42 (serverName, port, PacketSize, ConnectionTimeout); } else { ParseDataSource (dataSource, out port, out serverName); TdsConnectionInfo info = new TdsConnectionInfo (serverName, port, packetSize, ConnectionTimeout, minPoolSize, maxPoolSize); pool = tdsConnectionPools.GetConnectionPool (connectionString, info); tds = pool.GetConnection (); } } catch (TdsTimeoutException e) { throw TdsException.FromTdsInternalException ((TdsInternalException) e); } tds.TdsErrorMessage += new TdsInternalErrorMessageEventHandler (ErrorHandler); tds.TdsInfoMessage += new TdsInternalInfoMessageEventHandler (MessageHandler); if (!tds.IsConnected) { try { tds.Connect (parms); ChangeState (ConnectionState.Open); ChangeDatabase (parms.Database); } catch { if (pooling) pool.ReleaseConnection (tds); throw; } } else if (connectionReset) { // tds.ExecuteNonQuery ("EXEC sp_reset_connection"); FIXME ChangeState (ConnectionState.Open); } } private void ParseDataSource (string theDataSource, out int thePort, out string theServerName) { theServerName = ""; thePort = 1433; // default TCP port for SQL Server int idx = 0; if ((idx = theDataSource.IndexOf (",")) > -1) { theServerName = theDataSource.Substring (0, idx); string p = theDataSource.Substring (idx + 1); thePort = Int32.Parse (p); } else { theServerName = theDataSource; } } void SetConnectionString (string connectionString) { connectionString += ";"; NameValueCollection parameters = new NameValueCollection (); if (connectionString == String.Empty) return; bool inQuote = false; bool inDQuote = false; string name = String.Empty; string value = String.Empty; StringBuilder sb = new StringBuilder (); foreach (char c in connectionString) { switch (c) { case '\'': inQuote = !inQuote; break; case '"' : inDQuote = !inDQuote; break; case ';' : if (!inDQuote && !inQuote) { if (name != String.Empty && name != null) { value = sb.ToString (); parameters [name.ToUpper ().Trim ()] = value.Trim (); } name = String.Empty; value = String.Empty; sb = new StringBuilder (); } else sb.Append (c); break; case '=' : if (!inDQuote && !inQuote) { name = sb.ToString (); sb = new StringBuilder (); } else sb.Append (c); break; default: sb.Append (c); break; } } if (this.ConnectionString == null) { SetDefaultConnectionParameters (parameters); } SetProperties (parameters); this.connectionString = connectionString; } void SetDefaultConnectionParameters (NameValueCollection parameters) { if (null == parameters.Get ("APPLICATION NAME")) parameters["APPLICATION NAME"] = ".Net TdsClient Data Provider"; if (null == parameters.Get ("CONNECT TIMEOUT") && null == parameters.Get ("CONNECTION TIMEOUT")) parameters["CONNECT TIMEOUT"] = "15"; if (null == parameters.Get ("CONNECTION LIFETIME")) parameters["CONNECTION LIFETIME"] = "0"; if (null == parameters.Get ("CONNECTION RESET")) parameters["CONNECTION RESET"] = "true"; if (null == parameters.Get ("ENLIST")) parameters["ENLIST"] = "true"; if (null == parameters.Get ("INTEGRATED SECURITY") && null == parameters.Get ("TRUSTED_CONNECTION")) parameters["INTEGRATED SECURITY"] = "false"; if (null == parameters.Get ("MAX POOL SIZE")) parameters["MAX POOL SIZE"] = "100"; if (null == parameters.Get ("MIN POOL SIZE")) parameters["MIN POOL SIZE"] = "0"; if (null == parameters.Get ("NETWORK LIBRARY") && null == parameters.Get ("NET")) parameters["NETWORK LIBRARY"] = "dbmssocn"; if (null == parameters.Get ("PACKET SIZE")) parameters["PACKET SIZE"] = "512"; if (null == parameters.Get ("PERSIST SECURITY INFO")) parameters["PERSIST SECURITY INFO"] = "false"; if (null == parameters.Get ("POOLING")) parameters["POOLING"] = "true"; if (null == parameters.Get ("WORKSTATION ID")) parameters["WORKSTATION ID"] = Dns.GetHostByName ("localhost").HostName; } private void SetProperties (NameValueCollection parameters) { string value; foreach (string name in parameters) { value = parameters[name]; switch (name) { case "APPLICATION NAME" : parms.ApplicationName = value; break; case "ATTACHDBFILENAME" : case "EXTENDED PROPERTIES" : case "INITIAL FILE NAME" : break; case "CONNECT TIMEOUT" : case "CONNECTION TIMEOUT" : connectionTimeout = Int32.Parse (value); break; case "CONNECTION LIFETIME" : break; case "CONNECTION RESET" : connectionReset = !(value.ToUpper ().Equals ("FALSE") || value.ToUpper ().Equals ("NO")); break; case "CURRENT LANGUAGE" : parms.Language = value; break; case "DATA SOURCE" : case "SERVER" : case "ADDRESS" : case "ADDR" : case "NETWORK ADDRESS" : dataSource = value; break; case "ENLIST" : break; case "INITIAL CATALOG" : case "DATABASE" : parms.Database = value; break; case "INTEGRATED SECURITY" : case "TRUSTED_CONNECTION" : break; case "MAX POOL SIZE" : maxPoolSize = Int32.Parse (value); break; case "MIN POOL SIZE" : minPoolSize = Int32.Parse (value); break; case "NET" : case "NETWORK LIBRARY" : if (!value.ToUpper ().Equals ("DBMSSOCN")) throw new ArgumentException ("Unsupported network library."); break; case "PACKET SIZE" : packetSize = Int32.Parse (value); break; case "PASSWORD" : case "PWD" : parms.Password = value; break; case "PERSIST SECURITY INFO" : break; case "POOLING" : pooling = !(value.ToUpper ().Equals ("FALSE") || value.ToUpper ().Equals ("NO")); break; case "USER ID" : parms.User = value; break; case "WORKSTATION ID" : parms.Hostname = value; break; } } } static bool IsValidDatabaseName (string database) { if (database.Length > 32 || database.Length < 1) return false; if (database[0] == '"' && database[database.Length] == '"') database = database.Substring (1, database.Length - 2); else if (Char.IsDigit (database[0])) return false; if (database[0] == '_') return false; foreach (char c in database.Substring (1, database.Length - 1)) if (!Char.IsLetterOrDigit (c) && c != '_') return false; return true; } private void OnTdsInfoMessage (TdsInfoMessageEventArgs value) { if (InfoMessage != null) InfoMessage (this, value); } private void OnStateChange (StateChangeEventArgs value) { if (StateChange != null) StateChange (this, value); } #endregion // Methods } }
// 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 Microsoft.VisualStudio.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.VisualStudio.InteractiveWindow.UnitTests { public class InteractiveWindowHistoryTests : IDisposable { #region Helpers private readonly InteractiveWindowTestHost _testHost; private readonly IInteractiveWindow _window; private readonly IInteractiveWindowOperations _operations; public InteractiveWindowHistoryTests() { _testHost = new InteractiveWindowTestHost(); _window = _testHost.Window; _operations = _window.Operations; } void IDisposable.Dispose() { _testHost.Dispose(); } /// <summary> /// Sets the active code to the specified text w/o executing it. /// </summary> private void SetActiveCode(string text) { using (var edit = _window.CurrentLanguageBuffer.CreateEdit(EditOptions.None, reiteratedVersionNumber: null, editTag: null)) { edit.Replace(new Span(0, _window.CurrentLanguageBuffer.CurrentSnapshot.Length), text); edit.Apply(); } } private void InsertAndExecuteInputs(params string[] inputs) { foreach (var input in inputs) { InsertAndExecuteInput(input); } } private void InsertAndExecuteInput(string input) { _window.InsertCode(input); AssertCurrentSubmission(input); ExecuteInput(); } private void ExecuteInput() { ((InteractiveWindow)_window).ExecuteInputAsync().PumpingWait(); } private void AssertCurrentSubmission(string expected) { Assert.Equal(expected, _window.CurrentLanguageBuffer.CurrentSnapshot.GetText()); } #endregion Helpers [WpfFact] public void CheckHistoryPrevious() { const string inputString = "1 "; InsertAndExecuteInput(inputString); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString); } [WpfFact] public void CheckHistoryPreviousNotCircular() { //submit, submit, up, up, up const string inputString1 = "1 "; const string inputString2 = "2 "; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); //this up should not be circular _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); } [WpfFact] public void CheckHistoryPreviousAfterSubmittingEntryFromHistory() { //submit, submit, submit, up, up, submit, up, up, up const string inputString1 = "1 "; const string inputString2 = "2 "; const string inputString3 = "3 "; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); InsertAndExecuteInput(inputString3); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString3); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); ExecuteInput(); //history navigation should start from the last history pointer _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); //has reached the top, no change _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); } [WpfFact] public void CheckHistoryPreviousAfterSubmittingNewEntryWhileNavigatingHistory() { //submit, submit, up, up, submit new, up, up, up const string inputString1 = "1 "; const string inputString2 = "2 "; const string inputString3 = "3 "; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); SetActiveCode(inputString3); AssertCurrentSubmission(inputString3); ExecuteInput(); //History pointer should be reset. Previous should now bring up last entry _operations.HistoryPrevious(); AssertCurrentSubmission(inputString3); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); //has reached the top, no change _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); } [WpfFact] public void CheckHistoryNextNotCircular() { //submit, submit, down, up, down, down const string inputString1 = "1 "; const string inputString2 = "2 "; const string empty = ""; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); //Next should do nothing as history pointer is uninitialized and there is //no next entry. Buffer should be empty _operations.HistoryNext(); AssertCurrentSubmission(empty); //Go back once entry _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); //Go fwd one entry - should do nothing as history pointer is at last entry //buffer should have same value as before _operations.HistoryNext(); AssertCurrentSubmission(inputString2); //Next should again do nothing as it is the last item, buffer should have the same value _operations.HistoryNext(); AssertCurrentSubmission(inputString2); //This is to make sure the window doesn't crash ExecuteInput(); AssertCurrentSubmission(empty); } [WpfFact] public void CheckHistoryNextAfterSubmittingEntryFromHistory() { //submit, submit, submit, up, up, submit, down, down, down const string inputString1 = "1 "; const string inputString2 = "2 "; const string inputString3 = "3 "; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); InsertAndExecuteInput(inputString3); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString3); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); //submit inputString2 again. Should be added at the end of history ExecuteInput(); //history navigation should start from the last history pointer _operations.HistoryNext(); AssertCurrentSubmission(inputString3); //This next should take us to the InputString2 which was resubmitted _operations.HistoryNext(); AssertCurrentSubmission(inputString2); //has reached the top, no change _operations.HistoryNext(); AssertCurrentSubmission(inputString2); } [WpfFact] public void CheckHistoryNextAfterSubmittingNewEntryWhileNavigatingHistory() { //submit, submit, up, up, submit new, down, up const string inputString1 = "1 "; const string inputString2 = "2 "; const string inputString3 = "3 "; const string empty = ""; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString2); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString1); SetActiveCode(inputString3); AssertCurrentSubmission(inputString3); ExecuteInput(); //History pointer should be reset. next should do nothing _operations.HistoryNext(); AssertCurrentSubmission(empty); _operations.HistoryPrevious(); AssertCurrentSubmission(inputString3); } [WpfFact] public void CheckUncommittedInputAfterNavigatingHistory() { //submit, submit, up, up, submit new, down, up const string inputString1 = "1 "; const string inputString2 = "2 "; const string uncommittedInput = "uncommittedInput"; InsertAndExecuteInput(inputString1); InsertAndExecuteInput(inputString2); //Add uncommitted input SetActiveCode(uncommittedInput); //Navigate history. This should save uncommitted input _operations.HistoryPrevious(); //Navigate to next item at the end of history. //This should bring back uncommitted input _operations.HistoryNext(); AssertCurrentSubmission(uncommittedInput); } [WpfFact] public void CheckHistoryPreviousAfterReset() { const string resetCommand1 = "#reset"; const string resetCommand2 = "#reset "; InsertAndExecuteInput(resetCommand1); InsertAndExecuteInput(resetCommand2); _operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand2); _operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand1); _operations.HistoryPrevious(); AssertCurrentSubmission(resetCommand1); } [WpfFact] public void TestHistoryPrevious() { InsertAndExecuteInputs("1", "2", "3"); _operations.HistoryPrevious(); AssertCurrentSubmission("3"); _operations.HistoryPrevious(); AssertCurrentSubmission("2"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); } [WpfFact] public void TestHistoryNext() { InsertAndExecuteInputs("1", "2", "3"); SetActiveCode("4"); _operations.HistoryNext(); AssertCurrentSubmission("4"); _operations.HistoryNext(); AssertCurrentSubmission("4"); _operations.HistoryPrevious(); AssertCurrentSubmission("3"); _operations.HistoryPrevious(); AssertCurrentSubmission("2"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryNext(); AssertCurrentSubmission("2"); _operations.HistoryNext(); AssertCurrentSubmission("3"); _operations.HistoryNext(); AssertCurrentSubmission("4"); _operations.HistoryNext(); AssertCurrentSubmission("4"); } [WpfFact] public void TestHistoryPreviousWithPattern_NoMatch() { InsertAndExecuteInputs("123", "12", "1"); _operations.HistoryPrevious("4"); AssertCurrentSubmission(""); _operations.HistoryPrevious("4"); AssertCurrentSubmission(""); } [WpfFact] public void TestHistoryPreviousWithPattern_PatternMaintained() { InsertAndExecuteInputs("123", "12", "1"); _operations.HistoryPrevious("12"); AssertCurrentSubmission("12"); // Skip over non-matching entry. _operations.HistoryPrevious("12"); AssertCurrentSubmission("123"); _operations.HistoryPrevious("12"); AssertCurrentSubmission("123"); } [WpfFact] public void TestHistoryPreviousWithPattern_PatternDropped() { InsertAndExecuteInputs("1", "2", "3"); _operations.HistoryPrevious("2"); AssertCurrentSubmission("2"); // Skip over non-matching entry. _operations.HistoryPrevious(null); AssertCurrentSubmission("1"); // Pattern isn't passed, so return to normal iteration. _operations.HistoryPrevious(null); AssertCurrentSubmission("1"); } [WpfFact] public void TestHistoryPreviousWithPattern_PatternChanged() { InsertAndExecuteInputs("10", "20", "15", "25"); _operations.HistoryPrevious("1"); AssertCurrentSubmission("15"); // Skip over non-matching entry. _operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); // Skip over non-matching entry. _operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); } [WpfFact] public void TestHistoryNextWithPattern_NoMatch() { InsertAndExecuteInputs("start", "1", "12", "123"); SetActiveCode("end"); _operations.HistoryPrevious(); AssertCurrentSubmission("123"); _operations.HistoryPrevious(); AssertCurrentSubmission("12"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("start"); _operations.HistoryNext("4"); AssertCurrentSubmission("end"); _operations.HistoryNext("4"); AssertCurrentSubmission("end"); } [WpfFact] public void TestHistoryNextWithPattern_PatternMaintained() { InsertAndExecuteInputs("start", "1", "12", "123"); SetActiveCode("end"); _operations.HistoryPrevious(); AssertCurrentSubmission("123"); _operations.HistoryPrevious(); AssertCurrentSubmission("12"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("start"); _operations.HistoryNext("12"); AssertCurrentSubmission("12"); // Skip over non-matching entry. _operations.HistoryNext("12"); AssertCurrentSubmission("123"); _operations.HistoryNext("12"); AssertCurrentSubmission("end"); } [WpfFact] public void TestHistoryNextWithPattern_PatternDropped() { InsertAndExecuteInputs("start", "3", "2", "1"); SetActiveCode("end"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("2"); _operations.HistoryPrevious(); AssertCurrentSubmission("3"); _operations.HistoryPrevious(); AssertCurrentSubmission("start"); _operations.HistoryNext("2"); AssertCurrentSubmission("2"); // Skip over non-matching entry. _operations.HistoryNext(null); AssertCurrentSubmission("1"); // Pattern isn't passed, so return to normal iteration. _operations.HistoryNext(null); AssertCurrentSubmission("end"); } [WpfFact] public void TestHistoryNextWithPattern_PatternChanged() { InsertAndExecuteInputs("start", "25", "15", "20", "10"); SetActiveCode("end"); _operations.HistoryPrevious(); AssertCurrentSubmission("10"); _operations.HistoryPrevious(); AssertCurrentSubmission("20"); _operations.HistoryPrevious(); AssertCurrentSubmission("15"); _operations.HistoryPrevious(); AssertCurrentSubmission("25"); _operations.HistoryPrevious(); AssertCurrentSubmission("start"); _operations.HistoryNext("1"); AssertCurrentSubmission("15"); // Skip over non-matching entry. _operations.HistoryNext("2"); AssertCurrentSubmission("20"); // Skip over non-matching entry. _operations.HistoryNext("2"); AssertCurrentSubmission("end"); } [WpfFact] public void TestHistorySearchPrevious() { InsertAndExecuteInputs("123", "12", "1"); // Default search string is empty. _operations.HistorySearchPrevious(); AssertCurrentSubmission("1"); // Pattern is captured before this step. _operations.HistorySearchPrevious(); AssertCurrentSubmission("12"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); } [WpfFact] public void TestHistorySearchPreviousWithPattern() { InsertAndExecuteInputs("123", "12", "1"); SetActiveCode("12"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("12"); // Pattern is captured before this step. _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("123"); } [WpfFact] public void TestHistorySearchNextWithPattern() { InsertAndExecuteInputs("12", "123", "12", "1"); SetActiveCode("end"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistoryPrevious(); AssertCurrentSubmission("12"); _operations.HistoryPrevious(); AssertCurrentSubmission("123"); _operations.HistoryPrevious(); AssertCurrentSubmission("12"); _operations.HistorySearchNext(); AssertCurrentSubmission("123"); // Pattern is captured before this step. _operations.HistorySearchNext(); AssertCurrentSubmission("12"); _operations.HistorySearchNext(); AssertCurrentSubmission("end"); } [WpfFact] public void TestHistoryPreviousAndSearchPrevious() { InsertAndExecuteInputs("200", "100", "30", "20", "10", "2", "1"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("10"); // Pattern is captured before this step. _operations.HistoryPrevious(); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); _operations.HistoryPrevious(); AssertCurrentSubmission("200"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("200"); // No-op results in non-matching history entry after SearchPrevious. } [WpfFact] public void TestHistoryPreviousAndSearchPrevious_ExplicitPattern() { InsertAndExecuteInputs("200", "100", "30", "20", "10", "2", "1"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("10"); // Pattern is captured before this step. _operations.HistoryPrevious("2"); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. _operations.HistorySearchPrevious(); AssertCurrentSubmission("100"); _operations.HistoryPrevious("2"); AssertCurrentSubmission("200"); _operations.HistorySearchPrevious(); AssertCurrentSubmission("200"); // No-op results in non-matching history entry after SearchPrevious. } [WpfFact] public void TestHistoryNextAndSearchNext() { InsertAndExecuteInputs("1", "2", "10", "20", "30", "100", "200"); SetActiveCode("4"); _operations.HistoryPrevious(); AssertCurrentSubmission("200"); _operations.HistoryPrevious(); AssertCurrentSubmission("100"); _operations.HistoryPrevious(); AssertCurrentSubmission("30"); _operations.HistoryPrevious(); AssertCurrentSubmission("20"); _operations.HistoryPrevious(); AssertCurrentSubmission("10"); _operations.HistoryPrevious(); AssertCurrentSubmission("2"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistorySearchNext(); AssertCurrentSubmission("10"); // Pattern is captured before this step. _operations.HistoryNext(); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. _operations.HistorySearchNext(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. _operations.HistorySearchNext(); AssertCurrentSubmission("4"); // Restoring input results in non-matching history entry after SearchNext. _operations.HistoryNext(); AssertCurrentSubmission("4"); } [WpfFact] public void TestHistoryNextAndSearchNext_ExplicitPattern() { InsertAndExecuteInputs("1", "2", "10", "20", "30", "100", "200"); SetActiveCode("4"); _operations.HistoryPrevious(); AssertCurrentSubmission("200"); _operations.HistoryPrevious(); AssertCurrentSubmission("100"); _operations.HistoryPrevious(); AssertCurrentSubmission("30"); _operations.HistoryPrevious(); AssertCurrentSubmission("20"); _operations.HistoryPrevious(); AssertCurrentSubmission("10"); _operations.HistoryPrevious(); AssertCurrentSubmission("2"); _operations.HistoryPrevious(); AssertCurrentSubmission("1"); _operations.HistorySearchNext(); AssertCurrentSubmission("10"); // Pattern is captured before this step. _operations.HistoryNext("2"); AssertCurrentSubmission("20"); // NB: Doesn't match pattern. _operations.HistorySearchNext(); AssertCurrentSubmission("100"); // NB: Reuses existing pattern. _operations.HistorySearchNext(); AssertCurrentSubmission("4"); // Restoring input results in non-matching history entry after SearchNext. _operations.HistoryNext("2"); AssertCurrentSubmission("4"); } } }
// Copyright 2021 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! using gax = Google.Api.Gax; using sys = System; namespace Google.Ads.GoogleAds.V9.Resources { /// <summary>Resource name for the <c>AdGroupFeed</c> resource.</summary> public sealed partial class AdGroupFeedName : gax::IResourceName, sys::IEquatable<AdGroupFeedName> { /// <summary>The possible contents of <see cref="AdGroupFeedName"/>.</summary> public enum ResourceNameType { /// <summary>An unparsed resource name.</summary> Unparsed = 0, /// <summary> /// A resource name with pattern <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>. /// </summary> CustomerAdGroupFeed = 1, } private static gax::PathTemplate s_customerAdGroupFeed = new gax::PathTemplate("customers/{customer_id}/adGroupFeeds/{ad_group_id_feed_id}"); /// <summary>Creates a <see cref="AdGroupFeedName"/> 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="AdGroupFeedName"/> containing the provided /// <paramref name="unparsedResourceName"/>. /// </returns> public static AdGroupFeedName FromUnparsed(gax::UnparsedResourceName unparsedResourceName) => new AdGroupFeedName(ResourceNameType.Unparsed, gax::GaxPreconditions.CheckNotNull(unparsedResourceName, nameof(unparsedResourceName))); /// <summary> /// Creates a <see cref="AdGroupFeedName"/> with the pattern /// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <returns>A new instance of <see cref="AdGroupFeedName"/> constructed from the provided ids.</returns> public static AdGroupFeedName FromCustomerAdGroupFeed(string customerId, string adGroupId, string feedId) => new AdGroupFeedName(ResourceNameType.CustomerAdGroupFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId))); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupFeedName"/> with pattern /// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupFeedName"/> with pattern /// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>. /// </returns> public static string Format(string customerId, string adGroupId, string feedId) => FormatCustomerAdGroupFeed(customerId, adGroupId, feedId); /// <summary> /// Formats the IDs into the string representation of this <see cref="AdGroupFeedName"/> with pattern /// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>. /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> /// <returns> /// The string representation of this <see cref="AdGroupFeedName"/> with pattern /// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c>. /// </returns> public static string FormatCustomerAdGroupFeed(string customerId, string adGroupId, string feedId) => s_customerAdGroupFeed.Expand(gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), $"{(gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)))}~{(gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId)))}"); /// <summary>Parses the given resource name string into a new <see cref="AdGroupFeedName"/> instance.</summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c></description></item> /// </list> /// </remarks> /// <param name="adGroupFeedName">The resource name in string form. Must not be <c>null</c>.</param> /// <returns>The parsed <see cref="AdGroupFeedName"/> if successful.</returns> public static AdGroupFeedName Parse(string adGroupFeedName) => Parse(adGroupFeedName, false); /// <summary> /// Parses the given resource name string into a new <see cref="AdGroupFeedName"/> instance; optionally allowing /// an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupFeedName">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="AdGroupFeedName"/> if successful.</returns> public static AdGroupFeedName Parse(string adGroupFeedName, bool allowUnparsed) => TryParse(adGroupFeedName, allowUnparsed, out AdGroupFeedName 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="AdGroupFeedName"/> instance. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c></description></item> /// </list> /// </remarks> /// <param name="adGroupFeedName">The resource name in string form. Must not be <c>null</c>.</param> /// <param name="result"> /// When this method returns, the parsed <see cref="AdGroupFeedName"/>, 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 adGroupFeedName, out AdGroupFeedName result) => TryParse(adGroupFeedName, false, out result); /// <summary> /// Tries to parse the given resource name string into a new <see cref="AdGroupFeedName"/> instance; optionally /// allowing an unparseable resource name. /// </summary> /// <remarks> /// To parse successfully, the resource name must be formatted as one of the following: /// <list type="bullet"> /// <item><description><c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c></description></item> /// </list> /// Or may be in any format if <paramref name="allowUnparsed"/> is <c>true</c>. /// </remarks> /// <param name="adGroupFeedName">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="AdGroupFeedName"/>, 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 adGroupFeedName, bool allowUnparsed, out AdGroupFeedName result) { gax::GaxPreconditions.CheckNotNull(adGroupFeedName, nameof(adGroupFeedName)); gax::TemplatedResourceName resourceName; if (s_customerAdGroupFeed.TryParseName(adGroupFeedName, out resourceName)) { string[] split1 = ParseSplitHelper(resourceName[1], new char[] { '~', }); if (split1 == null) { result = null; return false; } result = FromCustomerAdGroupFeed(resourceName[0], split1[0], split1[1]); return true; } if (allowUnparsed) { if (gax::UnparsedResourceName.TryParse(adGroupFeedName, out gax::UnparsedResourceName unparsedResourceName)) { result = FromUnparsed(unparsedResourceName); return true; } } result = null; return false; } private static string[] ParseSplitHelper(string s, char[] separators) { string[] result = new string[separators.Length + 1]; int i0 = 0; for (int i = 0; i <= separators.Length; i++) { int i1 = i < separators.Length ? s.IndexOf(separators[i], i0) : s.Length; if (i1 < 0 || i1 == i0) { return null; } result[i] = s.Substring(i0, i1 - i0); i0 = i1 + 1; } return result; } private AdGroupFeedName(ResourceNameType type, gax::UnparsedResourceName unparsedResourceName = null, string adGroupId = null, string customerId = null, string feedId = null) { Type = type; UnparsedResource = unparsedResourceName; AdGroupId = adGroupId; CustomerId = customerId; FeedId = feedId; } /// <summary> /// Constructs a new instance of a <see cref="AdGroupFeedName"/> class from the component parts of pattern /// <c>customers/{customer_id}/adGroupFeeds/{ad_group_id}~{feed_id}</c> /// </summary> /// <param name="customerId">The <c>Customer</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="adGroupId">The <c>AdGroup</c> ID. Must not be <c>null</c> or empty.</param> /// <param name="feedId">The <c>Feed</c> ID. Must not be <c>null</c> or empty.</param> public AdGroupFeedName(string customerId, string adGroupId, string feedId) : this(ResourceNameType.CustomerAdGroupFeed, customerId: gax::GaxPreconditions.CheckNotNullOrEmpty(customerId, nameof(customerId)), adGroupId: gax::GaxPreconditions.CheckNotNullOrEmpty(adGroupId, nameof(adGroupId)), feedId: gax::GaxPreconditions.CheckNotNullOrEmpty(feedId, nameof(feedId))) { } /// <summary>The <see cref="ResourceNameType"/> of the contained resource name.</summary> public ResourceNameType Type { get; } /// <summary> /// The contained <see cref="gax::UnparsedResourceName"/>. Only non-<c>null</c> if this instance contains an /// unparsed resource name. /// </summary> public gax::UnparsedResourceName UnparsedResource { get; } /// <summary> /// The <c>AdGroup</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string AdGroupId { get; } /// <summary> /// The <c>Customer</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string CustomerId { get; } /// <summary> /// The <c>Feed</c> ID. Will not be <c>null</c>, unless this instance contains an unparsed resource name. /// </summary> public string FeedId { 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.CustomerAdGroupFeed: return s_customerAdGroupFeed.Expand(CustomerId, $"{AdGroupId}~{FeedId}"); 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 AdGroupFeedName); /// <inheritdoc/> public bool Equals(AdGroupFeedName other) => ToString() == other?.ToString(); /// <inheritdoc/> public static bool operator ==(AdGroupFeedName a, AdGroupFeedName b) => ReferenceEquals(a, b) || (a?.Equals(b) ?? false); /// <inheritdoc/> public static bool operator !=(AdGroupFeedName a, AdGroupFeedName b) => !(a == b); } public partial class AdGroupFeed { /// <summary> /// <see cref="AdGroupFeedName"/>-typed view over the <see cref="ResourceName"/> resource name property. /// </summary> internal AdGroupFeedName ResourceNameAsAdGroupFeedName { get => string.IsNullOrEmpty(ResourceName) ? null : AdGroupFeedName.Parse(ResourceName, allowUnparsed: true); set => ResourceName = value?.ToString() ?? ""; } /// <summary><see cref="FeedName"/>-typed view over the <see cref="Feed"/> resource name property.</summary> internal FeedName FeedAsFeedName { get => string.IsNullOrEmpty(Feed) ? null : FeedName.Parse(Feed, allowUnparsed: true); set => Feed = value?.ToString() ?? ""; } /// <summary> /// <see cref="AdGroupName"/>-typed view over the <see cref="AdGroup"/> resource name property. /// </summary> internal AdGroupName AdGroupAsAdGroupName { get => string.IsNullOrEmpty(AdGroup) ? null : AdGroupName.Parse(AdGroup, allowUnparsed: true); set => AdGroup = value?.ToString() ?? ""; } } }
// // 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.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.Azure.Management.ApiManagement; using Microsoft.Azure.Management.ApiManagement.SmapiModels; using Newtonsoft.Json.Linq; namespace Microsoft.Azure.Management.ApiManagement { /// <summary> /// Operations for managing Identity Providers. /// </summary> internal partial class IdentityProviderOperations : IServiceOperations<ApiManagementClient>, IIdentityProviderOperations { /// <summary> /// Initializes a new instance of the IdentityProviderOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal IdentityProviderOperations(ApiManagementClient client) { this._client = client; } private ApiManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.Azure.Management.ApiManagement.ApiManagementClient. /// </summary> public ApiManagementClient Client { get { return this._client; } } /// <summary> /// Creates new or update existing identity provider configuration. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='identityProviderName'> /// Required. Identifier of the identity provider. /// </param> /// <param name='parameters'> /// Required. Create parameters. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> CreateAsync(string resourceGroupName, string serviceName, string identityProviderName, IdentityProviderCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (identityProviderName == null) { throw new ArgumentNullException("identityProviderName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ClientId == null) { throw new ArgumentNullException("parameters.ClientId"); } if (parameters.ClientSecret == null) { throw new ArgumentNullException("parameters.ClientSecret"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("identityProviderName", identityProviderName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/identityProviders/"; url = url + Uri.EscapeDataString(identityProviderName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject identityProviderCreateParametersValue = new JObject(); requestDoc = identityProviderCreateParametersValue; identityProviderCreateParametersValue["clientId"] = parameters.ClientId; identityProviderCreateParametersValue["clientSecret"] = parameters.ClientSecret; if (parameters.AllowedTenants != null) { if (parameters.AllowedTenants is ILazyCollection == false || ((ILazyCollection)parameters.AllowedTenants).IsInitialized) { JArray allowedTenantsArray = new JArray(); foreach (string allowedTenantsItem in parameters.AllowedTenants) { allowedTenantsArray.Add(allowedTenantsItem); } identityProviderCreateParametersValue["allowedTenants"] = allowedTenantsArray; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Created && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes specific identity provider configuration. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='identityProviderName'> /// Required. Identifier of the identity provider. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> DeleteAsync(string resourceGroupName, string serviceName, string identityProviderName, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (identityProviderName == null) { throw new ArgumentNullException("identityProviderName"); } if (etag == null) { throw new ArgumentNullException("etag"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("identityProviderName", identityProviderName); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/identityProviders/"; url = url + Uri.EscapeDataString(identityProviderName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Gets specific identity provider. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='identityProviderName'> /// Required. Identifier of the identity provider. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// Get Identity Provider operation response details. /// </returns> public async Task<IdentityProviderGetResponse> GetAsync(string resourceGroupName, string serviceName, string identityProviderName, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (identityProviderName == null) { throw new ArgumentNullException("identityProviderName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("identityProviderName", identityProviderName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/identityProviders/"; url = url + Uri.EscapeDataString(identityProviderName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result IdentityProviderGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new IdentityProviderGetResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { IdentityProviderContract valueInstance = new IdentityProviderContract(); result.Value = valueInstance; JToken typeValue = responseDoc["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { IdentityProviderTypeContract typeInstance = ApiManagementClient.ParseIdentityProviderTypeContract(((string)typeValue)); valueInstance.Type = typeInstance; } JToken clientIdValue = responseDoc["clientId"]; if (clientIdValue != null && clientIdValue.Type != JTokenType.Null) { string clientIdInstance = ((string)clientIdValue); valueInstance.ClientId = clientIdInstance; } JToken clientSecretValue = responseDoc["clientSecret"]; if (clientSecretValue != null && clientSecretValue.Type != JTokenType.Null) { string clientSecretInstance = ((string)clientSecretValue); valueInstance.ClientSecret = clientSecretInstance; } JToken allowedTenantsArray = responseDoc["allowedTenants"]; if (allowedTenantsArray != null && allowedTenantsArray.Type != JTokenType.Null) { foreach (JToken allowedTenantsValue in ((JArray)allowedTenantsArray)) { valueInstance.AllowedTenants.Add(((string)allowedTenantsValue)); } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='query'> /// Optional. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// List IdentityProvider operation response details. /// </returns> public async Task<IdentityProviderListResponse> ListAsync(string resourceGroupName, string serviceName, QueryParameters query, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("query", query); TracingAdapter.Enter(invocationId, this, "ListAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/identityProviders"; List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); List<string> odataFilter = new List<string>(); if (query != null && query.Filter != null) { odataFilter.Add(Uri.EscapeDataString(query.Filter)); } if (odataFilter.Count > 0) { queryParameters.Add("$filter=" + string.Join(null, odataFilter)); } if (query != null && query.Top != null) { queryParameters.Add("$top=" + Uri.EscapeDataString(query.Top.Value.ToString())); } if (query != null && query.Skip != null) { queryParameters.Add("$skip=" + Uri.EscapeDataString(query.Skip.Value.ToString())); } if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result IdentityProviderListResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new IdentityProviderListResponse(); JToken responseDoc = null; if (string.IsNullOrEmpty(responseContent) == false) { responseDoc = JToken.Parse(responseContent); } if (responseDoc != null && responseDoc.Type != JTokenType.Null) { JToken resultArray = responseDoc; if (resultArray != null && resultArray.Type != JTokenType.Null) { foreach (JToken resultValue in ((JArray)resultArray)) { IdentityProviderContract identityProviderContractInstance = new IdentityProviderContract(); result.Result.Add(identityProviderContractInstance); JToken typeValue = resultValue["type"]; if (typeValue != null && typeValue.Type != JTokenType.Null) { IdentityProviderTypeContract typeInstance = ApiManagementClient.ParseIdentityProviderTypeContract(((string)typeValue)); identityProviderContractInstance.Type = typeInstance; } JToken clientIdValue = resultValue["clientId"]; if (clientIdValue != null && clientIdValue.Type != JTokenType.Null) { string clientIdInstance = ((string)clientIdValue); identityProviderContractInstance.ClientId = clientIdInstance; } JToken clientSecretValue = resultValue["clientSecret"]; if (clientSecretValue != null && clientSecretValue.Type != JTokenType.Null) { string clientSecretInstance = ((string)clientSecretValue); identityProviderContractInstance.ClientSecret = clientSecretInstance; } JToken allowedTenantsArray = resultValue["allowedTenants"]; if (allowedTenantsArray != null && allowedTenantsArray.Type != JTokenType.Null) { foreach (JToken allowedTenantsValue in ((JArray)allowedTenantsArray)) { identityProviderContractInstance.AllowedTenants.Add(((string)allowedTenantsValue)); } } } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Patches specific identity provider. /// </summary> /// <param name='resourceGroupName'> /// Required. The name of the resource group. /// </param> /// <param name='serviceName'> /// Required. The name of the Api Management service. /// </param> /// <param name='identityProviderName'> /// Required. Identifier of the identity provider. /// </param> /// <param name='parameters'> /// Required. Update parameters. /// </param> /// <param name='etag'> /// Required. ETag. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> UpdateAsync(string resourceGroupName, string serviceName, string identityProviderName, IdentityProviderUpdateParameters parameters, string etag, CancellationToken cancellationToken) { // Validate if (resourceGroupName == null) { throw new ArgumentNullException("resourceGroupName"); } if (serviceName == null) { throw new ArgumentNullException("serviceName"); } if (identityProviderName == null) { throw new ArgumentNullException("identityProviderName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (etag == null) { throw new ArgumentNullException("etag"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("serviceName", serviceName); tracingParameters.Add("identityProviderName", identityProviderName); tracingParameters.Add("parameters", parameters); tracingParameters.Add("etag", etag); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } // Construct URL string url = ""; url = url + "/subscriptions/"; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/resourceGroups/"; url = url + Uri.EscapeDataString(resourceGroupName); url = url + "/providers/"; url = url + "Microsoft.ApiManagement"; url = url + "/service/"; url = url + Uri.EscapeDataString(serviceName); url = url + "/identityProviders/"; url = url + Uri.EscapeDataString(identityProviderName); List<string> queryParameters = new List<string>(); queryParameters.Add("api-version=2016-10-10"); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = new HttpMethod("PATCH"); httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", etag); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; JToken requestDoc = null; JObject identityProviderUpdateParametersValue = new JObject(); requestDoc = identityProviderUpdateParametersValue; if (parameters.ClientId != null) { identityProviderUpdateParametersValue["clientId"] = parameters.ClientId; } if (parameters.ClientSecret != null) { identityProviderUpdateParametersValue["clientSecret"] = parameters.ClientSecret; } if (parameters.AllowedTenants != null) { if (parameters.AllowedTenants is ILazyCollection == false || ((ILazyCollection)parameters.AllowedTenants).IsInitialized) { JArray allowedTenantsArray = new JArray(); foreach (string allowedTenantsItem in parameters.AllowedTenants) { allowedTenantsArray.Add(allowedTenantsItem); } identityProviderUpdateParametersValue["allowedTenants"] = allowedTenantsArray; } } requestContent = requestDoc.ToString(Newtonsoft.Json.Formatting.Indented); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/json"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK && statusCode != HttpStatusCode.NoContent) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } } }
/* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ namespace Apache.Ignite.Core.Impl.Binary { using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Runtime.CompilerServices; using System.Text; using Apache.Ignite.Core.Binary; using Apache.Ignite.Core.Common; using Apache.Ignite.Core.Impl.Binary.IO; using Apache.Ignite.Core.Impl.Common; /// <summary> /// Binary object. /// </summary> internal class BinaryObject : IBinaryObject { /** Cache empty dictionary. */ private static readonly IDictionary<int, int> EmptyFields = new Dictionary<int, int>(); /** Marshaller. */ private readonly Marshaller _marsh; /** Raw data of this binary object. */ private readonly byte[] _data; /** Offset in data array. */ private readonly int _offset; /** Header. */ private readonly BinaryObjectHeader _header; /** Fields. */ private volatile IDictionary<int, int> _fields; /** Deserialized value. */ private object _deserialized; /// <summary> /// Initializes a new instance of the <see cref="BinaryObject" /> class. /// </summary> /// <param name="marsh">Marshaller.</param> /// <param name="data">Raw data of this binary object.</param> /// <param name="offset">Offset in data array.</param> /// <param name="header">The header.</param> public BinaryObject(Marshaller marsh, byte[] data, int offset, BinaryObjectHeader header) { Debug.Assert(marsh != null); Debug.Assert(data != null); Debug.Assert(offset >= 0 && offset < data.Length); _marsh = marsh; _data = data; _offset = offset; _header = header; } /** <inheritdoc /> */ public int TypeId { get { return _header.TypeId; } } /** <inheritdoc /> */ public T GetField<T>(string fieldName) { IgniteArgumentCheck.NotNullOrEmpty(fieldName, "fieldName"); int pos; return TryGetFieldPosition(fieldName, out pos) ? GetField<T>(pos, null) : default(T); } /** <inheritdoc /> */ public bool HasField(string fieldName) { IgniteArgumentCheck.NotNullOrEmpty(fieldName, "fieldName"); int pos; return TryGetFieldPosition(fieldName, out pos); } /// <summary> /// Gets field value on the given object. /// </summary> /// <param name="pos">Position.</param> /// <param name="builder">Builder.</param> /// <returns>Field value.</returns> public T GetField<T>(int pos, BinaryObjectBuilder builder) { using (IBinaryStream stream = new BinaryHeapStream(_data)) { stream.Seek(pos + _offset, SeekOrigin.Begin); return _marsh.Unmarshal<T>(stream, BinaryMode.ForceBinary, builder); } } /** <inheritdoc /> */ public T Deserialize<T>() { return Deserialize<T>(BinaryMode.Deserialize); } /** <inheritdoc /> */ [ExcludeFromCodeCoverage] public int EnumValue { get { throw new NotSupportedException("IBinaryObject.Value is only supported for enums. " + "Check IBinaryObject.IsEnum property before accessing Value."); } } /** <inheritdoc /> */ public IBinaryObjectBuilder ToBuilder() { return _marsh.Ignite.GetBinary().GetBuilder(this); } /// <summary> /// Internal deserialization routine. /// </summary> /// <param name="mode">The mode.</param> /// <returns> /// Deserialized object. /// </returns> private T Deserialize<T>(BinaryMode mode) { if (_deserialized == null) { T res; using (IBinaryStream stream = new BinaryHeapStream(_data)) { stream.Seek(_offset, SeekOrigin.Begin); res = _marsh.Unmarshal<T>(stream, mode); } var desc = _marsh.GetDescriptor(true, _header.TypeId); if (!desc.KeepDeserialized) return res; _deserialized = res; } return (T)_deserialized; } /** <inheritdoc /> */ public IBinaryType GetBinaryType() { return _marsh.GetBinaryType(_header.TypeId); } /// <summary> /// Raw data of this binary object. /// </summary> public byte[] Data { get { return _data; } } /// <summary> /// Offset in data array. /// </summary> public int Offset { get { return _offset; } } /// <summary> /// Gets the header. /// </summary> public BinaryObjectHeader Header { get { return _header; } } public bool TryGetFieldPosition(string fieldName, out int pos) { var desc = _marsh.GetDescriptor(true, _header.TypeId); InitializeFields(desc); int fieldId = BinaryUtils.FieldId(_header.TypeId, fieldName, desc.NameMapper, desc.IdMapper); return _fields.TryGetValue(fieldId, out pos); } /// <summary> /// Lazy fields initialization routine. /// </summary> private void InitializeFields(IBinaryTypeDescriptor desc = null) { if (_fields != null) return; desc = desc ?? _marsh.GetDescriptor(true, _header.TypeId); using (var stream = new BinaryHeapStream(_data)) { var hdr = BinaryObjectHeader.Read(stream, _offset); _fields = BinaryObjectSchemaSerializer.ReadSchema(stream, _offset, hdr, desc.Schema,_marsh) .ToDictionary() ?? EmptyFields; } } /** <inheritdoc /> */ public override int GetHashCode() { return _header.HashCode; } /** <inheritdoc /> */ public override bool Equals(object obj) { if (this == obj) return true; BinaryObject that = obj as BinaryObject; if (that == null) return false; if (_data == that._data && _offset == that._offset) return true; if (TypeId != that.TypeId) return false; var desc = _marsh.GetDescriptor(true, TypeId); return BinaryUtils.GetEqualityComparer(desc).Equals(this, that); } /** <inheritdoc /> */ public override string ToString() { return ToString(new Dictionary<int, int>()); } /// <summary> /// ToString implementation. /// </summary> /// <param name="handled">Already handled objects.</param> /// <returns>Object string.</returns> private string ToString(IDictionary<int, int> handled) { int idHash; bool alreadyHandled = handled.TryGetValue(_offset, out idHash); if (!alreadyHandled) idHash = RuntimeHelpers.GetHashCode(this); StringBuilder sb; IBinaryTypeDescriptor desc = _marsh.GetDescriptor(true, _header.TypeId); IBinaryType meta; try { meta = _marsh.GetBinaryType(_header.TypeId); } catch (IgniteException) { meta = null; } if (meta == null) sb = new StringBuilder("BinaryObject [typeId=").Append(_header.TypeId).Append(", idHash=" + idHash); else { sb = new StringBuilder(meta.TypeName).Append(" [idHash=" + idHash); if (!alreadyHandled) { handled[_offset] = idHash; InitializeFields(); foreach (string fieldName in meta.Fields) { sb.Append(", "); int fieldId = BinaryUtils.FieldId(_header.TypeId, fieldName, desc.NameMapper, desc.IdMapper); int fieldPos; if (_fields.TryGetValue(fieldId, out fieldPos)) { sb.Append(fieldName).Append('='); ToString0(sb, GetField<object>(fieldPos, null), handled); } } } else sb.Append(", ..."); } sb.Append(']'); return sb.ToString(); } /// <summary> /// Internal ToString routine with correct collections printout. /// </summary> /// <param name="sb">String builder.</param> /// <param name="obj">Object to print.</param> /// <param name="handled">Already handled objects.</param> /// <returns>The same string builder.</returns> private static void ToString0(StringBuilder sb, object obj, IDictionary<int, int> handled) { IEnumerable col = (obj is string) ? null : obj as IEnumerable; if (col == null) { BinaryObject obj0 = obj as BinaryObject; sb.Append(obj0 == null ? obj : obj0.ToString(handled)); } else { sb.Append('['); bool first = true; foreach (object elem in col) { if (first) first = false; else sb.Append(", "); ToString0(sb, elem, handled); } sb.Append(']'); } } } }
using System; using System.Collections; using System.Text; namespace Pantry.Actions { class Rotate90X : IAction { public bool CanAct(ActionContext ac, object o) { return Algorithms.TransformGeometry.CanApply(o); } public string Name() { return "Rotate90X"; } public void Act(ActionContext Context, object o) { xmljr.math.Matrix4x4 M = new xmljr.math.Matrix4x4(); M.Data[ 0] = 1; M.Data[ 1] = 0; M.Data[ 2] = 0; M.Data[ 3] = 0; M.Data[ 4] = 0; M.Data[ 5] = 0; M.Data[ 6] = 1; M.Data[ 7] = 0; M.Data[ 8] = 0; M.Data[ 9] = -1; M.Data[10] = 0; M.Data[11] = 0; M.Data[12] = 0; M.Data[13] = 0; M.Data[14] = 0; M.Data[15] = 1; Algorithms.TransformGeometry.ApplyMatrix(o, M); } } class Rotate90Y : IAction { public bool CanAct(ActionContext ac, object o) { return Algorithms.TransformGeometry.CanApply(o); } public string Name() { return "Rotate90Y"; } public void Act(ActionContext Context, object o) { xmljr.math.Matrix4x4 M = new xmljr.math.Matrix4x4(); M.Data[ 0] = 0; M.Data[ 1] = 0; M.Data[ 2] = -1; M.Data[ 3] = 0; M.Data[ 4] = 0; M.Data[ 5] = 1; M.Data[ 6] = 0; M.Data[ 7] = 0; M.Data[ 8] = 1; M.Data[ 9] = 0; M.Data[10] = 0; M.Data[11] = 0; M.Data[12] = 0; M.Data[13] = 0; M.Data[14] = 0; M.Data[15] = 1; Algorithms.TransformGeometry.ApplyMatrix(o, M); } } class Rotate90Z : IAction { public bool CanAct(ActionContext ac, object o) { return Algorithms.TransformGeometry.CanApply(o); } public string Name() { return "Rotate90Z"; } public void Act(ActionContext Context, object o) { xmljr.math.Matrix4x4 M = new xmljr.math.Matrix4x4(); M.Data[ 0] = 0; M.Data[ 1] = 1; M.Data[ 2] = 0; M.Data[ 3] = 0; M.Data[ 4] = -1; M.Data[ 5] = 0; M.Data[ 6] = 0; M.Data[ 7] = 0; M.Data[ 8] = 0; M.Data[ 9] = 0; M.Data[10] = 1; M.Data[11] = 0; M.Data[12] = 0; M.Data[13] = 0; M.Data[14] = 0; M.Data[15] = 1; Algorithms.TransformGeometry.ApplyMatrix(o, M); } } class ChangeHands : IAction { public bool CanAct(ActionContext ac, object o) { return Algorithms.TransformGeometry.CanApply(o); } public string Name() { return "ChangeHands"; } public void Act(ActionContext Context, object o) { xmljr.math.Matrix4x4 M = new xmljr.math.Matrix4x4(); M.Data[ 0] = -1; M.Data[ 1] = 0; M.Data[ 2] = 0; M.Data[ 3] = 0; M.Data[ 4] = 0; M.Data[ 5] = -1; M.Data[ 6] = 0; M.Data[ 7] = 0; M.Data[ 8] = 0; M.Data[ 9] = 0; M.Data[10] = -1; M.Data[11] = 0; M.Data[12] = 0; M.Data[13] = 0; M.Data[14] = 0; M.Data[15] = 1; Algorithms.TransformGeometry.ApplyMatrix(o, M); } } class Centerize : IAction { public bool CanAct(ActionContext ac, object o) { return Algorithms.TransformGeometry.CanApply(o); } public string Name() { return "Centerize"; } public void Act(ActionContext Context, object o) { ArrayList L = Algorithms.PointPerspective.View(o); double maxX = -1000000; double maxY = -1000000; double maxZ = -1000000; double minX = 1000000; double minY = 1000000; double minZ = 1000000; foreach (xmljr.math.Vector3 V in L) { maxX = Math.Max(V.x, maxX); maxY = Math.Max(V.y, maxY); maxZ = Math.Max(V.z, maxZ); minX = Math.Min(V.x, minX); minY = Math.Min(V.y, minY); minZ = Math.Min(V.z, minZ); } Algorithms.TransformGeometry.Translate(o, (float)(-(maxX + minX) / 2.0), (float)(-(maxY + minY) / 2.0), (float)(-(maxZ + minZ) / 2.0)); } } class SmashYeq0 : IAction { public bool CanAct(ActionContext ac, object o) { return Algorithms.TransformGeometry.CanApply(o); } public string Name() { return "SmashYeq0"; } public void Act(ActionContext Context, object o) { ArrayList L = Algorithms.PointPerspective.View(o); double minY = 1000000; foreach (xmljr.math.Vector3 V in L) { minY = Math.Min(V.y, minY); } Algorithms.TransformGeometry.Translate(o, 0, (float)(-minY), 0); } } class ApplyOp : IAction { public bool CanAct(ActionContext ac, object o) { return Algorithms.TransformGeometry.CanApply(o); } public string Name() { return "ApplyOp"; } public void Act(ActionContext Context, object o) { Algorithms.TransformGeometry.TranslateAndUniformScale(o, (float)Context.TranslateX, (float)Context.TranslateY, (float)Context.TranslateZ, (float)Context.Scale); Context.InvalidateOp = true; } } class CenterGrid : IAction { public bool CanAct(ActionContext ac, object o) { return Algorithms.TransformGeometry.CanApply(o); } public string Name() { return "CenterGrid"; } public void Act(ActionContext Context, object o) { Algorithms.TransformGeometry.Translate(o,Context.GridH/2.0f,0,Context.GridH/2.0f); Context.InvalidateOp = true; } } class FlipNormals : IAction { public bool CanAct(ActionContext ac, object o) { return Algorithms.TransformGeometry.CanApply(o); } public string Name() { return "FlipNormals"; } public void Act(ActionContext Context, object o) { Algorithms.TransformGeometry.FlipNormals(o); Context.InvalidateOp = true; } } }
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Net.Http; using System.Net.Http.Headers; using System.Web.Http; using System.Web.Http.Controllers; using System.Web.Http.Description; using DisasterRecoveryAPI.Areas.HelpPage.ModelDescriptions; using DisasterRecoveryAPI.Areas.HelpPage.Models; namespace DisasterRecoveryAPI.Areas.HelpPage { public static class HelpPageConfigurationExtensions { private const string ApiModelPrefix = "MS_HelpPageApiModel_"; /// <summary> /// Sets the documentation provider for help page. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="documentationProvider">The documentation provider.</param> public static void SetDocumentationProvider(this HttpConfiguration config, IDocumentationProvider documentationProvider) { config.Services.Replace(typeof(IDocumentationProvider), documentationProvider); } /// <summary> /// Sets the objects that will be used by the formatters to produce sample requests/responses. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleObjects">The sample objects.</param> public static void SetSampleObjects(this HttpConfiguration config, IDictionary<Type, object> sampleObjects) { config.GetHelpPageSampleGenerator().SampleObjects = sampleObjects; } /// <summary> /// Sets the sample request directly for the specified media type and action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample request directly for the specified media type and action with parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample request.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleRequest(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Request, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample request directly for the specified media type of the action. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, new[] { "*" }), sample); } /// <summary> /// Sets the sample response directly for the specified media type of the action with specific parameters. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample response.</param> /// <param name="mediaType">The media type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetSampleResponse(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, SampleDirection.Response, controllerName, actionName, parameterNames), sample); } /// <summary> /// Sets the sample directly for all actions with the specified media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> public static void SetSampleForMediaType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType), sample); } /// <summary> /// Sets the sample directly for all actions with the specified type and media type. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sample">The sample.</param> /// <param name="mediaType">The media type.</param> /// <param name="type">The parameter type or return type of an action.</param> public static void SetSampleForType(this HttpConfiguration config, object sample, MediaTypeHeaderValue mediaType, Type type) { config.GetHelpPageSampleGenerator().ActionSamples.Add(new HelpPageSampleKey(mediaType, type), sample); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> passed to the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate request samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualRequestType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Request, controllerName, actionName, parameterNames), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, new[] { "*" }), type); } /// <summary> /// Specifies the actual type of <see cref="System.Net.Http.ObjectContent{T}"/> returned as part of the <see cref="System.Net.Http.HttpRequestMessage"/> in an action. /// The help page will use this information to produce more accurate response samples. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="type">The type.</param> /// <param name="controllerName">Name of the controller.</param> /// <param name="actionName">Name of the action.</param> /// <param name="parameterNames">The parameter names.</param> public static void SetActualResponseType(this HttpConfiguration config, Type type, string controllerName, string actionName, params string[] parameterNames) { config.GetHelpPageSampleGenerator().ActualHttpMessageTypes.Add(new HelpPageSampleKey(SampleDirection.Response, controllerName, actionName, parameterNames), type); } /// <summary> /// Gets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <returns>The help page sample generator.</returns> public static HelpPageSampleGenerator GetHelpPageSampleGenerator(this HttpConfiguration config) { return (HelpPageSampleGenerator)config.Properties.GetOrAdd( typeof(HelpPageSampleGenerator), k => new HelpPageSampleGenerator()); } /// <summary> /// Sets the help page sample generator. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="sampleGenerator">The help page sample generator.</param> public static void SetHelpPageSampleGenerator(this HttpConfiguration config, HelpPageSampleGenerator sampleGenerator) { config.Properties.AddOrUpdate( typeof(HelpPageSampleGenerator), k => sampleGenerator, (k, o) => sampleGenerator); } /// <summary> /// Gets the model description generator. /// </summary> /// <param name="config">The configuration.</param> /// <returns>The <see cref="ModelDescriptionGenerator"/></returns> public static ModelDescriptionGenerator GetModelDescriptionGenerator(this HttpConfiguration config) { return (ModelDescriptionGenerator)config.Properties.GetOrAdd( typeof(ModelDescriptionGenerator), k => InitializeModelDescriptionGenerator(config)); } /// <summary> /// Gets the model that represents an API displayed on the help page. The model is initialized on the first call and cached for subsequent calls. /// </summary> /// <param name="config">The <see cref="HttpConfiguration"/>.</param> /// <param name="apiDescriptionId">The <see cref="ApiDescription"/> ID.</param> /// <returns> /// An <see cref="HelpPageApiModel"/> /// </returns> public static HelpPageApiModel GetHelpPageApiModel(this HttpConfiguration config, string apiDescriptionId) { object model; string modelId = ApiModelPrefix + apiDescriptionId; if (!config.Properties.TryGetValue(modelId, out model)) { Collection<ApiDescription> apiDescriptions = config.Services.GetApiExplorer().ApiDescriptions; ApiDescription apiDescription = apiDescriptions.FirstOrDefault(api => String.Equals(api.GetFriendlyId(), apiDescriptionId, StringComparison.OrdinalIgnoreCase)); if (apiDescription != null) { model = GenerateApiModel(apiDescription, config); config.Properties.TryAdd(modelId, model); } } return (HelpPageApiModel)model; } private static HelpPageApiModel GenerateApiModel(ApiDescription apiDescription, HttpConfiguration config) { HelpPageApiModel apiModel = new HelpPageApiModel() { ApiDescription = apiDescription, }; ModelDescriptionGenerator modelGenerator = config.GetModelDescriptionGenerator(); HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); GenerateUriParameters(apiModel, modelGenerator); GenerateRequestModelDescription(apiModel, modelGenerator, sampleGenerator); GenerateResourceDescription(apiModel, modelGenerator); GenerateSamples(apiModel, sampleGenerator); return apiModel; } private static void GenerateUriParameters(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromUri) { HttpParameterDescriptor parameterDescriptor = apiParameter.ParameterDescriptor; Type parameterType = null; ModelDescription typeDescription = null; ComplexTypeModelDescription complexTypeDescription = null; if (parameterDescriptor != null) { parameterType = parameterDescriptor.ParameterType; typeDescription = modelGenerator.GetOrCreateModelDescription(parameterType); complexTypeDescription = typeDescription as ComplexTypeModelDescription; } // Example: // [TypeConverter(typeof(PointConverter))] // public class Point // { // public Point(int x, int y) // { // X = x; // Y = y; // } // public int X { get; set; } // public int Y { get; set; } // } // Class Point is bindable with a TypeConverter, so Point will be added to UriParameters collection. // // public class Point // { // public int X { get; set; } // public int Y { get; set; } // } // Regular complex class Point will have properties X and Y added to UriParameters collection. if (complexTypeDescription != null && !IsBindableWithTypeConverter(parameterType)) { foreach (ParameterDescription uriParameter in complexTypeDescription.Properties) { apiModel.UriParameters.Add(uriParameter); } } else if (parameterDescriptor != null) { ParameterDescription uriParameter = AddParameterDescription(apiModel, apiParameter, typeDescription); if (!parameterDescriptor.IsOptional) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Required" }); } object defaultValue = parameterDescriptor.DefaultValue; if (defaultValue != null) { uriParameter.Annotations.Add(new ParameterAnnotation() { Documentation = "Default value is " + Convert.ToString(defaultValue, CultureInfo.InvariantCulture) }); } } else { Debug.Assert(parameterDescriptor == null); // If parameterDescriptor is null, this is an undeclared route parameter which only occurs // when source is FromUri. Ignored in request model and among resource parameters but listed // as a simple string here. ModelDescription modelDescription = modelGenerator.GetOrCreateModelDescription(typeof(string)); AddParameterDescription(apiModel, apiParameter, modelDescription); } } } } private static bool IsBindableWithTypeConverter(Type parameterType) { if (parameterType == null) { return false; } return TypeDescriptor.GetConverter(parameterType).CanConvertFrom(typeof(string)); } private static ParameterDescription AddParameterDescription(HelpPageApiModel apiModel, ApiParameterDescription apiParameter, ModelDescription typeDescription) { ParameterDescription parameterDescription = new ParameterDescription { Name = apiParameter.Name, Documentation = apiParameter.Documentation, TypeDescription = typeDescription, }; apiModel.UriParameters.Add(parameterDescription); return parameterDescription; } private static void GenerateRequestModelDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator, HelpPageSampleGenerator sampleGenerator) { ApiDescription apiDescription = apiModel.ApiDescription; foreach (ApiParameterDescription apiParameter in apiDescription.ParameterDescriptions) { if (apiParameter.Source == ApiParameterSource.FromBody) { Type parameterType = apiParameter.ParameterDescriptor.ParameterType; apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); apiModel.RequestDocumentation = apiParameter.Documentation; } else if (apiParameter.ParameterDescriptor != null && apiParameter.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage)) { Type parameterType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); if (parameterType != null) { apiModel.RequestModelDescription = modelGenerator.GetOrCreateModelDescription(parameterType); } } } } private static void GenerateResourceDescription(HelpPageApiModel apiModel, ModelDescriptionGenerator modelGenerator) { ResponseDescription response = apiModel.ApiDescription.ResponseDescription; Type responseType = response.ResponseType ?? response.DeclaredType; if (responseType != null && responseType != typeof(void)) { apiModel.ResourceDescription = modelGenerator.GetOrCreateModelDescription(responseType); } } [SuppressMessage("Microsoft.Design", "CA1031:DoNotCatchGeneralExceptionTypes", Justification = "The exception is recorded as ErrorMessages.")] private static void GenerateSamples(HelpPageApiModel apiModel, HelpPageSampleGenerator sampleGenerator) { try { foreach (var item in sampleGenerator.GetSampleRequests(apiModel.ApiDescription)) { apiModel.SampleRequests.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } foreach (var item in sampleGenerator.GetSampleResponses(apiModel.ApiDescription)) { apiModel.SampleResponses.Add(item.Key, item.Value); LogInvalidSampleAsError(apiModel, item.Value); } } catch (Exception e) { apiModel.ErrorMessages.Add(String.Format(CultureInfo.CurrentCulture, "An exception has occurred while generating the sample. Exception message: {0}", HelpPageSampleGenerator.UnwrapException(e).Message)); } } private static bool TryGetResourceParameter(ApiDescription apiDescription, HttpConfiguration config, out ApiParameterDescription parameterDescription, out Type resourceType) { parameterDescription = apiDescription.ParameterDescriptions.FirstOrDefault( p => p.Source == ApiParameterSource.FromBody || (p.ParameterDescriptor != null && p.ParameterDescriptor.ParameterType == typeof(HttpRequestMessage))); if (parameterDescription == null) { resourceType = null; return false; } resourceType = parameterDescription.ParameterDescriptor.ParameterType; if (resourceType == typeof(HttpRequestMessage)) { HelpPageSampleGenerator sampleGenerator = config.GetHelpPageSampleGenerator(); resourceType = sampleGenerator.ResolveHttpRequestMessageType(apiDescription); } if (resourceType == null) { parameterDescription = null; return false; } return true; } private static ModelDescriptionGenerator InitializeModelDescriptionGenerator(HttpConfiguration config) { ModelDescriptionGenerator modelGenerator = new ModelDescriptionGenerator(config); Collection<ApiDescription> apis = config.Services.GetApiExplorer().ApiDescriptions; foreach (ApiDescription api in apis) { ApiParameterDescription parameterDescription; Type parameterType; if (TryGetResourceParameter(api, config, out parameterDescription, out parameterType)) { modelGenerator.GetOrCreateModelDescription(parameterType); } } return modelGenerator; } private static void LogInvalidSampleAsError(HelpPageApiModel apiModel, object sample) { InvalidSample invalidSample = sample as InvalidSample; if (invalidSample != null) { apiModel.ErrorMessages.Add(invalidSample.ErrorMessage); } } } }
//--------------------------------------------------------------------------- // // <copyright file=AdornerDecorator.cs company=Microsoft> // Copyright (C) Microsoft Corporation. All rights reserved. // </copyright> // // // Description: // AdornerDecorator class. // See spec at: http://avalon/uis/Specs/AdornerLayer%20Spec.htm // // History: // 1/29/2004 psarrett: Created // //--------------------------------------------------------------------------- using System; using System.Collections; using System.Windows; using System.Windows.Controls; using System.Windows.Media; using System.Windows.Threading; namespace System.Windows.Documents { /// <summary> /// This AdornerDecorator does not hookup its child in the logical tree. It's being /// used by PopupRoot and FixedDocument. /// </summary> internal class NonLogicalAdornerDecorator : AdornerDecorator { public override UIElement Child { get { return IntChild; } set { if (IntChild != value) { this.RemoveVisualChild(IntChild); this.RemoveVisualChild(AdornerLayer); IntChild = value; if(value != null) { this.AddVisualChild(value); this.AddVisualChild(AdornerLayer); } InvalidateMeasure(); } } } } /// <summary> /// Object which allows elements beneath it in the visual tree to be adorned. /// AdornerDecorator has two children. /// The first child is the parent of the rest of the visual tree below the AdornerDecorator. /// The second child is the AdornerLayer on which adorners are rendered. /// /// AdornerDecorator is intended to be used as part of an object's Style. /// </summary> public class AdornerDecorator : Decorator { //------------------------------------------------------ // // Constructors // //------------------------------------------------------ #region Constructors /// <summary> /// Constructor /// </summary> public AdornerDecorator() : base() { _adornerLayer = new AdornerLayer(); } #endregion Constructors //------------------------------------------------------ // // Public Methods // //------------------------------------------------------ //------------------------------------------------------ // // Public Properties // //------------------------------------------------------ #region Public Properties /// <summary> /// AdornerLayer on which adorners are rendered. /// </summary> public AdornerLayer AdornerLayer { get { return _adornerLayer; } } #endregion Public Properties //------------------------------------------------------ // // Protected Methods // //------------------------------------------------------ #region Protected Methods /// <summary> /// Measurement override. Implement your size-to-content logic here. /// </summary> /// <param name="constraint"> /// Sizing constraint. /// </param> protected override Size MeasureOverride(Size constraint) { Size desiredSize = base.MeasureOverride(constraint); if (VisualTreeHelper.GetParent(_adornerLayer) != null) { // We don't really care about the size of the AdornerLayer-- we'll // always just make the AdornerDecorator the full desiredSize. But // we need to measure it anyway, to make sure Adorners render. _adornerLayer.Measure(constraint); } return desiredSize; } /// <summary> /// Override for <seealso cref="FrameworkElement.ArrangeOverride" /> /// </summary> /// <param name="finalSize">The size reserved for this element by the parent</param> /// <returns>The actual ink area of the element, typically the same as finalSize</returns> protected override Size ArrangeOverride(Size finalSize) { Size inkSize = base.ArrangeOverride(finalSize); if (VisualTreeHelper.GetParent(_adornerLayer) != null) { _adornerLayer.Arrange(new Rect(finalSize)); } return (inkSize); } /// <summary> /// Gets or sets the child of the AdornerDecorator. /// </summary> public override UIElement Child { get { return base.Child; } set { Visual old = base.Child; if (old == value) { return; } if (value == null) { base.Child = null; RemoveVisualChild(_adornerLayer); } else { base.Child = value; if (null == old) { AddVisualChild(_adornerLayer); } } } } /// <summary> /// Returns the Visual children count. /// </summary> protected override int VisualChildrenCount { get { if (base.Child != null) { return 2; // One for the child and one for the adorner layer. } else { return 0; } } } /// <summary> /// Returns the child at the specified index. /// </summary> protected override Visual GetVisualChild(int index) { if (base.Child == null) { throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } else { switch (index) { case 0: return base.Child; case 1: return _adornerLayer; default: throw new ArgumentOutOfRangeException("index", index, SR.Get(SRID.Visual_ArgumentOutOfRange)); } } } #endregion Protected Methods //------------------------------------------------------ // // Private Members // //------------------------------------------------------ #region Private Members // // This property // 1. Finds the correct initial size for the _effectiveValues store on the current DependencyObject // 2. This is a performance optimization // internal override int EffectiveValuesInitialSize { get { return 6; } } readonly AdornerLayer _adornerLayer; #endregion Private Members } }
using System; using System.Collections.Generic; using System.Text; namespace gov.va.medora.mdo { public class Note { public IList<Author> Signers { get; set; } string id; string timestamp; string serviceCategory; string documentDefinitionId; string localTitle; string standardTitle; Author author = null; Author cosigner; HospitalLocation location; string text; SiteId siteId; bool fHasAddendum = false; bool fIsAddendum = false; string originalNoteID; bool fHasImages = false; string admitTimestamp; string dischargeTimestamp; Author approvedBy; string status; string consultId; string surgicalProcId; string prfId; string parentId; string procId; string procTimestamp; string subject; string _type; public Note() { } public string Type { get { return _type; } set { _type = value; } } public string Id { get { return id; } set { id = value; } } public string Timestamp { get { return timestamp; } set { timestamp = value; } } public string ServiceCategory { get { return serviceCategory; } set { serviceCategory = value; } } public string DocumentDefinitionId { get { return documentDefinitionId; } set { documentDefinitionId = value; } } public string LocalTitle { get { return localTitle; } set { localTitle = value; } } public string StandardTitle { get { return standardTitle; } set { standardTitle = value; } } public Author Author { get { return author; } set { author = value; } } public HospitalLocation Location { get { return location; } set { location = value; } } public string Text { get { return text; } set { text = value; } } public SiteId SiteId { get { return siteId; } set { siteId = value; } } public bool HasAddendum { get { return fHasAddendum; } set { fHasAddendum = value; } } public bool IsAddendum { get { return fIsAddendum; } set { fIsAddendum = value; } } public string OriginalNoteId { get { return originalNoteID; } set { originalNoteID = value; } } public bool HasImages { get { return fHasImages; } set { fHasImages = value; } } public string AdmitTimestamp { get { return admitTimestamp; } set { admitTimestamp = value; } } public string DischargeTimestamp { get { return dischargeTimestamp; } set { dischargeTimestamp = value; } } public Author ApprovedBy { get { return approvedBy; } set { approvedBy = value; } } public string Status { get { return status; } set { status = value; } } public string ConsultId { get { return consultId; } set { consultId = value; } } public string SurgicalProcId { get { return surgicalProcId; } set { surgicalProcId = value; } } public string PrfId { get { return prfId; } set { prfId = value; } } public Author Cosigner { get { return cosigner; } set { cosigner = value; } } public string ParentId { get { return parentId; } set { parentId = value; } } public string Subject { get { return subject; } set { subject = value; } } public string ProcId { get { return procId; } set { procId = value; } } public string ProcTimestamp { get { return procTimestamp; } set { procTimestamp = value; } } } }
using System; using System.Collections; using System.Collections.Generic; using System.Runtime.Serialization; using NUnit.Framework; using ServiceStack.Text.Json; #if !MONOTOUCH using ServiceStack.Common.Tests.Models; #endif namespace ServiceStack.Text.Tests.JsonTests { [TestFixture] public class BasicJsonTests : TestBase { public class JsonPrimitives { public int Int { get; set; } public long Long { get; set; } public float Float { get; set; } public double Double { get; set; } public bool Boolean { get; set; } public DateTime DateTime { get; set; } public string NullString { get; set; } public static JsonPrimitives Create(int i) { return new JsonPrimitives { Int = i, Long = i, Float = i, Double = i, Boolean = i % 2 == 0, DateTime = DateTimeExtensions.FromUnixTimeMs(1), }; } } public class NullableValueTypes { public int? Int { get; set; } public long? Long { get; set; } public decimal? Decimal { get; set; } public double? Double { get; set; } public bool? Boolean { get; set; } public DateTime? DateTime { get; set; } } [SetUp] public void Setup () { #if MONOTOUCH JsConfig.Reset(); JsConfig.RegisterTypeForAot<ExampleEnumWithoutFlagsAttribute>(); JsConfig.RegisterTypeForAot<ExampleEnum>(); #endif } [TearDown] public void TearDown() { JsConfig.Reset(); } [Test] public void Can_parse_json_with_nullable_valuetypes() { var json = "{}"; var item = JsonSerializer.DeserializeFromString<NullableValueTypes>(json); Assert.That(item.Int, Is.Null, "int"); Assert.That(item.Long, Is.Null, "long"); Assert.That(item.Decimal, Is.Null, "decimal"); Assert.That(item.Double, Is.Null, "double"); Assert.That(item.Boolean, Is.Null, "boolean"); Assert.That(item.DateTime, Is.Null, "datetime"); } [Test] public void Can_parse_json_with_nullable_valuetypes_that_has_included_null_values() { var json = "{\"Int\":null,\"Long\":null,\"Decimal\":null,\"Double\":null,\"Boolean\":null,\"DateTime\":null}"; var item = JsonSerializer.DeserializeFromString<NullableValueTypes>(json); Assert.That(item.Int, Is.Null, "int"); Assert.That(item.Long, Is.Null, "long"); Assert.That(item.Decimal, Is.Null, "decimal"); Assert.That(item.Double, Is.Null, "double"); Assert.That(item.Boolean, Is.Null, "boolean"); Assert.That(item.DateTime, Is.Null, "datetime"); } [Test] public void Can_parse_json_with_nulls_or_empty_string_in_nullables() { const string json = "{\"Int\":null,\"Boolean\":\"\"}"; var value = JsonSerializer.DeserializeFromString<NullableValueTypes>(json); Assert.That(value.Int, Is.EqualTo(null)); Assert.That(value.Boolean, Is.EqualTo(null)); } [Test] public void Can_parse_json_with_nullable_valuetypes_that_has_no_value_specified() { var json = "{\"Int\":,\"Long\":,\"Decimal\":,\"Double\":,\"Boolean\":,\"DateTime\":}"; var item = JsonSerializer.DeserializeFromString<NullableValueTypes>(json); Assert.That(item.Int, Is.Null, "int"); Assert.That(item.Long, Is.Null, "long"); Assert.That(item.Decimal, Is.Null, "decimal"); Assert.That(item.Double, Is.Null, "double"); Assert.That(item.Boolean, Is.Null, "boolean"); Assert.That(item.DateTime, Is.Null, "datetime"); } [Test] public void Can_handle_json_primitives() { var json = JsonSerializer.SerializeToString(JsonPrimitives.Create(1)); Log(json); Assert.That(json, Is.EqualTo( "{\"Int\":1,\"Long\":1,\"Float\":1,\"Double\":1,\"Boolean\":false,\"DateTime\":\"\\/Date(1)\\/\"}")); } [Test] public void Can_parse_json_with_nulls() { const string json = "{\"Int\":1,\"NullString\":null}"; var value = JsonSerializer.DeserializeFromString<JsonPrimitives>(json); Assert.That(value.Int, Is.EqualTo(1)); Assert.That(value.NullString, Is.Null); } [Test] public void Can_serialize_dictionary_of_int_int() { var json = JsonSerializer.SerializeToString<IntIntDictionary>(new IntIntDictionary() { Dictionary = { { 10, 100 }, { 20, 200 } } }); const string expected = "{\"Dictionary\":{\"10\":100,\"20\":200}}"; Assert.That(json, Is.EqualTo(expected)); } private class IntIntDictionary { public IntIntDictionary() { Dictionary = new Dictionary<int, int>(); } public IDictionary<int, int> Dictionary { get; set; } } [Test] public void Serialize_skips_null_values_by_default() { var o = new NullValueTester { Name = "Brandon", Type = "Programmer", SampleKey = 12, Nothing = (string)null, NullableDateTime = null }; var s = JsonSerializer.SerializeToString(o); Assert.That(s, Is.EqualTo("{\"Name\":\"Brandon\",\"Type\":\"Programmer\",\"SampleKey\":12}")); } [Test] public void Serialize_can_include_null_values() { var o = new NullValueTester { Name = "Brandon", Type = "Programmer", SampleKey = 12, Nothing = null, NullClass = null, NullableDateTime = null, }; JsConfig.IncludeNullValues = true; var s = JsonSerializer.SerializeToString(o); JsConfig.Reset(); Assert.That(s, Is.EqualTo("{\"Name\":\"Brandon\",\"Type\":\"Programmer\",\"SampleKey\":12,\"Nothing\":null,\"NullClass\":null,\"NullableDateTime\":null}")); } private class NullClass { } [Test] public void Deserialize_sets_null_values() { var s = "{\"Name\":\"Brandon\",\"Type\":\"Programmer\",\"SampleKey\":12,\"Nothing\":null}"; var o = JsonSerializer.DeserializeFromString<NullValueTester>(s); Assert.That(o.Name, Is.EqualTo("Brandon")); Assert.That(o.Type, Is.EqualTo("Programmer")); Assert.That(o.SampleKey, Is.EqualTo(12)); Assert.That(o.Nothing, Is.Null); } [Test] public void Deserialize_ignores_omitted_values() { var s = "{\"Type\":\"Programmer\",\"SampleKey\":2}"; var o = JsonSerializer.DeserializeFromString<NullValueTester>(s); Assert.That(o.Name, Is.EqualTo("Miguel")); Assert.That(o.Type, Is.EqualTo("Programmer")); Assert.That(o.SampleKey, Is.EqualTo(2)); Assert.That(o.Nothing, Is.EqualTo("zilch")); } private class NullValueTester { public string Name { get; set; } public string Type { get; set; } public int SampleKey { get; set; } public string Nothing { get; set; } public NullClass NullClass { get; set; } public DateTime? NullableDateTime { get; set; } public NullValueTester() { Name = "Miguel"; Type = "User"; SampleKey = 1; Nothing = "zilch"; NullableDateTime = new DateTime(2012, 01, 01); } } #if !MONOTOUCH [DataContract] class Person { [DataMember(Name = "MyID")] public int Id { get; set; } [DataMember] public string Name { get; set; } } [Test] public void Can_override_name() { var person = new Person { Id = 123, Name = "Abc" }; Assert.That(TypeSerializer.SerializeToString(person), Is.EqualTo("{MyID:123,Name:Abc}")); Assert.That(JsonSerializer.SerializeToString(person), Is.EqualTo("{\"MyID\":123,\"Name\":\"Abc\"}")); } #endif [Flags] public enum ExampleEnum : ulong { None = 0, One = 1, Two = 2, Four = 4, Eight = 8 } [Test] public void Can_serialize_unsigned_flags_enum() { var anon = new { EnumProp1 = ExampleEnum.One | ExampleEnum.Two, EnumProp2 = ExampleEnum.Eight, }; Assert.That(TypeSerializer.SerializeToString(anon), Is.EqualTo("{EnumProp1:3,EnumProp2:8}")); Assert.That(JsonSerializer.SerializeToString(anon), Is.EqualTo("{\"EnumProp1\":3,\"EnumProp2\":8}")); } public enum ExampleEnumWithoutFlagsAttribute : ulong { None = 0, One = 1, Two = 2 } public class ClassWithEnumWithoutFlagsAttribute { public ExampleEnumWithoutFlagsAttribute EnumProp1 { get; set; } public ExampleEnumWithoutFlagsAttribute EnumProp2 { get; set; } } [Test] public void Can_serialize_unsigned_enum_with_turned_on_TreatEnumAsInteger() { JsConfig.TreatEnumAsInteger = true; var anon = new ClassWithEnumWithoutFlagsAttribute { EnumProp1 = ExampleEnumWithoutFlagsAttribute.One, EnumProp2 = ExampleEnumWithoutFlagsAttribute.Two }; Assert.That(JsonSerializer.SerializeToString(anon), Is.EqualTo("{\"EnumProp1\":1,\"EnumProp2\":2}")); Assert.That(TypeSerializer.SerializeToString(anon), Is.EqualTo("{EnumProp1:1,EnumProp2:2}")); } [Test] public void Can_deserialize_unsigned_enum_with_turned_on_TreatEnumAsInteger() { JsConfig.TreatEnumAsInteger = true; var s = "{\"EnumProp1\":1,\"EnumProp2\":2}"; var o = JsonSerializer.DeserializeFromString<ClassWithEnumWithoutFlagsAttribute>(s); Assert.That(o.EnumProp1, Is.EqualTo(ExampleEnumWithoutFlagsAttribute.One)); Assert.That(o.EnumProp2, Is.EqualTo(ExampleEnumWithoutFlagsAttribute.Two)); } [Test] public void Can_serialize_object_array_with_nulls() { var objs = new[] { (object)"hello", (object)null }; JsConfig.IncludeNullValues = false; Assert.That(objs.ToJson(), Is.EqualTo("[\"hello\",null]")); } [Test] public void Should_return_null_instance_for_empty_json() { var o = JsonSerializer.DeserializeFromString("", typeof(JsonPrimitives)); Assert.IsNull(o); } [Test] public void Can_parse_empty_string_dictionary_with_leading_whitespace() { var serializer = new JsonSerializer<Dictionary<string, string>>(); Assert.That(serializer.DeserializeFromString(" {}"), Is.Empty); } [Test] public void Can_parse_nonempty_string_dictionary_with_leading_whitespace() { var serializer = new JsonSerializer<Dictionary<string, string>>(); var dictionary = serializer.DeserializeFromString(" {\"A\":\"N\",\"B\":\"O\"}"); Assert.That(dictionary.Count, Is.EqualTo(2)); Assert.That(dictionary["A"], Is.EqualTo("N")); Assert.That(dictionary["B"], Is.EqualTo("O")); } [Test] public void Can_parse_empty_dictionary_with_leading_whitespace() { var serializer = new JsonSerializer<Dictionary<int, double>>(); Assert.That(serializer.DeserializeFromString(" {}"), Is.Empty); } [Test] public void Can_parse_nonempty_dictionary_with_leading_whitespace() { var serializer = new JsonSerializer<Dictionary<int, double>>(); var dictionary = serializer.DeserializeFromString(" {\"1\":2.5,\"2\":5}"); Assert.That(dictionary.Count, Is.EqualTo(2)); Assert.That(dictionary[1], Is.EqualTo(2.5)); Assert.That(dictionary[2], Is.EqualTo(5.0)); } [Test] public void Can_parse_empty_hashtable_with_leading_whitespace() { var serializer = new JsonSerializer<Hashtable>(); Assert.That(serializer.DeserializeFromString(" {}"), Is.Empty); } [Test] public void Can_parse_nonempty_hashtable_with_leading_whitespace() { var serializer = new JsonSerializer<Hashtable>(); var hashtable = serializer.DeserializeFromString(" {\"A\":1,\"B\":2}"); Assert.That(hashtable.Count, Is.EqualTo(2)); Assert.That(hashtable["A"].ToString(), Is.EqualTo(1.ToString())); Assert.That(hashtable["B"].ToString(), Is.EqualTo(2.ToString())); } [Test] public void Can_parse_empty_json_object_with_leading_whitespace() { var serializer = new JsonSerializer<JsonObject>(); Assert.That(serializer.DeserializeFromString(" {}"), Is.Empty); } [Test] public void Can_parse_nonempty_json_object_with_leading_whitespace() { var serializer = new JsonSerializer<JsonObject>(); var jsonObject = serializer.DeserializeFromString(" {\"foo\":\"bar\"}"); Assert.That(jsonObject, Is.Not.Empty); Assert.That(jsonObject["foo"], Is.EqualTo("bar")); } [Test] public void Can_parse_empty_key_value_pair_with_leading_whitespace() { var serializer = new JsonSerializer<KeyValuePair<string, string>>(); Assert.That(serializer.DeserializeFromString(" {}"), Is.EqualTo(default(KeyValuePair<string, string>))); } [Test] public void Can_parse_nonempty_key_value_pair_with_leading_whitespace() { var serializer = new JsonSerializer<KeyValuePair<string, string>>(); var keyValuePair = serializer.DeserializeFromString(" {\"Key\":\"foo\"\"Value\":\"bar\"}"); Assert.That(keyValuePair, Is.EqualTo(new KeyValuePair<string, string>("foo", "bar"))); } [Test] public void Can_parse_empty_object_with_leading_whitespace() { var serializer = new JsonSerializer<Foo>(); var foo = serializer.DeserializeFromString(" {}"); Assert.That(foo, Is.Not.Null); Assert.That(foo.Bar, Is.Null); } [Test] public void Can_parse_nonempty_object_with_leading_whitespace() { var serializer = new JsonSerializer<Foo>(); var foo = serializer.DeserializeFromString(" {\"Bar\":\"baz\"}"); Assert.That(foo, Is.Not.Null); Assert.That(foo.Bar, Is.EqualTo("baz")); } public class Foo { public string Bar { get; set; } } } }
using System; using System.Windows.Forms; using System.Drawing; using System.Drawing.Drawing2D; using System.Collections; using System.Collections.Generic; using System.Security.Permissions; using System.Diagnostics.CodeAnalysis; namespace WeifenLuo.WinFormsUI.Docking { public abstract class DockPaneStripBase : Control { [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] protected internal class Tab : IDisposable { private IDockContent m_content; public Tab(IDockContent content) { m_content = content; } ~Tab() { Dispose(false); } public IDockContent Content { get { return m_content; } } public Form ContentForm { get { return m_content as Form; } } public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } } [SuppressMessage("Microsoft.Design", "CA1034:NestedTypesShouldNotBeVisible")] protected sealed class TabCollection : IEnumerable<Tab> { #region IEnumerable Members IEnumerator<Tab> IEnumerable<Tab>.GetEnumerator() { for (int i = 0; i < Count; i++) yield return this[i]; } IEnumerator IEnumerable.GetEnumerator() { for (int i = 0; i < Count; i++) yield return this[i]; } #endregion internal TabCollection(DockPane pane) { m_dockPane = pane; } private DockPane m_dockPane; public DockPane DockPane { get { return m_dockPane; } } public int Count { get { return DockPane.DisplayingContents.Count; } } public Tab this[int index] { get { IDockContent content = DockPane.DisplayingContents[index]; if (content == null) throw (new ArgumentOutOfRangeException("index")); return content.DockHandler.GetTab(DockPane.TabStripControl); } } public bool Contains(Tab tab) { return (IndexOf(tab) != -1); } public bool Contains(IDockContent content) { return (IndexOf(content) != -1); } public int IndexOf(Tab tab) { if (tab == null) return -1; return DockPane.DisplayingContents.IndexOf(tab.Content); } public int IndexOf(IDockContent content) { return DockPane.DisplayingContents.IndexOf(content); } } protected DockPaneStripBase(DockPane pane) { m_dockPane = pane; SetStyle(ControlStyles.OptimizedDoubleBuffer, true); SetStyle(ControlStyles.Selectable, false); AllowDrop = true; } private DockPane m_dockPane; protected DockPane DockPane { get { return m_dockPane; } } protected DockPane.AppearanceStyle Appearance { get { return DockPane.Appearance; } } private TabCollection m_tabs = null; protected TabCollection Tabs { get { if (m_tabs == null) m_tabs = new TabCollection(DockPane); return m_tabs; } } internal void RefreshChanges() { if (IsDisposed) return; OnRefreshChanges(); } protected virtual void OnRefreshChanges() { } protected internal abstract int MeasureHeight(); protected internal abstract void EnsureTabVisible(IDockContent content); protected int HitTest() { return HitTest(PointToClient(Control.MousePosition)); } protected internal abstract int HitTest(Point point); public abstract GraphicsPath GetOutline(int index); protected internal virtual Tab CreateTab(IDockContent content) { return new Tab(content); } private Rectangle _dragBox = Rectangle.Empty; protected override void OnMouseDown(MouseEventArgs e) { base.OnMouseDown(e); int index = HitTest(); if (index != -1) { if (e.Button == MouseButtons.Middle) { // Close the specified content. IDockContent content = Tabs[index].Content; DockPane.CloseContent(content); } else { IDockContent content = Tabs[index].Content; if (DockPane.ActiveContent != content) DockPane.ActiveContent = content; } } if (e.Button == MouseButtons.Left) { var dragSize = SystemInformation.DragSize; _dragBox = new Rectangle(new Point(e.X - (dragSize.Width / 2), e.Y - (dragSize.Height / 2)), dragSize); } } protected override void OnMouseMove(MouseEventArgs e) { base.OnMouseMove(e); if (e.Button != MouseButtons.Left || _dragBox.Contains(e.Location)) return; if (DockPane.ActiveContent == null) return; if (DockPane.DockPanel.AllowEndUserDocking && DockPane.DockPanel.AllowChangeLayout && DockPane.AllowDockDragAndDrop && DockPane.ActiveContent.DockHandler.AllowEndUserDocking) DockPane.DockPanel.BeginDrag(DockPane.ActiveContent.DockHandler); } protected bool HasTabPageContextMenu { get { return DockPane.HasTabPageContextMenu; } } protected void ShowTabPageContextMenu(Point position) { DockPane.ShowTabPageContextMenu(this, position); } protected override void OnMouseUp(MouseEventArgs e) { base.OnMouseUp(e); if (e.Button == MouseButtons.Right) ShowTabPageContextMenu(new Point(e.X, e.Y)); } [SecurityPermission(SecurityAction.LinkDemand, Flags = SecurityPermissionFlag.UnmanagedCode)] protected override void WndProc(ref Message m) { if (m.Msg == (int)Win32.Msgs.WM_LBUTTONDBLCLK) { base.WndProc(ref m); int index = HitTest(); if (DockPane.DockPanel.AllowEndUserDocking && DockPane.DockPanel.AllowChangeLayout && index != -1) { IDockContent content = Tabs[index].Content; if (content.DockHandler.CheckDockState(!content.DockHandler.IsFloat) != DockState.Unknown) content.DockHandler.IsFloat = !content.DockHandler.IsFloat; } return; } base.WndProc(ref m); return; } protected override void OnDragOver(DragEventArgs drgevent) { base.OnDragOver(drgevent); int index = HitTest(); if (index != -1) { IDockContent content = Tabs[index].Content; if (DockPane.ActiveContent != content) DockPane.ActiveContent = content; } } protected abstract Rectangle GetTabBounds(Tab tab); internal static Rectangle ToScreen(Rectangle rectangle, Control parent) { if (parent == null) return rectangle; return new Rectangle(parent.PointToScreen(new Point(rectangle.Left, rectangle.Top)), new Size(rectangle.Width, rectangle.Height)); } protected override AccessibleObject CreateAccessibilityInstance() { return new DockPaneStripAccessibleObject(this); } public class DockPaneStripAccessibleObject : Control.ControlAccessibleObject { private DockPaneStripBase _strip; private DockState _state; public DockPaneStripAccessibleObject(DockPaneStripBase strip) : base(strip) { _strip = strip; } public override AccessibleRole Role { get { return AccessibleRole.PageTabList; } } public override int GetChildCount() { return _strip.Tabs.Count; } public override AccessibleObject GetChild(int index) { return new DockPaneStripTabAccessibleObject(_strip, _strip.Tabs[index], this); } public override AccessibleObject HitTest(int x, int y) { Point point = new Point(x, y); foreach (Tab tab in _strip.Tabs) { Rectangle rectangle = _strip.GetTabBounds(tab); if (ToScreen(rectangle, _strip).Contains(point)) return new DockPaneStripTabAccessibleObject(_strip, tab, this); } return null; } } protected class DockPaneStripTabAccessibleObject : AccessibleObject { private DockPaneStripBase _strip; private Tab _tab; private AccessibleObject _parent; internal DockPaneStripTabAccessibleObject(DockPaneStripBase strip, Tab tab, AccessibleObject parent) { _strip = strip; _tab = tab; _parent = parent; } public override AccessibleObject Parent { get { return _parent; } } public override AccessibleRole Role { get { return AccessibleRole.PageTab; } } public override Rectangle Bounds { get { Rectangle rectangle = _strip.GetTabBounds(_tab); return ToScreen(rectangle, _strip); } } public override string Name { get { return _tab.Content.DockHandler.TabText; } set { //base.Name = value; } } } } }
using System.ComponentModel; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Linq; using NetGore; using NetGore.World; using SFML.Graphics; namespace DemoGame { /// <summary> /// Abstract class for an Entity that is a Character. /// </summary> public abstract partial class CharacterEntity : DynamicEntity, IUpdateableEntity { Direction _heading = Direction.East; /// <summary> /// Initializes a new instance of the <see cref="CharacterEntity"/> class. /// </summary> /// <param name="position">The initial world position.</param> /// <param name="size">The initial size.</param> protected CharacterEntity(Vector2 position, Vector2 size) : base(position, size) { } /// <summary> /// Synchronizes the BodyInfo index for the CharacterEntity. /// </summary> [SyncValue("BodyID")] protected internal BodyID BodyID { get { return BodyInfo.ID; } set { BodyInfo = BodyInfoManager.Instance.GetBody(value); } } /// <summary> /// Gets or sets (protected) the CharacterEntity's BodyInfo. /// </summary> public BodyInfo BodyInfo { get; protected set; } /// <summary> /// When overridden in the derived class, gets if this <see cref="Entity"/> will collide against /// walls. If false, this <see cref="Entity"/> will pass through walls and completely ignore them. /// </summary> [Browsable(false)] public override bool CollidesAgainstWalls { get { return true; } } /// <summary> /// When overridden in the derived class, gets or protected sets if the CharacterEntity has a chat dialog. /// </summary> [SyncValue("HasChatDialog")] [Browsable(false)] public abstract bool HasChatDialog { get; protected set; } /// <summary> /// When overridden in the derived class, gets or protected sets if the CharacterEntity has a shop. /// </summary> [SyncValue("HasShop")] [Browsable(false)] public abstract bool HasShop { get; protected set; } /// <summary> /// Gets or sets the direction the character is currently facing. /// </summary> [SyncValue("Heading")] public Direction Heading { get { return _heading; } set { SetHeading(value); } } /// <summary> /// Gets if the character is moving left or right. /// </summary> [Browsable(false)] public bool IsMoving { get { return Velocity.X != 0; } } /// <summary> /// Gets if the character is moving to the left. /// </summary> [Browsable(false)] public bool IsMovingLeft { get { return Velocity.X < 0; } } /// <summary> /// Gets if the character is moving to the right. /// </summary> [Browsable(false)] public bool IsMovingRight { get { return Velocity.X > 0; } } /// <summary> /// Gets or sets the name of the CharacterEntity. /// </summary> [SyncValue] public virtual string Name { get; set; } /// <summary> /// A flag that determines whether or not this <see cref="CharcterEntity"/> is visible to other clients. /// </summary> [SyncValue] public bool Invisible { get; set; } /// <summary> /// Handles collision against other entities. /// </summary> /// <param name="collideWith">Entity the character collided with.</param> /// <param name="displacement">Displacement between the character and entity.</param> public override void CollideInto(Entity collideWith, Vector2 displacement) { } /// <summary> /// Gets the map interface for the CharacterEntity. If no valid map interface is supplied, /// no map-based collision detection and updating can be used. /// </summary> /// <returns>Map interface for the CharacterEntity.</returns> [SuppressMessage("Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate")] protected abstract IMap GetIMap(); /// <summary> /// Handles updating this <see cref="Entity"/>. /// </summary> /// <param name="imap">The map the <see cref="Entity"/> is on.</param> /// <param name="deltaTime">The amount of time (in milliseconds) that has elapsed since the last update.</param> protected override void HandleUpdate(IMap imap, int deltaTime) { ThreadAsserts.IsMainThread(); Debug.Assert(imap != null, "How the hell is a null Map updating?"); Debug.Assert(deltaTime >= 0, "Unless we're going back in time, deltaTime < 0 makes no sense at all."); // Perform pre-collision detection updating UpdatePreCollision(imap, deltaTime); // Performs basic entity updating base.HandleUpdate(imap, deltaTime); // Perform post-collision detection updating UpdatePostCollision(deltaTime); } /// <summary> /// Sets the character's heading. /// </summary> /// <param name="newHeading">New heading for the character.</param> public virtual void SetHeading(Direction newHeading) { _heading = newHeading; } /// <summary> /// Moves the character to a new location instantly. The character's velocity will /// also be set to zero upon teleporting. /// </summary> /// <param name="position">New position</param> protected override void Teleport(Vector2 position) { // Force the character to stop moving #if !TOPDOWN _state = CharacterState.Falling; #endif SetVelocity(Vector2.Zero); StopMoving(); // Teleport base.Teleport(position); } /// <summary> /// Moves the character to the new location. Unlike Teleport(), this will not set the /// velocity to zero, and is intended for position corrections / resynchronization. /// </summary> /// <param name="position">Correct position.</param> public virtual void UpdatePosition(Vector2 position) { base.Teleport(position); } /// <summary> /// Performs the post-collision detection updating. /// </summary> /// <param name="deltaTime">Time elapsed (in milliseconds) since the last update.</param> protected virtual void UpdatePostCollision(int deltaTime) { // Update the character's state UpdateState(); } /// <summary> /// Performs the pre-collision detection updating. /// </summary> /// <param name="map">The map.</param> /// <param name="deltaTime">Time elapsed (in milliseconds) since the last update.</param> protected virtual void UpdatePreCollision(IMap map, int deltaTime) { // Update velocity UpdateVelocity(map, deltaTime); } #region IUpdateableEntity Members /// <summary> /// Updates the <see cref="IUpdateableEntity"/>. /// </summary> /// <param name="imap">The map that this <see cref="IUpdateableEntity"/> is on.</param> /// <param name="deltaTime">Time elapsed (in milliseconds) since the last update.</param> public void Update(IMap imap, int deltaTime) { HandleUpdate(imap, deltaTime); } #endregion } }
// // BansheeDbFormatMigrator.cs // // Author: // Aaron Bockover <abockover@novell.com> // Gabriel Burt <gburt@novell.com> // // Copyright (C) 2007-2009 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.Data; using System.Reflection; using System.Text; using System.Threading; using Mono.Unix; using Mono.Data.Sqlite; using Hyena; using Hyena.Jobs; using Hyena.Data.Sqlite; using Timer=Hyena.Timer; using Banshee.ServiceStack; using Banshee.Sources; using Banshee.Collection; using Banshee.Collection.Database; using Banshee.Streaming; // MIGRATION NOTE: Return true if the step should allow the driver to continue // Return false if the step should terminate driver namespace Banshee.Database { public class BansheeDbFormatMigrator { // NOTE: Whenever there is a change in ANY of the database schema, // this version MUST be incremented and a migration method // MUST be supplied to match the new version number protected const int CURRENT_VERSION = 42; protected const int CURRENT_METADATA_VERSION = 7; #region Migration Driver public delegate void SlowStartedHandler(string title, string message); public event SlowStartedHandler SlowStarted; public event EventHandler SlowPulse; public event EventHandler SlowFinished; public event EventHandler Started; public event EventHandler Finished; protected sealed class DatabaseVersionAttribute : Attribute { private int version; public DatabaseVersionAttribute(int version) { this.version = version; } public int Version { get { return version; } } } private HyenaSqliteConnection connection; public BansheeDbFormatMigrator (HyenaSqliteConnection connection) { this.connection = connection; } protected virtual void OnSlowStarted(string title, string message) { SlowStartedHandler handler = SlowStarted; if(handler != null) { handler(title, message); } } protected virtual void OnSlowPulse() { EventHandler handler = SlowPulse; if(handler != null) { handler(this, EventArgs.Empty); } } protected virtual void OnSlowFinished() { EventHandler handler = SlowFinished; if(handler != null) { handler(this, EventArgs.Empty); } } protected virtual void OnStarted () { EventHandler handler = Started; if (handler != null) { handler (this, EventArgs.Empty); } } protected virtual void OnFinished () { EventHandler handler = Finished; if (handler != null) { handler (this, EventArgs.Empty); } } public void Migrate () { try { if (DatabaseVersion > CURRENT_VERSION) { throw new DatabaseVersionTooHigh (CURRENT_VERSION, DatabaseVersion); } else if (DatabaseVersion < CURRENT_VERSION) { Execute ("BEGIN"); InnerMigrate (); Execute ("COMMIT"); } else { Log.DebugFormat ("Database version {0} is up to date", DatabaseVersion); } // Trigger metadata refreshes if necessary int metadata_version = connection.Query<int> ("SELECT Value FROM CoreConfiguration WHERE Key = 'MetadataVersion'"); if (DatabaseVersion == CURRENT_VERSION && metadata_version < CURRENT_METADATA_VERSION) { ServiceManager.ServiceStarted += OnServiceStarted; } } catch (DatabaseVersionTooHigh) { throw; } catch (Exception) { Log.Warning ("Rolling back database migration"); Execute ("ROLLBACK"); throw; } OnFinished (); } private void InnerMigrate () { MethodInfo [] methods = GetType ().GetMethods (BindingFlags.Instance | BindingFlags.NonPublic); bool terminate = false; bool ran_migration_step = false; Log.DebugFormat ("Migrating from database version {0} to {1}", DatabaseVersion, CURRENT_VERSION); for (int i = DatabaseVersion + 1; i <= CURRENT_VERSION; i++) { foreach (MethodInfo method in methods) { foreach (DatabaseVersionAttribute attr in method.GetCustomAttributes ( typeof (DatabaseVersionAttribute), false)) { if (attr.Version != i) { continue; } if (!ran_migration_step) { ran_migration_step = true; OnStarted (); } if (!(bool)method.Invoke (this, null)) { terminate = true; } break; } } if (terminate) { break; } } Execute (String.Format ("UPDATE CoreConfiguration SET Value = {0} WHERE Key = 'DatabaseVersion'", CURRENT_VERSION)); } protected bool TableExists(string tableName) { return connection.TableExists (tableName); } protected void Execute(string query) { connection.Execute (query); } protected int DatabaseVersion { get { if (!TableExists("CoreConfiguration")) { return 0; } return connection.Query<int> ("SELECT Value FROM CoreConfiguration WHERE Key = 'DatabaseVersion'"); } } #endregion #pragma warning disable 0169 #region Version 1 [DatabaseVersion (1)] private bool Migrate_1 () { if (TableExists("Tracks")) { InitializeFreshDatabase (true); uint timer_id = Log.DebugTimerStart ("Database Schema Migration"); OnSlowStarted (Catalog.GetString ("Upgrading your Banshee Database"), Catalog.GetString ("Please wait while your old Banshee database is migrated to the new format.")); Thread thread = new Thread (MigrateFromLegacyBanshee); thread.Name = "Database Migrator"; thread.Start (); while (thread.IsAlive) { OnSlowPulse (); Thread.Sleep (100); } Log.DebugTimerPrint (timer_id); OnSlowFinished (); return false; } else { InitializeFreshDatabase (false); return false; } } #endregion #region Version 2 [DatabaseVersion (2)] private bool Migrate_2 () { Execute (String.Format ("ALTER TABLE CoreTracks ADD COLUMN Attributes INTEGER DEFAULT {0}", (int)TrackMediaAttributes.Default)); return true; } #endregion #region Version 3 [DatabaseVersion (3)] private bool Migrate_3 () { Execute ("ALTER TABLE CorePlaylists ADD COLUMN PrimarySourceID INTEGER"); Execute ("UPDATE CorePlaylists SET PrimarySourceID = 1"); Execute ("ALTER TABLE CoreSmartPlaylists ADD COLUMN PrimarySourceID INTEGER"); Execute ("UPDATE CoreSmartPlaylists SET PrimarySourceID = 1"); return true; } #endregion #region Version 4 [DatabaseVersion (4)] private bool Migrate_4 () { Execute ("ALTER TABLE CoreTracks ADD COLUMN LastSkippedStamp INTEGER"); return true; } #endregion #region Version 5 [DatabaseVersion (5)] private bool Migrate_5 () { Execute ("ALTER TABLE CoreTracks ADD COLUMN TitleLowered TEXT"); Execute ("ALTER TABLE CoreArtists ADD COLUMN NameLowered TEXT"); Execute ("ALTER TABLE CoreAlbums ADD COLUMN TitleLowered TEXT"); // Set default so sorting isn't whack while we regenerate Execute ("UPDATE CoreTracks SET TitleLowered = lower(Title)"); Execute ("UPDATE CoreArtists SET NameLowered = lower(Name)"); Execute ("UPDATE CoreAlbums SET TitleLowered = lower(Title)"); // Drop old indexes Execute ("DROP INDEX IF EXISTS CoreTracksPrimarySourceIndex"); Execute ("DROP INDEX IF EXISTS CoreTracksArtistIndex"); Execute ("DROP INDEX IF EXISTS CoreTracksAlbumIndex"); Execute ("DROP INDEX IF EXISTS CoreTracksRatingIndex"); Execute ("DROP INDEX IF EXISTS CoreTracksLastPlayedStampIndex"); Execute ("DROP INDEX IF EXISTS CoreTracksDateAddedStampIndex"); Execute ("DROP INDEX IF EXISTS CoreTracksPlayCountIndex"); Execute ("DROP INDEX IF EXISTS CoreTracksTitleIndex"); Execute ("DROP INDEX IF EXISTS CoreAlbumsIndex"); Execute ("DROP INDEX IF EXISTS CoreAlbumsArtistID"); Execute ("DROP INDEX IF EXISTS CoreArtistsIndex"); Execute ("DROP INDEX IF EXISTS CorePlaylistEntriesIndex"); Execute ("DROP INDEX IF EXISTS CorePlaylistTrackIDIndex"); Execute ("DROP INDEX IF EXISTS CoreSmartPlaylistEntriesPlaylistIndex"); Execute ("DROP INDEX IF EXISTS CoreSmartPlaylistEntriesTrackIndex"); // Create new indexes Execute ("CREATE INDEX IF NOT EXISTS CoreTracksIndex ON CoreTracks(ArtistID, AlbumID, PrimarySourceID, Disc, TrackNumber, Uri)"); Execute ("CREATE INDEX IF NOT EXISTS CoreArtistsIndex ON CoreArtists(NameLowered)"); Execute ("CREATE INDEX IF NOT EXISTS CoreAlbumsIndex ON CoreAlbums(ArtistID, TitleLowered)"); Execute ("CREATE INDEX IF NOT EXISTS CoreSmartPlaylistEntriesIndex ON CoreSmartPlaylistEntries(SmartPlaylistID, TrackID)"); Execute ("CREATE INDEX IF NOT EXISTS CorePlaylistEntriesIndex ON CorePlaylistEntries(PlaylistID, TrackID)"); return true; } #endregion #region Version 6 [DatabaseVersion (6)] private bool Migrate_6 () { Execute ("INSERT INTO CoreConfiguration (EntryID, Key, Value) VALUES (null, 'MetadataVersion', 0)"); return true; } #endregion #region Version 7 [DatabaseVersion (7)] private bool Migrate_7 () { try { Execute ("UPDATE CorePrimarySources SET StringID = 'MusicLibrarySource-Library' WHERE StringID = 'Library'"); } catch {} try { Execute ("UPDATE CorePrimarySources SET StringID = 'VideoLibrarySource-VideoLibrary' WHERE StringID = 'VideoLibrary'"); } catch {} try { Execute ("UPDATE CorePrimarySources SET StringID = 'PodcastSource-podcasting' WHERE StringID = 'podcasting'"); } catch {} try { Execute ("DELETE FROM CoreCache; DELETE FROM CoreCacheModels"); } catch {} return true; } #endregion #region Version 8 [DatabaseVersion (8)] private bool Migrate_8 () { Execute ("ALTER TABLE CorePrimarySources ADD COLUMN CachedCount INTEGER"); Execute ("ALTER TABLE CorePlaylists ADD COLUMN CachedCount INTEGER"); Execute ("ALTER TABLE CoreSmartPlaylists ADD COLUMN CachedCount INTEGER"); // This once, we need to reload all the sources at start up. Then never again, woo! Application.ClientStarted += ReloadAllSources; return true; } #endregion #region Version 9 [DatabaseVersion (9)] private bool Migrate_9 () { Execute (String.Format ("ALTER TABLE CoreTracks ADD COLUMN LastStreamError INTEGER DEFAULT {0}", (int)StreamPlaybackError.None)); return true; } #endregion #region Version 10 [DatabaseVersion (10)] private bool Migrate_10 () { // Clear these out for people who ran the pre-alpha podcast plugin Execute ("DROP TABLE IF EXISTS PodcastEnclosures"); Execute ("DROP TABLE IF EXISTS PodcastItems"); Execute ("DROP TABLE IF EXISTS PodcastSyndications"); Execute ("ALTER TABLE CoreTracks ADD COLUMN ExternalID INTEGER"); return true; } #endregion #region Version 11 [DatabaseVersion (11)] private bool Migrate_11 () { Execute("CREATE INDEX CoreTracksExternalIDIndex ON CoreTracks(PrimarySourceID, ExternalID)"); return true; } #endregion #region Version 12 [DatabaseVersion (12)] private bool Migrate_12 () { Execute ("ALTER TABLE CoreAlbums ADD COLUMN ArtistName STRING"); Execute ("ALTER TABLE CoreAlbums ADD COLUMN ArtistNameLowered STRING"); return true; } #endregion #region Version 13 [DatabaseVersion (13)] private bool Migrate_13 () { Execute("CREATE INDEX CoreAlbumsArtistIndex ON CoreAlbums(TitleLowered, ArtistNameLowered)"); Execute("CREATE INDEX CoreTracksUriIndex ON CoreTracks(PrimarySourceID, Uri)"); return true; } #endregion #region Version 14 [DatabaseVersion (14)] private bool Migrate_14 () { InitializeOrderedTracks (); return true; } #endregion #region Version 15 [DatabaseVersion (15)] private bool Migrate_15 () { string [] columns = new string [] {"Genre", "Composer", "Copyright", "LicenseUri", "Comment"}; foreach (string column in columns) { Execute (String.Format ("UPDATE CoreTracks SET {0} = NULL WHERE {0} IS NOT NULL AND trim({0}) = ''", column)); } return true; } #endregion #region Version 16 [DatabaseVersion (16)] private bool Migrate_16 () { // The CoreCache table is now created as needed, and as a TEMP table Execute ("DROP TABLE CoreCache"); Execute ("COMMIT; VACUUM; BEGIN"); Execute ("ANALYZE"); return true; } #endregion #region Version 17 [DatabaseVersion (17)] private bool Migrate_17 () { Execute ("CREATE INDEX CoreTracksCoverArtIndex ON CoreTracks (PrimarySourceID, AlbumID, DateUpdatedStamp)"); Execute ("ANALYZE"); return true; } #endregion #region Version 18 [DatabaseVersion (18)] private bool Migrate_18 () { Execute ("ALTER TABLE CoreTracks ADD COLUMN MetadataHash TEXT"); return true; } #endregion #region Version 19 [DatabaseVersion (19)] private bool Migrate_19 () { Execute ("ALTER TABLE CoreAlbums ADD COLUMN IsCompilation INTEGER DEFAULT 0"); Execute ("ALTER TABLE CoreTracks ADD COLUMN BPM INTEGER"); Execute ("ALTER TABLE CoreTracks ADD COLUMN DiscCount INTEGER"); Execute ("ALTER TABLE CoreTracks ADD COLUMN Conductor TEXT"); Execute ("ALTER TABLE CoreTracks ADD COLUMN Grouping TEXT"); Execute ("ALTER TABLE CoreTracks ADD COLUMN BitRate INTEGER DEFAULT 0"); return true; } #endregion #region Version 20 [DatabaseVersion (20)] private bool Migrate_20 () { Execute ("ALTER TABLE CoreSmartPlaylists ADD COLUMN IsTemporary INTEGER DEFAULT 0"); Execute ("ALTER TABLE CorePlaylists ADD COLUMN IsTemporary INTEGER DEFAULT 0"); Execute ("ALTER TABLE CorePrimarySources ADD COLUMN IsTemporary INTEGER DEFAULT 0"); return true; } #endregion #region Version 21 [DatabaseVersion (21)] private bool Migrate_21 () { // We had a bug where downloaded podcast episodes would no longer have the Podcast attribute. int id = connection.Query<int> ("SELECT PrimarySourceId FROM CorePrimarySources WHERE StringID = 'PodcastSource-PodcastLibrary'"); if (id > 0) { connection.Execute ("UPDATE CoreTracks SET Attributes = Attributes | ? WHERE PrimarySourceID = ?", (int)TrackMediaAttributes.Podcast, id); } return true; } #endregion #region Version 22 [DatabaseVersion (22)] private bool Migrate_22 () { Execute ("ALTER TABLE CoreTracks ADD COLUMN LastSyncedStamp INTEGER DEFAULT NULL"); Execute ("ALTER TABLE CoreTracks ADD COLUMN FileModifiedStamp INTEGER DEFAULT NULL"); Execute ("UPDATE CoreTracks SET LastSyncedStamp = DateAddedStamp;"); return true; } #endregion #region Version 23 [DatabaseVersion (23)] private bool Migrate_23 () { Execute ("ALTER TABLE CoreArtists ADD COLUMN NameSort TEXT"); Execute ("ALTER TABLE CoreAlbums ADD COLUMN ArtistNameSort TEXT"); Execute ("ALTER TABLE CoreAlbums ADD COLUMN TitleSort TEXT"); Execute ("ALTER TABLE CoreTracks ADD COLUMN TitleSort TEXT"); return true; } #endregion #region Version 24 [DatabaseVersion (24)] private bool Migrate_24 () { Execute ("UPDATE CoreArtists SET NameLowered = HYENA_SEARCH_KEY(Name)"); Execute ("UPDATE CoreAlbums SET ArtistNameLowered = HYENA_SEARCH_KEY(ArtistName)"); Execute ("UPDATE CoreAlbums SET TitleLowered = HYENA_SEARCH_KEY(Title)"); Execute ("UPDATE CoreTracks SET TitleLowered = HYENA_SEARCH_KEY(Title)"); return true; } #endregion #region Version 25 [DatabaseVersion (25)] private bool Migrate_25 () { Execute ("ALTER TABLE CoreArtists ADD COLUMN NameSortKey BLOB"); Execute ("ALTER TABLE CoreAlbums ADD COLUMN ArtistNameSortKey BLOB"); Execute ("ALTER TABLE CoreAlbums ADD COLUMN TitleSortKey BLOB"); Execute ("ALTER TABLE CoreTracks ADD COLUMN TitleSortKey BLOB"); return true; } #endregion #region Version 26 [DatabaseVersion (26)] private bool Migrate_26 () { string unknown_artist = "Unknown Artist"; string unknown_album = "Unknown Album"; string unknown_title = "Unknown Title"; connection.Execute ("UPDATE CoreArtists SET Name = NULL, NameLowered = HYENA_SEARCH_KEY(?)" + " WHERE Name IN ('', ?, ?) OR Name IS NULL", ArtistInfo.UnknownArtistName, unknown_artist, ArtistInfo.UnknownArtistName); connection.Execute ("UPDATE CoreAlbums SET ArtistName = NULL, ArtistNameLowered = HYENA_SEARCH_KEY(?)" + " WHERE ArtistName IN ('', ?, ?) OR ArtistName IS NULL", ArtistInfo.UnknownArtistName, unknown_artist, ArtistInfo.UnknownArtistName); connection.Execute ("UPDATE CoreAlbums SET Title = NULL, TitleLowered = HYENA_SEARCH_KEY(?)" + " WHERE Title IN ('', ?, ?) OR Title IS NULL", AlbumInfo.UnknownAlbumTitle, unknown_album, AlbumInfo.UnknownAlbumTitle); connection.Execute ("UPDATE CoreTracks SET Title = NULL, TitleLowered = HYENA_SEARCH_KEY(?)" + " WHERE Title IN ('', ?, ?) OR Title IS NULL", TrackInfo.UnknownTitle, unknown_title, TrackInfo.UnknownTitle); return true; } #endregion #region Version 27 [DatabaseVersion (27)] private bool Migrate_27 () { // One time fixup to MetadataHash now that our unknown metadata is handled properly string sql_select = @" SELECT t.TrackID, al.Title, ar.Name, t.Duration, t.Genre, t.Title, t.TrackNumber, t.Year FROM CoreTracks AS t JOIN CoreAlbums AS al ON al.AlbumID=t.AlbumID JOIN CoreArtists AS ar ON ar.ArtistID=t.ArtistID WHERE t.Title IS NULL OR ar.Name IS NULL OR al.Title IS NULL "; HyenaSqliteCommand sql_update = new HyenaSqliteCommand (@" UPDATE CoreTracks SET MetadataHash = ? WHERE TrackID = ? "); StringBuilder sb = new StringBuilder (); using (var reader = new HyenaDataReader (connection.Query (sql_select))) { while (reader.Read ()) { sb.Length = 0; sb.Append (reader.Get<string> (1)); sb.Append (reader.Get<string> (2)); sb.Append ((int)reader.Get<TimeSpan> (3).TotalSeconds); sb.Append (reader.Get<string> (4)); sb.Append (reader.Get<string> (5)); sb.Append (reader.Get<int> (6)); sb.Append (reader.Get<int> (7)); string hash = Hyena.CryptoUtil.Md5Encode (sb.ToString (), System.Text.Encoding.UTF8); connection.Execute (sql_update, hash, reader.Get<int> (0)); } } return true; } #endregion #region Version 28 [DatabaseVersion (28)] private bool Migrate_28 () { // Update search keys for new space-stripping behavior. connection.Execute ("UPDATE CoreArtists SET NameLowered = HYENA_SEARCH_KEY(IFNULL(Name, ?))", ArtistInfo.UnknownArtistName); connection.Execute ("UPDATE CoreAlbums SET ArtistNameLowered = HYENA_SEARCH_KEY(IFNULL(ArtistName, ?))," + " TitleLowered = HYENA_SEARCH_KEY(IFNULL(Title, ?))", ArtistInfo.UnknownArtistName, AlbumInfo.UnknownAlbumTitle); connection.Execute ("UPDATE CoreTracks SET TitleLowered = HYENA_SEARCH_KEY(IFNULL(Title, ?))", TrackInfo.UnknownTitle); return true; } #endregion #region Version 29 [DatabaseVersion (29)] private bool Migrate_29 () { Execute ("ALTER TABLE CoreTracks ADD COLUMN Score INTEGER DEFAULT 0"); Execute (@" UPDATE CoreTracks SET Score = CAST(ROUND(100.00 * PlayCount / (PlayCount + SkipCount)) AS INTEGER) WHERE PlayCount + SkipCount > 0 "); return true; } #endregion #region Version 30 [DatabaseVersion (30)] private bool Migrate_30 () { Execute ("DROP INDEX IF EXISTS CoreAlbumsIndex"); Execute ("DROP INDEX IF EXISTS CoreAlbumsArtistIndex"); Execute ("DROP INDEX IF EXISTS CoreArtistsIndex"); Execute ("CREATE INDEX CoreAlbumsIndex ON CoreAlbums(ArtistID, TitleSortKey)"); Execute ("CREATE INDEX CoreAlbumsArtistIndex ON CoreAlbums(TitleSortKey, ArtistNameSortKey)"); Execute ("CREATE INDEX CoreArtistsIndex ON CoreArtists(NameSortKey)"); Execute ("ANALYZE"); return true; } #endregion #region Version 31 [DatabaseVersion (31)] private bool Migrate_31 () { try { // Make paths not relative for Music Library items string library_path = Banshee.Library.LibrarySource.OldLocationSchema.Get (Banshee.Library.MusicLibrarySource.GetDefaultBaseDirectory ()); if (library_path != null) { int podcast_src_id = connection.Query<int> ("SELECT PrimarySourceID FROM CorePrimarySources WHERE StringID = 'PodcastSource-PodcastLibrary'"); connection.Execute (@" UPDATE CoreTracks SET Uri = BANSHEE_MIGRATE_PARTIAL(?, Uri) WHERE UriType = 1 AND PrimarySourceID != ?", library_path, podcast_src_id); string podcast_path = Paths.Combine (library_path, "Podcasts"); connection.Execute (@" UPDATE CoreTracks SET Uri = BANSHEE_MIGRATE_PARTIAL(?, Uri) WHERE UriType = 1 AND PrimarySourceID = ?", podcast_path, podcast_src_id); } } catch (Exception e) { Hyena.Log.Exception (e); } return true; } #endregion #region Version 32 [DatabaseVersion (32)] private bool Migrate_32 () { Execute ("DROP INDEX IF EXISTS CoreSmartPlaylistEntriesPlaylistIndex"); Execute ("DROP INDEX IF EXISTS CoreSmartPlaylistEntriesIndex"); Execute ("ANALYZE"); return true; } #endregion #region Version 33 [DatabaseVersion (33)] private bool Migrate_33 () { // We used to have a bug where MimeType didn't get set for tracks we ripped, // so set any blank ones now. See BGO #536590 foreach (var ext in new string [] {"mp3", "ogg", "flac", "aac", "oga", "wma", "wm"}) { Execute (String.Format ( "UPDATE CoreTracks SET MimeType = 'taglib/{0}' WHERE PrimarySourceId = 1 AND (MimeType IS NULL OR MimeType = '') AND Uri LIKE '%.{0}'", ext )); } return true; } #endregion #region Version 34 [DatabaseVersion (34)] private bool Migrate_34 () { Execute ("CREATE INDEX IF NOT EXISTS CoreSmartPlaylistEntriesIndex ON CoreSmartPlaylistEntries(SmartPlaylistID, TrackID)"); return true; } #endregion #region Version 35 [DatabaseVersion (35)] private bool Migrate_35 () { if (!connection.ColumnExists ("CorePlaylistEntries", "Generated")) { Execute ("ALTER TABLE CorePlaylistEntries ADD COLUMN Generated INTEGER NOT NULL DEFAULT 0"); } return true; } #endregion #region Version 36 [DatabaseVersion (36)] private bool Migrate_36 () { Execute(@" CREATE TABLE CoreShuffles ( ShufflerId INTEGER, TrackID INTEGER, LastShuffledAt INTEGER, CONSTRAINT one_entry_per_track UNIQUE (ShufflerID, TrackID) ) "); Execute("CREATE INDEX CoreShufflesIndex ON CoreShuffles (ShufflerId, TrackID, LastShuffledAt)"); Execute(@" CREATE TABLE CoreShufflers ( ShufflerId INTEGER PRIMARY KEY, Id TEXT UNIQUE ) "); return true; } #endregion #region Version 37 [DatabaseVersion (37)] private bool Migrate_37 () { SortKeyUpdater.ForceUpdate (); return true; } #endregion #region Version 38 [DatabaseVersion (38)] private bool Migrate_38 () { Execute ("ALTER TABLE CoreTracks ADD COLUMN SampleRate INTEGER DEFAULT 0"); Execute ("ALTER TABLE CoreTracks ADD COLUMN BitsPerSample INTEGER DEFAULT 0"); return true; } #endregion #region Version 39 [DatabaseVersion (39)] private bool Migrate_39 () { // One time fixup to MetadataHash, since we no longer include the Duration string sql_select = @" SELECT t.TrackID, al.Title, ar.Name, t.Genre, t.Title, t.TrackNumber, t.Year FROM CoreTracks AS t JOIN CoreAlbums AS al ON al.AlbumID=t.AlbumID JOIN CoreArtists AS ar ON ar.ArtistID=t.ArtistID "; HyenaSqliteCommand sql_update = new HyenaSqliteCommand (@" UPDATE CoreTracks SET MetadataHash = ? WHERE TrackID = ? "); StringBuilder sb = new StringBuilder (); using (var reader = new HyenaDataReader (connection.Query (sql_select))) { while (reader.Read ()) { sb.Length = 0; sb.Append (reader.Get<string> (1)); sb.Append (reader.Get<string> (2)); sb.Append (reader.Get<string> (3)); sb.Append (reader.Get<string> (4)); sb.Append (reader.Get<int> (5)); sb.Append (reader.Get<int> (6)); string hash = Hyena.CryptoUtil.Md5Encode (sb.ToString (), System.Text.Encoding.UTF8); connection.Execute (sql_update, hash, reader.Get<int> (0)); } } return true; } #endregion [DatabaseVersion (40)] private bool Migrate_40 () { Execute(@" CREATE TABLE CoreShuffleDiscards ( ShufflerId INTEGER, TrackID INTEGER, LastDiscardedAt INTEGER, CONSTRAINT one_entry_per_track UNIQUE (ShufflerID, TrackID) ) "); Execute("CREATE INDEX CoreShuffleDiscardsIndex ON CoreShuffleDiscards (ShufflerId, TrackID, LastDiscardedAt)"); return true; } [DatabaseVersion (41)] private bool Migrate_41 () { Execute ("DROP TABLE IF EXISTS CoreShuffleDiscards"); Execute ("DROP INDEX IF EXISTS CoreShuffleDiscardsIndex"); Execute (@" CREATE TABLE CoreShuffleModifications ( ShufflerId INTEGER, TrackID INTEGER, LastModifiedAt INTEGER, ModificationType INTEGER, CONSTRAINT one_entry_per_track UNIQUE (ShufflerID, TrackID) ) "); Execute ("CREATE INDEX CoreShuffleModificationsIndex ON CoreShuffleModifications (ShufflerId, TrackID, LastModifiedAt, ModificationType)"); return true; } [DatabaseVersion (42)] private bool Migrate_42 () { // Unset the Music attribute for any videos or podcasts connection.Execute ( @"UPDATE CoreTracks SET Attributes = Attributes & ? WHERE (Attributes & ?) != 0", (int)(~TrackMediaAttributes.Music), (int)(TrackMediaAttributes.VideoStream | TrackMediaAttributes.Podcast) ); return true; } #pragma warning restore 0169 #region Fresh database setup private void InitializeFreshDatabase (bool refresh_metadata) { Execute("DROP TABLE IF EXISTS CoreConfiguration"); Execute("DROP TABLE IF EXISTS CoreTracks"); Execute("DROP TABLE IF EXISTS CoreArtists"); Execute("DROP TABLE IF EXISTS CoreAlbums"); Execute("DROP TABLE IF EXISTS CorePlaylists"); Execute("DROP TABLE IF EXISTS CorePlaylistEntries"); Execute("DROP TABLE IF EXISTS CoreSmartPlaylists"); Execute("DROP TABLE IF EXISTS CoreSmartPlaylistEntries"); Execute("DROP TABLE IF EXISTS CoreRemovedTracks"); Execute("DROP TABLE IF EXISTS CoreTracksCache"); Execute("DROP TABLE IF EXISTS CoreCache"); Execute(@" CREATE TABLE CoreConfiguration ( EntryID INTEGER PRIMARY KEY, Key TEXT, Value TEXT ) "); Execute (String.Format ("INSERT INTO CoreConfiguration (EntryID, Key, Value) VALUES (null, 'DatabaseVersion', {0})", CURRENT_VERSION)); if (!refresh_metadata) { Execute (String.Format ("INSERT INTO CoreConfiguration (EntryID, Key, Value) VALUES (null, 'MetadataVersion', {0})", CURRENT_METADATA_VERSION)); } Execute(@" CREATE TABLE CorePrimarySources ( PrimarySourceID INTEGER PRIMARY KEY, StringID TEXT UNIQUE, CachedCount INTEGER, IsTemporary INTEGER DEFAULT 0 ) "); Execute ("INSERT INTO CorePrimarySources (StringID) VALUES ('MusicLibrarySource-Library')"); // TODO add these: // Others to consider: // AlbumArtist (TPE2) (in CoreAlbums?) Execute(String.Format (@" CREATE TABLE CoreTracks ( PrimarySourceID INTEGER NOT NULL, TrackID INTEGER PRIMARY KEY, ArtistID INTEGER, AlbumID INTEGER, TagSetID INTEGER, ExternalID INTEGER, MusicBrainzID TEXT, Uri TEXT, MimeType TEXT, FileSize INTEGER, BitRate INTEGER, SampleRate INTEGER, BitsPerSample INTEGER, Attributes INTEGER DEFAULT {0}, LastStreamError INTEGER DEFAULT {1}, Title TEXT, TitleLowered TEXT, TitleSort TEXT, TitleSortKey BLOB, TrackNumber INTEGER, TrackCount INTEGER, Disc INTEGER, DiscCount INTEGER, Duration INTEGER, Year INTEGER, Genre TEXT, Composer TEXT, Conductor TEXT, Grouping TEXT, Copyright TEXT, LicenseUri TEXT, Comment TEXT, Rating INTEGER, Score INTEGER, PlayCount INTEGER, SkipCount INTEGER, LastPlayedStamp INTEGER, LastSkippedStamp INTEGER, DateAddedStamp INTEGER, DateUpdatedStamp INTEGER, MetadataHash TEXT, BPM INTEGER, LastSyncedStamp INTEGER, FileModifiedStamp INTEGER ) ", (int)TrackMediaAttributes.Default, (int)StreamPlaybackError.None)); Execute("CREATE INDEX CoreTracksPrimarySourceIndex ON CoreTracks(ArtistID, AlbumID, PrimarySourceID, Disc, TrackNumber, Uri)"); Execute("CREATE INDEX CoreTracksAggregatesIndex ON CoreTracks(FileSize, Duration)"); Execute("CREATE INDEX CoreTracksExternalIDIndex ON CoreTracks(PrimarySourceID, ExternalID)"); Execute("CREATE INDEX CoreTracksUriIndex ON CoreTracks(PrimarySourceID, Uri)"); Execute("CREATE INDEX CoreTracksCoverArtIndex ON CoreTracks (PrimarySourceID, AlbumID, DateUpdatedStamp)"); Execute(@" CREATE TABLE CoreAlbums ( AlbumID INTEGER PRIMARY KEY, ArtistID INTEGER, TagSetID INTEGER, MusicBrainzID TEXT, Title TEXT, TitleLowered TEXT, TitleSort TEXT, TitleSortKey BLOB, ReleaseDate INTEGER, Duration INTEGER, Year INTEGER, IsCompilation INTEGER DEFAULT 0, ArtistName TEXT, ArtistNameLowered TEXT, ArtistNameSort TEXT, ArtistNameSortKey BLOB, Rating INTEGER ) "); Execute ("CREATE INDEX CoreAlbumsIndex ON CoreAlbums(ArtistID, TitleSortKey)"); Execute ("CREATE INDEX CoreAlbumsArtistIndex ON CoreAlbums(TitleSortKey, ArtistNameSortKey)"); Execute(@" CREATE TABLE CoreArtists ( ArtistID INTEGER PRIMARY KEY, TagSetID INTEGER, MusicBrainzID TEXT, Name TEXT, NameLowered TEXT, NameSort TEXT, NameSortKey BLOB, Rating INTEGER ) "); Execute ("CREATE INDEX CoreArtistsIndex ON CoreArtists(NameSortKey)"); Execute(@" CREATE TABLE CorePlaylists ( PrimarySourceID INTEGER, PlaylistID INTEGER PRIMARY KEY, Name TEXT, SortColumn INTEGER NOT NULL DEFAULT -1, SortType INTEGER NOT NULL DEFAULT 0, Special INTEGER NOT NULL DEFAULT 0, CachedCount INTEGER, IsTemporary INTEGER DEFAULT 0 ) "); Execute(@" CREATE TABLE CorePlaylistEntries ( EntryID INTEGER PRIMARY KEY, PlaylistID INTEGER NOT NULL, TrackID INTEGER NOT NULL, ViewOrder INTEGER NOT NULL DEFAULT 0, Generated INTEGER NOT NULL DEFAULT 0 ) "); Execute("CREATE INDEX CorePlaylistEntriesIndex ON CorePlaylistEntries(PlaylistID, TrackID)"); Execute(@" CREATE TABLE CoreSmartPlaylists ( PrimarySourceID INTEGER, SmartPlaylistID INTEGER PRIMARY KEY, Name TEXT NOT NULL, Condition TEXT, OrderBy TEXT, LimitNumber TEXT, LimitCriterion TEXT, CachedCount INTEGER, IsTemporary INTEGER DEFAULT 0 ) "); Execute(@" CREATE TABLE CoreSmartPlaylistEntries ( EntryID INTEGER PRIMARY KEY, SmartPlaylistID INTEGER NOT NULL, TrackID INTEGER NOT NULL ) "); Execute ("CREATE INDEX CoreSmartPlaylistEntriesIndex ON CoreSmartPlaylistEntries(SmartPlaylistID, TrackID)"); Execute(@" CREATE TABLE CoreRemovedTracks ( TrackID INTEGER NOT NULL, Uri TEXT, DateRemovedStamp INTEGER ) "); Execute(@" CREATE TABLE CoreCacheModels ( CacheID INTEGER PRIMARY KEY, ModelID TEXT ) "); // This index slows down queries were we shove data into the CoreCache. // Since we do that frequently, not using it. //Execute("CREATE INDEX CoreCacheModelId ON CoreCache(ModelID)"); Execute(@" CREATE TABLE CoreShuffles ( ShufflerId INTEGER, TrackID INTEGER, LastShuffledAt INTEGER, CONSTRAINT one_entry_per_track UNIQUE (ShufflerID, TrackID) ) "); Execute("CREATE INDEX CoreShufflesIndex ON CoreShuffles (ShufflerId, TrackID, LastShuffledAt)"); Execute(@" CREATE TABLE CoreShufflers ( ShufflerId INTEGER PRIMARY KEY, Id TEXT UNIQUE ) "); Execute (@" CREATE TABLE CoreShuffleModifications ( ShufflerId INTEGER, TrackID INTEGER, LastModifiedAt INTEGER, ModificationType INTEGER, CONSTRAINT one_entry_per_track UNIQUE (ShufflerID, TrackID) ) "); Execute ("CREATE INDEX CoreShuffleModificationsIndex ON CoreShuffleModifications (ShufflerId, TrackID, LastModifiedAt, ModificationType)"); } #endregion #region Legacy database migration private void MigrateFromLegacyBanshee() { Execute(@" INSERT INTO CoreArtists (ArtistID, TagSetID, MusicBrainzID, Name, NameLowered, NameSort, Rating) SELECT DISTINCT null, 0, null, Artist, NULL, NULL, 0 FROM Tracks ORDER BY Artist "); Execute(@" INSERT INTO CoreAlbums (AlbumID, ArtistID, TagSetID, MusicBrainzID, Title, TitleLowered, TitleSort, ReleaseDate, Duration, Year, IsCompilation, ArtistName, ArtistNameLowered, ArtistNameSort, Rating) SELECT DISTINCT null, (SELECT ArtistID FROM CoreArtists WHERE Name = Tracks.Artist LIMIT 1), 0, null, AlbumTitle, NULL, NULL, ReleaseDate, 0, 0, 0, Artist, NULL, NULL, 0 FROM Tracks ORDER BY AlbumTitle "); Execute (String.Format (@" INSERT INTO CoreTracks (PrimarySourceID, TrackID, ArtistID, AlbumID, TagSetID, ExternalID, MusicBrainzID, Uri, MimeType, FileSize, BitRate, Attributes, LastStreamError, Title, TitleLowered, TrackNumber, TrackCount, Disc, DiscCount, Duration, Year, Genre, Composer, Conductor, Grouping, Copyright, LicenseUri, Comment, Rating, Score, PlayCount, SkipCount, LastPlayedStamp, LastSkippedStamp, DateAddedStamp, DateUpdatedStamp, MetadataHash, BPM, LastSyncedStamp, FileModifiedStamp) SELECT 1, TrackID, (SELECT ArtistID FROM CoreArtists WHERE Name = Artist), (SELECT a.AlbumID FROM CoreAlbums a, CoreArtists b WHERE a.Title = AlbumTitle AND a.ArtistID = b.ArtistID AND b.Name = Artist), 0, 0, 0, Uri, MimeType, 0, 0, {0}, {1}, Title, NULL, TrackNumber, TrackCount, 0, 0, Duration * 1000, Year, Genre, NULL, NULL, NULL, NULL, NULL, NULL, Rating, 0, NumberOfPlays, 0, LastPlayedStamp, NULL, DateAddedStamp, DateAddedStamp, NULL, NULL, DateAddedStamp, NULL FROM Tracks ", (int)TrackMediaAttributes.Default, (int)StreamPlaybackError.None)); Execute ("UPDATE CoreTracks SET LastPlayedStamp = NULL WHERE LastPlayedStamp = -62135575200"); // Old versions of Banshee had different columns for Playlists/PlaylistEntries, so be careful try { Execute(@" INSERT INTO CorePlaylists (PlaylistID, Name, SortColumn, SortType) SELECT * FROM Playlists; INSERT INTO CorePlaylistEntries (EntryID, PlaylistID, TrackID, ViewOrder) SELECT * FROM PlaylistEntries "); } catch (Exception e) { Log.Exception ("Must be a pre-0.13.2 banshee.db, attempting to migrate", e); try { Execute(@" INSERT INTO CorePlaylists (PlaylistID, Name) SELECT PlaylistID, Name FROM Playlists; INSERT INTO CorePlaylistEntries (EntryID, PlaylistID, TrackID) SELECT EntryID, PlaylistID, TrackID FROM PlaylistEntries "); Log.Debug ("Success, was able to migrate older playlist information"); } catch (Exception e2) { Log.Exception ("Failed to migrate playlists", e2); } } // Really old versions of Banshee didn't have SmartPlaylists, so ignore errors try { Execute(@" INSERT INTO CoreSmartPlaylists (SmartPlaylistID, Name, Condition, OrderBy, LimitNumber, LimitCriterion) SELECT * FROM SmartPlaylists "); } catch {} Execute ("UPDATE CoreSmartPlaylists SET PrimarySourceID = 1"); Execute ("UPDATE CorePlaylists SET PrimarySourceID = 1"); InitializeOrderedTracks (); Migrate_15 (); } #endregion #region Utilities / Source / Service Stuff private void InitializeOrderedTracks () { foreach (long playlist_id in connection.QueryEnumerable<long> ("SELECT PlaylistID FROM CorePlaylists ORDER BY PlaylistID")) { if (connection.Query<long> (@"SELECT COUNT(*) FROM CorePlaylistEntries WHERE PlaylistID = ? AND ViewOrder > 0", playlist_id) <= 0) { long first_id = connection.Query<long> ("SELECT COUNT(*) FROM CorePlaylistEntries WHERE PlaylistID < ?", playlist_id); connection.Execute ( @"UPDATE CorePlaylistEntries SET ViewOrder = (ROWID - ?) WHERE PlaylistID = ?", first_id, playlist_id ); } } } private void OnServiceStarted (ServiceStartedArgs args) { if (args.Service is JobScheduler) { ServiceManager.ServiceStarted -= OnServiceStarted; if (ServiceManager.SourceManager.MusicLibrary != null) { RefreshMetadataDelayed (); } else { ServiceManager.SourceManager.SourceAdded += OnSourceAdded; } } } private void OnSourceAdded (SourceAddedArgs args) { if (ServiceManager.SourceManager.MusicLibrary != null && ServiceManager.SourceManager.VideoLibrary != null) { ServiceManager.SourceManager.SourceAdded -= OnSourceAdded; RefreshMetadataDelayed (); } } private void ReloadAllSources (Client client) { Application.ClientStarted -= ReloadAllSources; foreach (Source source in ServiceManager.SourceManager.Sources) { if (source is ITrackModelSource) { ((ITrackModelSource)source).Reload (); } } } #endregion #region Metadata Refresh Driver private void RefreshMetadataDelayed () { Application.RunTimeout (3000, RefreshMetadata); } private bool RefreshMetadata () { ThreadPool.QueueUserWorkItem (RefreshMetadataThread); return false; } private void RefreshMetadataThread (object state) { int total = ServiceManager.DbConnection.Query<int> ("SELECT count(*) FROM CoreTracks"); if (total <= 0) { return; } UserJob job = new UserJob (Catalog.GetString ("Refreshing Metadata")); job.SetResources (Resource.Cpu, Resource.Disk, Resource.Database); job.PriorityHints = PriorityHints.SpeedSensitive; job.Status = Catalog.GetString ("Scanning..."); job.IconNames = new string [] { "system-search", "gtk-find" }; job.Register (); HyenaSqliteCommand select_command = new HyenaSqliteCommand ( String.Format ( "SELECT {0} FROM {1} WHERE {2}", DatabaseTrackInfo.Provider.Select, DatabaseTrackInfo.Provider.From, DatabaseTrackInfo.Provider.Where ) ); int count = 0; using (System.Data.IDataReader reader = ServiceManager.DbConnection.Query (select_command)) { while (reader.Read ()) { DatabaseTrackInfo track = null; try { track = DatabaseTrackInfo.Provider.Load (reader); if (track != null && track.Uri != null && track.Uri.IsFile) { try { using (var file = StreamTagger.ProcessUri (track.Uri)) { StreamTagger.TrackInfoMerge (track, file, true); } } catch (Exception e) { Log.Warning (String.Format ("Failed to update metadata for {0}", track), e.GetType ().ToString (), false); } track.Save (false); track.Artist.Save (); track.Album.Save (); job.Status = String.Format ("{0} - {1}", track.DisplayArtistName, track.DisplayTrackTitle); } } catch (Exception e) { Log.Warning (String.Format ("Failed to update metadata for {0}", track), e.ToString (), false); } job.Progress = (double)++count / (double)total; } } if (ServiceManager.DbConnection.Query<int> ("SELECT count(*) FROM CoreConfiguration WHERE Key = 'MetadataVersion'") == 0) { Execute (String.Format ("INSERT INTO CoreConfiguration (EntryID, Key, Value) VALUES (null, 'MetadataVersion', {0})", CURRENT_METADATA_VERSION)); } else { Execute (String.Format ("UPDATE CoreConfiguration SET Value = {0} WHERE Key = 'MetadataVersion'", CURRENT_METADATA_VERSION)); } job.Finish (); ServiceManager.SourceManager.MusicLibrary.NotifyTracksChanged (); } #endregion class DatabaseVersionTooHigh : ApplicationException { internal DatabaseVersionTooHigh (int currentVersion, int databaseVersion) : base (String.Format ( "This version of Banshee was prepared to work with older database versions (=< {0}) thus it is too old to support the current version of the database ({1}).", currentVersion, databaseVersion)) { } private DatabaseVersionTooHigh () { } } } [SqliteFunction (Name = "BANSHEE_MIGRATE_PARTIAL", FuncType = FunctionType.Scalar, Arguments = 2)] internal class MigratePartialFunction : SqliteFunction { public override object Invoke (object[] args) { string library_path = (string)args[0]; string filename_fragment = (string)args[1]; string full_path = Paths.Combine (library_path, filename_fragment); return SafeUri.FilenameToUri (full_path); } } }
#region License /* ********************************************************************************** * Copyright (c) Roman Ivantsov * This source code is subject to terms and conditions of the MIT License * for Irony. A copy of the license can be found in the License.txt file * at the root of this distribution. * By using this source code in any fashion, you are agreeing to be bound by the terms of the * MIT License. * You must not remove this notice from this software. * **********************************************************************************/ #endregion using System; using System.Collections.Generic; using System.Text; using System.Diagnostics; namespace Irony.Parsing { [Flags] public enum StringOptions : short { None = 0, IsChar = 0x01, AllowsDoubledQuote = 0x02, //Convert doubled start/end symbol to a single symbol; for ex. in SQL, '' -> ' AllowsLineBreak = 0x04, IsTemplate = 0x08, //Can include embedded expressions that should be evaluated on the fly; ex in Ruby: "hello #{name}" NoEscapes = 0x10, AllowsUEscapes = 0x20, AllowsXEscapes = 0x40, AllowsOctalEscapes = 0x80, AllowsAllEscapes = AllowsUEscapes | AllowsXEscapes | AllowsOctalEscapes, } //Container for settings of tempate string parser, to interpet strings having embedded values or expressions // like in Ruby: // "Hello, #{name}" // Default values match settings for Ruby strings public class StringTemplateSettings : Ast.AstNodeConfig { public string StartTag = "#{"; public string EndTag = "}"; public Type AstNodeType = typeof(Ast.StringTemplateNode); public NonTerminal ExpressionRoot; } public class StringLiteral : CompoundTerminalBase { public enum StringFlagsInternal : short { HasEscapes = 0x100, } #region StringSubType class StringSubType { internal readonly string Start, End; internal readonly StringOptions Flags; internal readonly byte Index; internal StringSubType(string start, string end, StringOptions flags, byte index) { Start = start; End = end; Flags = flags; Index = index; } internal static int LongerStartFirst(StringSubType x, StringSubType y) { try {//in case any of them is null if (x.Start.Length > y.Start.Length) return -1; } catch { } return 0; } } class StringSubTypeList : List<StringSubType> { internal void Add(string start, string end, StringOptions flags) { base.Add(new StringSubType(start, end, flags, (byte) this.Count)); } } #endregion #region constructors and initialization public StringLiteral(string name): base(name) { base.SetFlag(TermFlags.IsLiteral); base.AstNodeType = typeof(Irony.Ast.LiteralValueNode); } public StringLiteral(string name, string startEndSymbol, StringOptions stringOptions) : this(name) { _subtypes.Add(startEndSymbol, startEndSymbol, stringOptions); } public StringLiteral(string name, string startEndSymbol) : this(name, startEndSymbol, StringOptions.None) { } public StringLiteral(string name, string startEndSymbol, StringOptions options, Type astNodeType) : this(name, startEndSymbol, options) { base.AstNodeType = astNodeType; } public StringLiteral(string name, string startEndSymbol, StringOptions options, AstNodeCreator astNodeCreator) : this(name, startEndSymbol, options) { base.AstNodeCreator = astNodeCreator; } public void AddStartEnd(string startEndSymbol, StringOptions stringOptions) { AddStartEnd(startEndSymbol, startEndSymbol, stringOptions); } public void AddStartEnd(string startSymbol, string endSymbol, StringOptions stringOptions) { _subtypes.Add(startSymbol, endSymbol, stringOptions); } public void AddPrefix(string prefix, StringOptions flags) { base.AddPrefixFlag(prefix, (short)flags); } #endregion #region Properties/Fields private readonly StringSubTypeList _subtypes = new StringSubTypeList(); string _startSymbolsFirsts; //first chars of start-end symbols #endregion #region overrides: Init, GetFirsts, ReadBody, etc... public override void Init(GrammarData grammarData) { base.Init(grammarData); _startSymbolsFirsts = string.Empty; if (_subtypes.Count == 0) { grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrInvStrDef, this.Name); //"Error in string literal [{0}]: No start/end symbols specified." return; } //collect all start-end symbols in lists and create strings of first chars var allStartSymbols = new StringSet(); //to detect duplicate start symbols _subtypes.Sort(StringSubType.LongerStartFirst); bool isTemplate = false; foreach (StringSubType subType in _subtypes) { if (allStartSymbols.Contains(subType.Start)) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrDupStartSymbolStr, subType.Start, this.Name); //"Duplicate start symbol {0} in string literal [{1}]." allStartSymbols.Add(subType.Start); _startSymbolsFirsts += subType.Start[0].ToString(); if ((subType.Flags & StringOptions.IsTemplate) != 0) isTemplate = true; } if (!CaseSensitive) _startSymbolsFirsts = _startSymbolsFirsts.ToLower() + _startSymbolsFirsts.ToUpper(); //Set multiline flag foreach (StringSubType info in _subtypes) { if ((info.Flags & StringOptions.AllowsLineBreak) != 0) { SetFlag(TermFlags.IsMultiline); break; } } //For templates only if(isTemplate) { //Check that template settings object is provided var templateSettings = this.AstNodeConfig as StringTemplateSettings; if(templateSettings == null) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplNoSettings, this.Name); //"Error in string literal [{0}]: IsTemplate flag is set, but TemplateSettings is not provided." else if (templateSettings.ExpressionRoot == null) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplMissingExprRoot, this.Name); //"" else if(!Grammar.SnippetRoots.Contains(templateSettings.ExpressionRoot)) grammarData.Language.Errors.Add(GrammarErrorLevel.Error, null, Resources.ErrTemplExprNotRoot, this.Name); //"" }//if //Create editor info if (this.EditorInfo == null) this.EditorInfo = new TokenEditorInfo(TokenType.String, TokenColor.String, TokenTriggers.None); }//method public override IList<string> GetFirsts() { StringList result = new StringList(); result.AddRange(Prefixes); //we assume that prefix is always optional, so string can start with start-end symbol foreach (char ch in _startSymbolsFirsts) result.Add(ch.ToString()); return result; } protected override bool ReadBody(ISourceStream source, CompoundTokenDetails details) { if (!details.PartialContinues) { if (!ReadStartSymbol(source, details)) return false; } return CompleteReadBody(source, details); } private bool CompleteReadBody(ISourceStream source, CompoundTokenDetails details) { bool escapeEnabled = !details.IsSet((short) StringOptions.NoEscapes); int start = source.PreviewPosition; string endQuoteSymbol = details.EndSymbol; string endQuoteDoubled = endQuoteSymbol + endQuoteSymbol; //doubled quote symbol bool lineBreakAllowed = details.IsSet((short) StringOptions.AllowsLineBreak); //1. Find the string end // first get the position of the next line break; we are interested in it to detect malformed string, // therefore do it only if linebreak is NOT allowed; if linebreak is allowed, set it to -1 (we don't care). int nlPos = lineBreakAllowed ? -1 : source.Text.IndexOf('\n', source.PreviewPosition); //fix by ashmind for EOF right after opening symbol while (true) { int endPos = source.Text.IndexOf(endQuoteSymbol, source.PreviewPosition); //Check for partial token in line-scanning mode if (endPos < 0 && details.PartialOk && lineBreakAllowed) { ProcessPartialBody(source, details); return true; } //Check for malformed string: either EndSymbol not found, or LineBreak is found before EndSymbol bool malformed = endPos < 0 || nlPos >= 0 && nlPos < endPos; if (malformed) { //Set source position for recovery: move to the next line if linebreak is not allowed. if (nlPos > 0) endPos = nlPos; if (endPos > 0) source.PreviewPosition = endPos + 1; details.Error = Resources.ErrBadStrLiteral;// "Mal-formed string literal - cannot find termination symbol."; return true; //we did find start symbol, so it is definitely string, only malformed }//if malformed if (source.EOF()) return true; //We found EndSymbol - check if it is escaped; if yes, skip it and continue search if (escapeEnabled && IsEndQuoteEscaped(source.Text, endPos)) { source.PreviewPosition = endPos + endQuoteSymbol.Length; continue; //searching for end symbol } //Check if it is doubled end symbol source.PreviewPosition = endPos; if (details.IsSet((short)StringOptions.AllowsDoubledQuote) && source.MatchSymbol(endQuoteDoubled, !CaseSensitive)) { source.PreviewPosition = endPos + endQuoteDoubled.Length; continue; }//checking for doubled end symbol //Ok, this is normal endSymbol that terminates the string. // Advance source position and get out from the loop details.Body = source.Text.Substring(start, endPos - start); source.PreviewPosition = endPos + endQuoteSymbol.Length; return true; //if we come here it means we're done - we found string end. } //end of loop to find string end; } private void ProcessPartialBody(ISourceStream source, CompoundTokenDetails details) { int from = source.PreviewPosition; source.PreviewPosition = source.Text.Length; details.Body = source.Text.Substring(from, source.PreviewPosition - from); details.IsPartial = true; } protected override void InitDetails(ParsingContext context, CompoundTerminalBase.CompoundTokenDetails details) { base.InitDetails(context, details); if (context.VsLineScanState.Value != 0) { //we are continuing partial string on the next line details.Flags = context.VsLineScanState.TerminalFlags; details.SubTypeIndex = context.VsLineScanState.TokenSubType; var stringInfo = _subtypes[context.VsLineScanState.TokenSubType]; details.StartSymbol = stringInfo.Start; details.EndSymbol = stringInfo.End; } } protected override void ReadSuffix(ISourceStream source, CompoundTerminalBase.CompoundTokenDetails details) { base.ReadSuffix(source, details); //"char" type can be identified by suffix (like VB where c suffix identifies char) // in this case we have details.TypeCodes[0] == char and we need to set the IsChar flag if (details.TypeCodes != null && details.TypeCodes[0] == TypeCode.Char) details.Flags |= (int)StringOptions.IsChar; else //we may have IsChar flag set (from startEndSymbol, like in c# single quote identifies char) // in this case set type code if (details.IsSet((short) StringOptions.IsChar)) details.TypeCodes = new TypeCode[] { TypeCode.Char }; } private bool IsEndQuoteEscaped(string text, int quotePosition) { bool escaped = false; int p = quotePosition - 1; while (p > 0 && text[p] == EscapeChar) { escaped = !escaped; p--; } return escaped; } private bool ReadStartSymbol(ISourceStream source, CompoundTokenDetails details) { if (_startSymbolsFirsts.IndexOf(source.PreviewChar) < 0) return false; foreach (StringSubType subType in _subtypes) { if (!source.MatchSymbol(subType.Start, !CaseSensitive)) continue; //We found start symbol details.StartSymbol = subType.Start; details.EndSymbol = subType.End; details.Flags |= (short) subType.Flags; details.SubTypeIndex = subType.Index; source.PreviewPosition += subType.Start.Length; return true; }//foreach return false; }//method //Extract the string content from lexeme, adjusts the escaped and double-end symbols protected override bool ConvertValue(CompoundTokenDetails details) { string value = details.Body; bool escapeEnabled = !details.IsSet((short)StringOptions.NoEscapes); //Fix all escapes if (escapeEnabled && value.IndexOf(EscapeChar) >= 0) { details.Flags |= (int) StringFlagsInternal.HasEscapes; string[] arr = value.Split(EscapeChar); bool ignoreNext = false; //we skip the 0 element as it is not preceeded by "\" for (int i = 1; i < arr.Length; i++) { if (ignoreNext) { ignoreNext = false; continue; } string s = arr[i]; if (string.IsNullOrEmpty(s)) { //it is "\\" - escaped escape symbol. arr[i] = @"\"; ignoreNext = true; continue; } //The char is being escaped is the first one; replace it with char in Escapes table char first = s[0]; char newFirst; if (Escapes.TryGetValue(first, out newFirst)) arr[i] = newFirst + s.Substring(1); else { arr[i] = HandleSpecialEscape(arr[i], details); }//else }//for i value = string.Join(string.Empty, arr); }// if EscapeEnabled //Check for doubled end symbol string endSymbol = details.EndSymbol; if (details.IsSet((short)StringOptions.AllowsDoubledQuote) && value.IndexOf(endSymbol) >= 0) value = value.Replace(endSymbol + endSymbol, endSymbol); if (details.IsSet((short)StringOptions.IsChar)) { if (value.Length != 1) { details.Error = Resources.ErrBadChar; //"Invalid length of char literal - should be a single character."; return false; } details.Value = value[0]; } else { details.TypeCodes = new TypeCode[] { TypeCode.String }; details.Value = value; } return true; } //Should support: \Udddddddd, \udddd, \xdddd, \N{name}, \0, \ddd (octal), protected virtual string HandleSpecialEscape(string segment, CompoundTokenDetails details) { if (string.IsNullOrEmpty(segment)) return string.Empty; int len, p; string digits; char ch; string result; char first = segment[0]; switch (first) { case 'u': case 'U': if (details.IsSet((short)StringOptions.AllowsUEscapes)) { len = (first == 'u' ? 4 : 8); if (segment.Length < len + 1) { details.Error = string.Format(Resources.ErrBadUnEscape, segment.Substring(len + 1), len);// "Invalid unicode escape ({0}), expected {1} hex digits." return segment; } digits = segment.Substring(1, len); ch = (char) Convert.ToUInt32(digits, 16); result = ch + segment.Substring(len + 1); return result; }//if break; case 'x': if (details.IsSet((short)StringOptions.AllowsXEscapes)) { //x-escape allows variable number of digits, from one to 4; let's count them p = 1; //current position while (p < 5 && p < segment.Length) { if (Strings.HexDigits.IndexOf(segment[p]) < 0) break; p++; } //p now point to char right after the last digit if (p <= 1) { details.Error = Resources.ErrBadXEscape; // @"Invalid \x escape, at least one digit expected."; return segment; } digits = segment.Substring(1, p - 1); ch = (char) Convert.ToUInt32(digits, 16); result = ch + segment.Substring(p); return result; }//if break; case '0': case '1': case '2': case '3': case '4': case '5': case '6': case '7': if (details.IsSet((short)StringOptions.AllowsOctalEscapes)) { //octal escape allows variable number of digits, from one to 3; let's count them p = 0; //current position while (p < 3 && p < segment.Length) { if (Strings.OctalDigits.IndexOf(segment[p]) < 0) break; p++; } //p now point to char right after the last digit digits = segment.Substring(0, p); ch = (char)Convert.ToUInt32(digits, 8); result = ch + segment.Substring(p); return result; }//if break; }//switch details.Error = string.Format(Resources.ErrInvEscape, segment); //"Invalid escape sequence: \{0}" return segment; }//method #endregion //Override method to provide different node type for string templates protected override Type GetAstNodeType(ParsingContext context, ParseTreeNode nodeInfo) { var details = nodeInfo.Token.Details as CompoundTokenDetails; //check that IsTemplate flag is set and that the string actually contains embedded expression(s) by checking the start tag var isTemplate = details != null && details.IsSet((short) StringOptions.IsTemplate); if (isTemplate) { var templateSettings = this.AstNodeConfig as StringTemplateSettings; isTemplate &= nodeInfo.Token.ValueString.Contains(templateSettings.StartTag); if (isTemplate) return templateSettings.AstNodeType; } //otherwise return default type from base method return base.GetAstNodeType(context, nodeInfo); }//method }//class }//namespace
using System; using System.Globalization; using Eto.Drawing; #if XAMMAC2 using AppKit; using Foundation; using CoreGraphics; using ObjCRuntime; using CoreAnimation; using CoreImage; #elif OSX using MonoMac.AppKit; using MonoMac.Foundation; using MonoMac.CoreGraphics; using MonoMac.ObjCRuntime; using MonoMac.CoreAnimation; using MonoMac.CoreImage; #if Mac64 using CGSize = MonoMac.Foundation.NSSize; using CGRect = MonoMac.Foundation.NSRect; using CGPoint = MonoMac.Foundation.NSPoint; using nfloat = System.Double; using nint = System.Int64; using nuint = System.UInt64; #else using CGSize = System.Drawing.SizeF; using CGRect = System.Drawing.RectangleF; using CGPoint = System.Drawing.PointF; using nfloat = System.Single; using nint = System.Int32; using nuint = System.UInt32; #endif #endif #if IOS using UIKit; using Foundation; using NSFont = UIKit.UIFont; namespace Eto.iOS.Drawing #elif OSX namespace Eto.Mac.Drawing #endif { public class FontHandler : WidgetHandler<NSFont, Font>, Font.IHandler { FontFamily family; FontTypeface typeface; FontStyle? style; FontDecoration decoration; NSDictionary _attributes; public FontHandler() { } public FontHandler(NSFont font) { Control = font; } public FontHandler(NSFont font, FontStyle style) { Control = font; this.style = style; } public void Create(FontTypeface face, float size, FontDecoration decoration) { typeface = face; family = face.Family; Control = ((FontTypefaceHandler)face.Handler).CreateFont(size); this.decoration = decoration; } public void Create(SystemFont systemFont, float? fontSize, FontDecoration decoration) { switch (systemFont) { case SystemFont.Default: Control = NSFont.SystemFontOfSize((nfloat)(fontSize ?? (float)NSFont.SystemFontSize)); break; case SystemFont.Bold: Control = NSFont.BoldSystemFontOfSize((nfloat)(fontSize ?? (float)NSFont.SystemFontSize)); break; case SystemFont.Label: #if IOS Control = NSFont.SystemFontOfSize(fontSize ?? NSFont.LabelFontSize); #elif OSX Control = NSFont.LabelFontOfSize((nfloat)(fontSize ?? (float)(NSFont.LabelFontSize + 2))); // labels get a size of 12 #endif break; #if OSX case SystemFont.TitleBar: Control = NSFont.TitleBarFontOfSize((nfloat)(fontSize ?? (float)NSFont.SystemFontSize)); break; case SystemFont.ToolTip: Control = NSFont.ToolTipsFontOfSize((nfloat)(fontSize ?? (float)NSFont.SystemFontSize)); break; case SystemFont.MenuBar: Control = NSFont.MenuBarFontOfSize((nfloat)(fontSize ?? (float)NSFont.SystemFontSize)); break; case SystemFont.Menu: Control = NSFont.MenuFontOfSize((nfloat)(fontSize ?? (float)NSFont.SystemFontSize)); break; case SystemFont.Message: Control = NSFont.MessageFontOfSize((nfloat)(fontSize ?? (float)NSFont.SystemFontSize)); break; case SystemFont.Palette: Control = NSFont.PaletteFontOfSize((nfloat)(fontSize ?? (float)NSFont.SmallSystemFontSize)); break; case SystemFont.StatusBar: Control = NSFont.SystemFontOfSize((nfloat)(fontSize ?? (float)NSFont.SystemFontSize)); break; #endif default: throw new NotSupportedException(); } this.decoration = decoration; } public float LineHeight { get { return Control.LineHeight(); // LineHeight() is the extension method above } } #if OSX NSFontTraitMask? traits; public static NSFont CreateFont(FontFamilyHandler familyHandler, float size, NSFontTraitMask traits, int weight = 5) { var font = NSFontManager.SharedFontManager.FontWithFamily(familyHandler.MacName, traits, weight, size); if (font == null) { if (traits.HasFlag(NSFontTraitMask.Italic)) { // fake italics by transforming the font const float kRotationForItalicText = 14.0f; var fontTransform = new NSAffineTransform(); fontTransform.Scale(size); var italicTransform = new NSAffineTransform(); italicTransform.TransformStruct = Matrix.FromSkew(0, kRotationForItalicText).ToCG(); fontTransform.AppendTransform(italicTransform); traits &= ~NSFontTraitMask.Italic; font = NSFontManager.SharedFontManager.FontWithFamily(familyHandler.MacName, traits, 5, size); if (font != null) { font = NSFont.FromDescription(font.FontDescriptor, fontTransform); } } } return font; } #endif public void Create(FontFamily family, float size, FontStyle style, FontDecoration decoration) { this.style = style; this.family = family; this.decoration = decoration; #if OSX var familyHandler = (FontFamilyHandler)family.Handler; traits = style.ToNS() & familyHandler.TraitMask; var font = CreateFont(familyHandler, size, traits.Value); if (font == null || font.Handle == IntPtr.Zero) throw new ArgumentOutOfRangeException(string.Empty, string.Format(CultureInfo.CurrentCulture, "Could not allocate font with family {0}, traits {1}, size {2}", family.Name, traits, size)); #elif IOS var familyHandler = (FontFamilyHandler)family.Handler; var font = familyHandler.CreateFont (size, style); /* var familyString = new StringBuilder(); switch (family) { case FontFamily.Monospace: familyString.Append ("CourierNewPS"); suffix = "MT"; break; default: case FontFamily.Sans: familyString.Append ("Helvetica"); italicString = "Oblique"; break; case FontFamily.Serif: familyString.Append ("TimesNewRomanPS"); suffix = "MT"; break; } bold = (style & FontStyle.Bold) != 0; italic = (style & FontStyle.Italic) != 0; if (bold || italic) familyString.Append ("-"); if (bold) familyString.Append ("Bold"); if (italic) familyString.Append (italicString); familyString.Append (suffix); var font = UIFont.FromName (familyString.ToString (), size); */ #endif Control = font; } public float Size { get { return (float)Control.PointSize; } } public string FamilyName { get { return Control.FamilyName; } } public FontFamily Family { get { if (family == null) family = new FontFamily(new FontFamilyHandler(Control.FamilyName)); return family; } } public FontTypeface Typeface { get { if (typeface == null) #if IOS typeface = ((FontFamilyHandler)Family.Handler).GetFace(Control); #else typeface = ((FontFamilyHandler)Family.Handler).GetFace(Control, traits); #endif return typeface; } } public FontStyle FontStyle { get { if (style == null) #if OSX style = NSFontManager.SharedFontManager.TraitsOfFont(Control).ToEto(); #elif IOS style = Typeface.FontStyle; #endif return style.Value; } } public FontDecoration FontDecoration { get { return decoration; } } public float Ascent { get { return (float)Control.Ascender; } } public float Descent { get { return (float)-Control.Descender; } } public float XHeight { #if OSX get { return (float)Control.XHeight; } #elif IOS get { return (float)Control.xHeight; } #endif } public float Leading { get { return (float)Control.Leading; } } public float Baseline { get { return Control.LineHeight() - Leading - Descent; } } public NSDictionary Attributes { get { if (_attributes == null) CreateAttributes(); return _attributes ?? (_attributes = CreateAttributes()); } } static readonly NSObject[] attributeKeys = { #if OSX #if __UNIFIED__ NSStringAttributeKey.Font, NSStringAttributeKey.UnderlineStyle, NSStringAttributeKey.StrikethroughStyle #else NSAttributedString.FontAttributeName, NSAttributedString.UnderlineStyleAttributeName, NSAttributedString.StrikethroughStyleAttributeName #endif #elif IOS UIStringAttributeKey.Font, UIStringAttributeKey.UnderlineStyle, UIStringAttributeKey.StrikethroughStyle #endif }; NSDictionary CreateAttributes() { return NSDictionary.FromObjectsAndKeys( new NSObject[] { Control, new NSNumber((int)(decoration.HasFlag(FontDecoration.Underline) ? NSUnderlineStyle.Single : NSUnderlineStyle.None)), NSNumber.FromBoolean(decoration.HasFlag(FontDecoration.Strikethrough)) }, attributeKeys ); } } }
// Copyright (c) 2010-2014 SharpDX - Alexandre Mutel // // 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.Diagnostics; using System.Reflection; using System.Text; using SharpDX.Collections; namespace SharpDX.Diagnostics { /// <summary> /// Event args for <see cref="ComObject"/> used by <see cref="ObjectTracker"/>. /// </summary> public class ComObjectEventArgs : EventArgs { /// <summary> /// The object being tracked/untracked. /// </summary> public ComObject Object; /// <summary> /// Initializes a new instance of the <see cref="ComObjectEventArgs"/> class. /// </summary> /// <param name="o">The o.</param> public ComObjectEventArgs(ComObject o) { Object = o; } } /// <summary> /// Track all allocated objects. /// </summary> public static class ObjectTracker { private static Dictionary<IntPtr, List<ObjectReference>> processGlobalObjectReferences; [ThreadStatic] private static Dictionary<IntPtr, List<ObjectReference>> threadStaticObjectReferences; /// <summary> /// Occurs when a ComObject is tracked. /// </summary> public static event EventHandler<ComObjectEventArgs> Tracked; /// <summary> /// Occurs when a ComObject is untracked. /// </summary> public static event EventHandler<ComObjectEventArgs> UnTracked; #if !W8CORE /// <summary> /// Initializes the <see cref="ObjectTracker"/> class. /// </summary> static ObjectTracker() { AppDomain.CurrentDomain.DomainUnload += OnProcessExit; AppDomain.CurrentDomain.ProcessExit += OnProcessExit; } /// <summary> /// Called when [process exit]. /// </summary> /// <param name="sender">The sender.</param> /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param> static void OnProcessExit(object sender, EventArgs e) { if (Configuration.EnableObjectTracking) { var text = ReportActiveObjects(); if (!string.IsNullOrEmpty(text)) Console.WriteLine(text); } } #endif private static Dictionary<IntPtr, List<ObjectReference>> ObjectReferences { get { Dictionary<IntPtr, List<ObjectReference>> objectReferences; if (Configuration.UseThreadStaticObjectTracking) { if (threadStaticObjectReferences == null) threadStaticObjectReferences = new Dictionary<IntPtr, List<ObjectReference>>(EqualityComparer.DefaultIntPtr); objectReferences = threadStaticObjectReferences; } else { if (processGlobalObjectReferences == null) processGlobalObjectReferences = new Dictionary<IntPtr, List<ObjectReference>>(EqualityComparer.DefaultIntPtr); objectReferences = processGlobalObjectReferences; } return objectReferences; } } /// <summary> /// Tracks the specified COM object. /// </summary> /// <param name="comObject">The COM object.</param> public static void Track(ComObject comObject) { if (comObject == null || comObject.NativePointer == IntPtr.Zero) return; lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (!ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { referenceList = new List<ObjectReference>(); ObjectReferences.Add(comObject.NativePointer, referenceList); } #if W8CORE var stacktrace = "Stacktrace is not available on this platform"; // This code is a workaround to be able to get a full stacktrace on Windows Store App. // This is an unsafe code, that should not run on production. Only at dev time! // Make sure we are on a 32bit process if(IntPtr.Size == 4) { // Get an access to a restricted method try { var stackTraceGetMethod = typeof(Environment).GetRuntimeProperty("StackTrace").GetMethod; try { // First try to get the stacktrace stacktrace = (string)stackTraceGetMethod.Invoke(null, null); } catch(Exception ex) { // If we have an exception, it means that the access to the method is not possible // so we are going to patch the field RuntimeMethodInfo.m_invocationFlags that should contain // 0x41 (initialized + security), and replace it by 0x1 (initialized) // and then callback again the method unsafe { // unsafe code, the RuntimeMethodInfo could be relocated (is it a real managed GC object?), // but we don't have much choice var addr = *(int**)Interop.Fixed(ref stackTraceGetMethod); // offset to RuntimeMethodInfo.m_invocationFlags addr += 13; // Check if we have the expecting value if(*addr == 0x41) { // if yes, change it to 0x1 *addr = 0x1; try { // And try to callit again a second time // if it succeeds, first Invoke() should run on next call stacktrace = (string)stackTraceGetMethod.Invoke(null, null); } catch(Exception ex2) { // if it is still failing, we can't do anything } } } } } catch(Exception ex) { // can't do anything } } referenceList.Add(new ObjectReference(DateTime.Now, comObject, stacktrace)); #else var stackTraceText = new StringBuilder(); var stackTrace = new StackTrace(3, true); foreach (var stackFrame in stackTrace.GetFrames()) { // Skip system/generated frame if (stackFrame.GetFileLineNumber() == 0) continue; stackTraceText.AppendFormat(System.Globalization.CultureInfo.InvariantCulture, "\t{0}({1},{2}) : {3}", stackFrame.GetFileName(), stackFrame.GetFileLineNumber(), stackFrame.GetFileColumnNumber(), stackFrame.GetMethod()).AppendLine(); } referenceList.Add(new ObjectReference(DateTime.Now, comObject, stackTraceText.ToString())); #endif // Fire Tracked event. OnTracked(comObject); } } /// <summary> /// Finds a list of object reference from a specified COM object pointer. /// </summary> /// <param name="comObjectPtr">The COM object pointer.</param> /// <returns>A list of object reference</returns> public static List<ObjectReference> Find(IntPtr comObjectPtr) { lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObjectPtr, out referenceList)) return new List<ObjectReference>(referenceList); } return new List<ObjectReference>(); } /// <summary> /// Finds the object reference for a specific COM object. /// </summary> /// <param name="comObject">The COM object.</param> /// <returns>An object reference</returns> public static ObjectReference Find(ComObject comObject) { lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { foreach (var objectReference in referenceList) { if (ReferenceEquals(objectReference.Object.Target, comObject)) return objectReference; } } } return null; } /// <summary> /// Untracks the specified COM object. /// </summary> /// <param name="comObject">The COM object.</param> public static void UnTrack(ComObject comObject) { if (comObject == null || comObject.NativePointer == IntPtr.Zero) return; lock (ObjectReferences) { List<ObjectReference> referenceList; // Object is already tracked if (ObjectReferences.TryGetValue(comObject.NativePointer, out referenceList)) { for (int i = referenceList.Count-1; i >=0; i--) { var objectReference = referenceList[i]; if (ReferenceEquals(objectReference.Object.Target, comObject)) referenceList.RemoveAt(i); else if (!objectReference.IsAlive) referenceList.RemoveAt(i); } // Remove empty list if (referenceList.Count == 0) ObjectReferences.Remove(comObject.NativePointer); // Fire UnTracked event OnUnTracked(comObject); } } } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> public static List<ObjectReference> FindActiveObjects() { var activeObjects = new List<ObjectReference>(); lock (ObjectReferences) { foreach (var referenceList in ObjectReferences.Values) { foreach (var objectReference in referenceList) { if (objectReference.IsAlive) activeObjects.Add(objectReference); } } } return activeObjects; } /// <summary> /// Reports all COM object that are active and not yet disposed. /// </summary> public static string ReportActiveObjects() { var text = new StringBuilder(); int count = 0; var countPerType = new Dictionary<string, int>(); foreach (var findActiveObject in FindActiveObjects()) { var findActiveObjectStr = findActiveObject.ToString(); if (!string.IsNullOrEmpty(findActiveObjectStr)) { text.AppendFormat("[{0}]: {1}", count, findActiveObjectStr); var target = findActiveObject.Object.Target; if (target != null) { int typeCount; var targetType = target.GetType().Name; if (!countPerType.TryGetValue(targetType, out typeCount)) { countPerType[targetType] = 0; } countPerType[targetType] = typeCount + 1; } } count++; } var keys = new List<string>(countPerType.Keys); keys.Sort(); text.AppendLine(); text.AppendLine("Count per Type:"); foreach (var key in keys) { text.AppendFormat("{0} : {1}", key, countPerType[key]); text.AppendLine(); } return text.ToString(); } private static void OnTracked(ComObject obj) { var handler = Tracked; if (handler != null) { handler(null, new ComObjectEventArgs(obj)); } } private static void OnUnTracked(ComObject obj) { var handler = UnTracked; if (handler != null) { handler(null, new ComObjectEventArgs(obj)); } } } }
using System; using Server.Network; using Server.Engines.Craft; namespace Server.Items { public class BaseQuiver : Container, ICraftable { public override int DefaultGumpID{ get{ return 0x108; } } public override int DefaultMaxItems{ get{ return 1; } } public override int DefaultMaxWeight{ get{ return 50; } } public override double DefaultWeight{ get{ return 2.0; } } private AosAttributes m_Attributes; private int m_Capacity; private int m_LowerAmmoCost; private int m_WeightReduction; private int m_DamageIncrease; [CommandProperty( AccessLevel.GameMaster)] public AosAttributes Attributes { get{ return m_Attributes; } set{} } [CommandProperty( AccessLevel.GameMaster)] public int Capacity { get{ return m_Capacity; } set{ m_Capacity = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster)] public int LowerAmmoCost { get{ return m_LowerAmmoCost; } set{ m_LowerAmmoCost = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster)] public int WeightReduction { get{ return m_WeightReduction; } set{ m_WeightReduction = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster)] public int DamageIncrease { get{ return m_DamageIncrease; } set{ m_DamageIncrease = value; InvalidateProperties(); } } private Mobile m_Crafter; private ClothingQuality m_Quality; [CommandProperty( AccessLevel.GameMaster )] public Mobile Crafter { get{ return m_Crafter; } set{ m_Crafter = value; InvalidateProperties(); } } [CommandProperty( AccessLevel.GameMaster )] public ClothingQuality Quality { get{ return m_Quality; } set{ m_Quality = value; InvalidateProperties(); } } public Item Ammo { get{ return Items.Count > 0 ? Items[ 0 ] : null; } } public BaseQuiver() : this( 0x2FB7 ) { } public BaseQuiver( int itemID ) : base( itemID ) { Weight = 2.0; Capacity = 500; Layer = Layer.Cloak; m_Attributes = new AosAttributes( this ); DamageIncrease = 10; } public BaseQuiver( Serial serial ) : base( serial ) { } public override void OnAfterDuped( Item newItem ) { BaseQuiver quiver = newItem as BaseQuiver; if ( quiver == null ) return; quiver.m_Attributes = new AosAttributes( newItem, m_Attributes ); } public override void UpdateTotal( Item sender, TotalType type, int delta ) { InvalidateProperties(); base.UpdateTotal(sender, type, delta); } public override int GetTotal( TotalType type ) { int total = base.GetTotal( type ); if ( type == TotalType.Weight ) total -= total * m_WeightReduction / 100; return total; } private static Type[] m_Ammo = new Type[] { typeof( Arrow ), typeof( Bolt ) }; public bool CheckType( Item item ) { Type type = item.GetType(); Item ammo = Ammo; if ( ammo != null ) { if ( ammo.GetType() == type ) return true; } else { for ( int i = 0; i < m_Ammo.Length; i++ ) { if ( type == m_Ammo[ i ] ) return true; } } return false; } public override bool CheckHold( Mobile m, Item item, bool message, bool checkItems, int plusItems, int plusWeight ) { if ( !CheckType( item ) ) { if ( message ) m.SendLocalizedMessage( 1074836 ); // The container can not hold that type of object. return false; } if ( Items.Count < DefaultMaxItems ) { if ( item.Amount <= m_Capacity ) return base.CheckHold( m, item, message, checkItems, plusItems, plusWeight ); return false; } else if ( checkItems ) return false; Item ammo = Ammo; if ( ammo == null || ammo.Deleted ) return false; if ( ammo.Amount + item.Amount <= m_Capacity ) return true; return false; } public override void AddItem( Item dropped ) { base.AddItem( dropped ); InvalidateWeight(); } public override void RemoveItem( Item dropped ) { base.RemoveItem( dropped ); InvalidateWeight(); } public override void OnAdded( object parent ) { if ( parent is Mobile ) { Mobile mob = (Mobile) parent; m_Attributes.AddStatBonuses( mob ); } } public override void OnRemoved( object parent ) { if ( parent is Mobile ) { Mobile mob = (Mobile) parent; m_Attributes.RemoveStatBonuses( mob ); } } public override void GetProperties( ObjectPropertyList list ) { base.GetProperties( list ); if ( m_Crafter != null ) list.Add( 1050043, m_Crafter.Name ); // crafted by ~1_NAME~ if ( m_Quality == ClothingQuality.Exceptional ) list.Add( 1063341 ); // exceptional Item ammo = Ammo; if ( ammo != null ) { if ( ammo is Arrow ) list.Add( 1075265, "{0}\t{1}", ammo.Amount, Capacity ); // Ammo: ~1_QUANTITY~/~2_CAPACITY~ arrows else if ( ammo is Bolt ) list.Add( 1075266, "{0}\t{1}", ammo.Amount, Capacity ); // Ammo: ~1_QUANTITY~/~2_CAPACITY~ bolts } else list.Add( 1075265, "{0}\t{1}", 0, Capacity ); // Ammo: ~1_QUANTITY~/~2_CAPACITY~ arrows int prop; if ( (prop = m_DamageIncrease) != 0 ) list.Add( 1074762, prop.ToString() ); // Damage modifier: ~1_PERCENT~% int phys, fire, cold, pois, nrgy, chaos, direct; phys = fire = cold = pois = nrgy = chaos = direct = 0; AlterBowDamage( ref phys, ref fire, ref cold, ref pois, ref nrgy, ref chaos, ref direct ); if ( phys != 0 ) list.Add( 1060403, phys.ToString() ); // physical damage ~1_val~% if ( fire != 0 ) list.Add( 1060405, fire.ToString() ); // fire damage ~1_val~% if ( cold != 0 ) list.Add( 1060404, cold.ToString() ); // cold damage ~1_val~% if ( pois != 0 ) list.Add( 1060406, pois.ToString() ); // poison damage ~1_val~% if ( nrgy != 0 ) list.Add( 1060407, nrgy.ToString() ); // energy damage ~1_val if ( chaos != 0 ) list.Add( 1072846, chaos.ToString() ); // chaos damage ~1_val~% if ( direct != 0 ) list.Add( 1079978, direct.ToString() ); // Direct Damage: ~1_PERCENT~% list.Add( 1075085 ); // Requirement: Mondain's Legacy if ( (prop = m_Attributes.DefendChance) != 0 ) list.Add( 1060408, prop.ToString() ); // defense chance increase ~1_val~% if ( (prop = m_Attributes.BonusDex) != 0 ) list.Add( 1060409, prop.ToString() ); // dexterity bonus ~1_val~ if ( (prop = m_Attributes.EnhancePotions) != 0 ) list.Add( 1060411, prop.ToString() ); // enhance potions ~1_val~% if ( (prop = m_Attributes.CastRecovery) != 0 ) list.Add( 1060412, prop.ToString() ); // faster cast recovery ~1_val~ if ( (prop = m_Attributes.CastSpeed) != 0 ) list.Add( 1060413, prop.ToString() ); // faster casting ~1_val~ if ( (prop = m_Attributes.AttackChance) != 0 ) list.Add( 1060415, prop.ToString() ); // hit chance increase ~1_val~% if ( (prop = m_Attributes.BonusHits) != 0 ) list.Add( 1060431, prop.ToString() ); // hit point increase ~1_val~ if ( (prop = m_Attributes.BonusInt) != 0 ) list.Add( 1060432, prop.ToString() ); // intelligence bonus ~1_val~ if ( (prop = m_Attributes.LowerManaCost) != 0 ) list.Add( 1060433, prop.ToString() ); // lower mana cost ~1_val~% if ( (prop = m_Attributes.LowerRegCost) != 0 ) list.Add( 1060434, prop.ToString() ); // lower reagent cost ~1_val~% if ( (prop = m_Attributes.Luck) != 0 ) list.Add( 1060436, prop.ToString() ); // luck ~1_val~ if ( (prop = m_Attributes.BonusMana) != 0 ) list.Add( 1060439, prop.ToString() ); // mana increase ~1_val~ if ( (prop = m_Attributes.RegenMana) != 0 ) list.Add( 1060440, prop.ToString() ); // mana regeneration ~1_val~ if ( (prop = m_Attributes.NightSight) != 0 ) list.Add( 1060441 ); // night sight if ( (prop = m_Attributes.ReflectPhysical) != 0 ) list.Add( 1060442, prop.ToString() ); // reflect physical damage ~1_val~% if ( (prop = m_Attributes.RegenStam) != 0 ) list.Add( 1060443, prop.ToString() ); // stamina regeneration ~1_val~ if ( (prop = m_Attributes.RegenHits) != 0 ) list.Add( 1060444, prop.ToString() ); // hit point regeneration ~1_val~ if ( (prop = m_Attributes.SpellDamage) != 0 ) list.Add( 1060483, prop.ToString() ); // spell damage increase ~1_val~% if ( (prop = m_Attributes.BonusStam) != 0 ) list.Add( 1060484, prop.ToString() ); // stamina increase ~1_val~ if ( (prop = m_Attributes.BonusStr) != 0 ) list.Add( 1060485, prop.ToString() ); // strength bonus ~1_val~ if ( (prop = m_Attributes.WeaponSpeed) != 0 ) list.Add( 1060486, prop.ToString() ); // swing speed increase ~1_val~% if ( (prop = m_LowerAmmoCost) > 0 ) list.Add( 1075208, prop.ToString() ); // Lower Ammo Cost ~1_Percentage~% double weight = 0; if ( ammo != null ) weight = ammo.Weight * ammo.Amount; list.Add( 1072241, "{0}\t{1}\t{2}\t{3}", Items.Count, DefaultMaxItems, (int) weight, DefaultMaxWeight ); // Contents: ~1_COUNT~/~2_MAXCOUNT items, ~3_WEIGHT~/~4_MAXWEIGHT~ stones if ( (prop = m_WeightReduction) != 0 ) list.Add( 1072210, prop.ToString() ); // Weight reduction: ~1_PERCENTAGE~% } private static void SetSaveFlag( ref SaveFlag flags, SaveFlag toSet, bool setIf ) { if ( setIf ) flags |= toSet; } private static bool GetSaveFlag( SaveFlag flags, SaveFlag toGet ) { return ( (flags & toGet) != 0 ); } [Flags] private enum SaveFlag { None = 0x00000000, Attributes = 0x00000001, DamageModifier = 0x00000002, LowerAmmoCost = 0x00000004, WeightReduction = 0x00000008, Crafter = 0x00000010, Quality = 0x00000020, Capacity = 0x00000040, DamageIncrease = 0x00000080 } public override void Serialize( GenericWriter writer ) { base.Serialize( writer ); writer.Write( 0 ); // version SaveFlag flags = SaveFlag.None; SetSaveFlag( ref flags, SaveFlag.Attributes, !m_Attributes.IsEmpty ); SetSaveFlag( ref flags, SaveFlag.LowerAmmoCost, m_LowerAmmoCost != 0 ); SetSaveFlag( ref flags, SaveFlag.WeightReduction, m_WeightReduction != 0 ); SetSaveFlag( ref flags, SaveFlag.DamageIncrease, m_DamageIncrease != 0 ); SetSaveFlag( ref flags, SaveFlag.Crafter, m_Crafter != null ); SetSaveFlag( ref flags, SaveFlag.Quality, true ); SetSaveFlag( ref flags, SaveFlag.Capacity, m_Capacity > 0 ); writer.WriteEncodedInt( (int) flags ); if ( GetSaveFlag( flags, SaveFlag.Attributes ) ) m_Attributes.Serialize( writer ); if ( GetSaveFlag( flags, SaveFlag.LowerAmmoCost ) ) writer.Write( (int) m_LowerAmmoCost ); if ( GetSaveFlag( flags, SaveFlag.WeightReduction ) ) writer.Write( (int) m_WeightReduction ); if ( GetSaveFlag( flags, SaveFlag.DamageIncrease ) ) writer.Write( (int) m_DamageIncrease ); if ( GetSaveFlag( flags, SaveFlag.Crafter ) ) writer.Write( (Mobile) m_Crafter ); if ( GetSaveFlag( flags, SaveFlag.Quality ) ) writer.Write( (int) m_Quality ); if ( GetSaveFlag( flags, SaveFlag.Capacity ) ) writer.Write( (int) m_Capacity ); } public override void Deserialize( GenericReader reader ) { base.Deserialize( reader ); int version = reader.ReadInt(); SaveFlag flags = (SaveFlag) reader.ReadEncodedInt(); if ( GetSaveFlag( flags, SaveFlag.Attributes ) ) m_Attributes = new AosAttributes( this, reader ); else m_Attributes = new AosAttributes( this ); if ( GetSaveFlag( flags, SaveFlag.LowerAmmoCost ) ) m_LowerAmmoCost = reader.ReadInt(); if ( GetSaveFlag( flags, SaveFlag.WeightReduction ) ) m_WeightReduction = reader.ReadInt(); if ( GetSaveFlag( flags, SaveFlag.DamageIncrease ) ) m_DamageIncrease = reader.ReadInt(); if ( GetSaveFlag( flags, SaveFlag.Crafter ) ) m_Crafter = reader.ReadMobile(); if ( GetSaveFlag( flags, SaveFlag.Quality ) ) m_Quality = (ClothingQuality) reader.ReadInt(); if ( GetSaveFlag( flags, SaveFlag.Capacity ) ) m_Capacity = reader.ReadInt(); } public virtual void AlterBowDamage( ref int phys, ref int fire, ref int cold, ref int pois, ref int nrgy, ref int chaos, ref int direct ) { } public void InvalidateWeight() { if ( RootParent is Mobile ) { Mobile m = (Mobile) RootParent; m.UpdateTotals(); } } #region ICraftable public virtual int OnCraft( int quality, bool makersMark, Mobile from, CraftSystem craftSystem, Type typeRes, BaseTool tool, CraftItem craftItem, int resHue ) { Quality = (ClothingQuality) quality; if ( makersMark ) Crafter = from; return quality; } #endregion } }
using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings; using Microsoft.CodeAnalysis.Options; using Microsoft.CodeAnalysis.ReplacePropertyWithMethods; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeActions.ReplacePropertyWithMethods { public class ReplacePropertyWithMethodsTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new ReplacePropertyWithMethodsCodeRefactoringProvider(); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestGetWithBody() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get { return 0; } } }", @"class C { private int GetProp() { return 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestPublicProperty() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get { return 0; } } }", @"class C { public int GetProp() { return 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestAnonyousType1() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get { return 0; } } public void M() { var v = new { P = this.Prop } } }", @"class C { public int GetProp() { return 0; } public void M() { var v = new { P = this.GetProp() } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestAnonyousType2() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get { return 0; } } public void M() { var v = new { this.Prop } } }", @"class C { public int GetProp() { return 0; } public void M() { var v = new { Prop = this.GetProp() } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestPassedToRef1() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get { return 0; } } public void RefM(ref int i) { } public void M() { RefM(ref this.Prop); } }", @"class C { public int GetProp() { return 0; } public void RefM(ref int i) { } public void M() { RefM(ref this.{|Conflict:GetProp|}()); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestPassedToOut1() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get { return 0; } } public void OutM(out int i) { } public void M() { OutM(out this.Prop); } }", @"class C { public int GetProp() { return 0; } public void OutM(out int i) { } public void M() { OutM(out this.{|Conflict:GetProp|}()); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestUsedInAttribute1() { await TestInRegularAndScriptAsync( @"using System; class CAttribute : Attribute { public int [||]Prop { get { return 0; } } } [C(Prop = 1)] class D { }", @"using System; class CAttribute : Attribute { public int GetProp() { return 0; } } [C({|Conflict:Prop|} = 1)] class D { }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestSetWithBody1() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { set { var v = value; } } }", @"class C { private void SetProp(int value) { var v = value; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestSetReference1() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { set { var v = value; } } void M() { this.Prop = 1; } }", @"class C { private void SetProp(int value) { var v = value; } void M() { this.SetProp(1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestGetterAndSetter() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get { return 0; } set { var v = value; } } }", @"class C { private int GetProp() { return 0; } private void SetProp(int value) { var v = value; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestGetterAndSetterAccessibilityChange() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get { return 0; } private set { var v = value; } } }", @"class C { public int GetProp() { return 0; } private void SetProp(int value) { var v = value; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestIncrement1() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get { return 0; } set { var v = value; } } void M() { this.Prop++; } }", @"class C { private int GetProp() { return 0; } private void SetProp(int value) { var v = value; } void M() { this.SetProp(this.GetProp() + 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestDecrement2() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get { return 0; } set { var v = value; } } void M() { this.Prop--; } }", @"class C { private int GetProp() { return 0; } private void SetProp(int value) { var v = value; } void M() { this.SetProp(this.GetProp() - 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestRecursiveGet() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get { return this.Prop + 1; } } }", @"class C { private int GetProp() { return this.GetProp() + 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestRecursiveSet() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { set { this.Prop = value + 1; } } }", @"class C { private void SetProp(int value) { this.SetProp(value + 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestCompoundAssign1() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get { return 0; } set { var v = value; } } void M() { this.Prop *= x; } }", @"class C { private int GetProp() { return 0; } private void SetProp(int value) { var v = value; } void M() { this.SetProp(this.GetProp() * x); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestCompoundAssign2() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get { return 0; } set { var v = value; } } void M() { this.Prop *= x + y; } }", @"class C { private int GetProp() { return 0; } private void SetProp(int value) { var v = value; } void M() { this.SetProp(this.GetProp() * (x + y)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestMissingAccessors() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { } void M() { var v = this.Prop; } }", @"class C { void M() { var v = this.GetProp(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestComputedProp() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop => 1; }", @"class C { private int GetProp() { return 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestComputedPropWithTrailingTrivia() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop => 1; // Comment }", @"class C { private int GetProp() { return 1; // Comment } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplaceMethodWithProperty)] public async Task TestIndentation() { await TestInRegularAndScriptAsync( @"class C { int [||]Foo { get { int count; foreach (var x in y) { count += bar; } return count; } } }", @"class C { private int GetFoo() { int count; foreach (var x in y) { count += bar; } return count; } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestComputedPropWithTrailingTriviaAfterArrow() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop => /* return 42 */ 42; }", @"class C { public int GetProp() { /* return 42 */ return 42; } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestAbstractProperty() { await TestInRegularAndScriptAsync( @"class C { public abstract int [||]Prop { get; } public void M() { var v = new { P = this.Prop } } }", @"class C { public abstract int GetProp(); public void M() { var v = new { P = this.GetProp() } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestVirtualProperty() { await TestInRegularAndScriptAsync( @"class C { public virtual int [||]Prop { get { return 1; } } public void M() { var v = new { P = this.Prop } } }", @"class C { public virtual int GetProp() { return 1; } public void M() { var v = new { P = this.GetProp() } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestInterfaceProperty() { await TestInRegularAndScriptAsync( @"interface I { int [||]Prop { get; } }", @"interface I { int GetProp(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestAutoProperty1() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get; } }", @"class C { private readonly int prop; public int GetProp() { return prop; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestAutoProperty2() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get; } public C() { this.Prop++; } }", @"class C { private readonly int prop; public int GetProp() { return prop; } public C() { this.prop = this.GetProp() + 1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestAutoProperty3() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get; } public C() { this.Prop *= x + y; } }", @"class C { private readonly int prop; public int GetProp() { return prop; } public C() { this.prop = this.GetProp() * (x + y); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestAutoProperty4() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get; } = 1; }", @"class C { private readonly int prop = 1; public int GetProp() { return prop; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestAutoProperty5() { await TestInRegularAndScriptAsync( @"class C { private int prop; public int [||]Prop { get; } = 1; }", @"class C { private int prop; private readonly int prop1 = 1; public int GetProp() { return prop1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestAutoProperty6() { await TestInRegularAndScriptAsync( @"class C { public int [||]PascalCase { get; } }", @"class C { private readonly int pascalCase; public int GetPascalCase() { return pascalCase; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestUniqueName1() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { get { return 0; } } public abstract int GetProp(); }", @"class C { public int GetProp1() { return 0; } public abstract int GetProp(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestUniqueName2() { await TestInRegularAndScriptAsync( @"class C { public int [||]Prop { set { } } public abstract void SetProp(int i); }", @"class C { public void SetProp1(int value) { } public abstract void SetProp(int i); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestUniqueName3() { await TestInRegularAndScriptAsync( @"class C { public object [||]Prop { set { } } public abstract void SetProp(dynamic i); }", @"class C { public void SetProp1(object value) { } public abstract void SetProp(dynamic i); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestTrivia1() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get; set; } void M() { Prop++; } }", @"class C { private int prop; private int GetProp() { return prop; } private void SetProp(int value) { prop = value; } void M() { SetProp(GetProp() + 1); } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestTrivia2() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get; set; } void M() { /* Leading */ Prop++; /* Trailing */ } }", @"class C { private int prop; private int GetProp() { return prop; } private void SetProp(int value) { prop = value; } void M() { /* Leading */ SetProp(GetProp() + 1); /* Trailing */ } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestTrivia3() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get; set; } void M() { /* Leading */ Prop += 1 /* Trailing */ ; } }", @"class C { private int prop; private int GetProp() { return prop; } private void SetProp(int value) { prop = value; } void M() { /* Leading */ SetProp(GetProp() + 1 /* Trailing */ ); } }", ignoreTrivia: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task ReplaceReadInsideWrite1() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get; set; } void M() { Prop = Prop + 1; } }", @"class C { private int prop; private int GetProp() { return prop; } private void SetProp(int value) { prop = value; } void M() { SetProp(GetProp() + 1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task ReplaceReadInsideWrite2() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get; set; } void M() { Prop *= Prop + 1; } }", @"class C { private int prop; private int GetProp() { return prop; } private void SetProp(int value) { prop = value; } void M() { SetProp(GetProp() * (GetProp() + 1)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] [WorkItem(16157, "https://github.com/dotnet/roslyn/issues/16157")] public async Task TestWithConditionalBinding1() { await TestInRegularAndScriptAsync( @"public class Foo { public bool [||]Any { get; } // Replace 'Any' with method public static void Bar() { var foo = new Foo(); bool f = foo?.Any == true; } }", @"public class Foo { private readonly bool any; public bool GetAny() { return any; } public static void Bar() { var foo = new Foo(); bool f = foo?.GetAny() == true; } }"); } [WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestCodeStyle1() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get { return 0; } } }", @"class C { private int GetProp() => 0; }", ignoreTrivia: false, options: PreferExpressionBodiedMethods); } [WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestCodeStyle2() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get { return 0; } set { throw e; } } }", @"class C { private int GetProp() => 0; private void SetProp(int value) => throw e; }", ignoreTrivia: false, options: PreferExpressionBodiedMethods); } [WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestCodeStyle3() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get => 0; set => throw e; } }", @"class C { private int GetProp() => 0; private void SetProp(int value) => throw e; }", ignoreTrivia: false, options: PreferExpressionBodiedMethods); } [WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestCodeStyle4() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop => 0; }", @"class C { private int GetProp() => 0; }", ignoreTrivia: false, options: PreferExpressionBodiedMethods); } [WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestCodeStyle5() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get; } }", @"class C { private readonly int prop; private int GetProp() => prop; }", ignoreTrivia: false, options: PreferExpressionBodiedMethods); } [WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestCodeStyle6() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get; set; } }", @"class C { private int prop; private int GetProp() => prop; private void SetProp(int value) => prop = value; }", ignoreTrivia: false, options: PreferExpressionBodiedMethods); } [WorkItem(16980, "https://github.com/dotnet/roslyn/issues/16980")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestCodeStyle7() { await TestInRegularAndScriptAsync( @"class C { int [||]Prop { get { A(); return B(); } } }", @"class C { private int GetProp() { A(); return B(); } }", ignoreTrivia: false, options: PreferExpressionBodiedMethods); } [WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestDocumentationComment1() { await TestInRegularAndScriptAsync( @"internal interface ILanguageServiceHost { /// <summary> /// Gets the active workspace project context that provides access to the language service for the active configured project. /// </summary> /// <value> /// An value that provides access to the language service for the active configured project. /// </value> object [||]ActiveProjectContext { get; } }", @"internal interface ILanguageServiceHost { /// <summary> /// Gets the active workspace project context that provides access to the language service for the active configured project. /// </summary> /// <returns> /// An value that provides access to the language service for the active configured project. /// </returns> object GetActiveProjectContext(); }", ignoreTrivia: false); } [WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestDocumentationComment2() { await TestInRegularAndScriptAsync( @"internal interface ILanguageServiceHost { /// <summary> /// Gets the active workspace project context that provides access to the language service for the active configured project. /// </summary> /// <value> /// An value that provides access to the language service for the active configured project. /// </value> object [||]ActiveProjectContext { set; } }", @"internal interface ILanguageServiceHost { /// <summary> /// Gets the active workspace project context that provides access to the language service for the active configured project. /// </summary> /// <returns> /// An value that provides access to the language service for the active configured project. /// </returns> void SetActiveProjectContext(object value); }", ignoreTrivia: false); } [WorkItem(18234, "https://github.com/dotnet/roslyn/issues/18234")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsReplacePropertyWithMethods)] public async Task TestDocumentationComment3() { await TestInRegularAndScriptAsync( @"internal interface ILanguageServiceHost { /// <summary> /// Gets the active workspace project context that provides access to the language service for the active configured project. /// </summary> /// <value> /// An value that provides access to the language service for the active configured project. /// </value> object [||]ActiveProjectContext { get; set; } }", @"internal interface ILanguageServiceHost { /// <summary> /// Gets the active workspace project context that provides access to the language service for the active configured project. /// </summary> /// <returns> /// An value that provides access to the language service for the active configured project. /// </returns> object GetActiveProjectContext(); void SetActiveProjectContext(object value); }", ignoreTrivia: false); } private IDictionary<OptionKey, object> PreferExpressionBodiedMethods => OptionsSet(SingleOption(CSharpCodeStyleOptions.PreferExpressionBodiedMethods, CSharpCodeStyleOptions.WhenPossibleWithSuggestionEnforcement)); } }
using System; using System.Collections; using System.Collections.Generic; namespace InControl { [AutoDiscover] public class Xbox360LinuxProfile : UnityInputDeviceProfile { public Xbox360LinuxProfile() { Name = "XBox 360 Controller"; Meta = "XBox 360 Controller on Linux"; SupportedPlatforms = new[] { "Linux" }; JoystickNames = new[] { "Microsoft X-Box 360 pad", "Generic X-Box pad" }; LastResortRegex = "360"; Sensitivity = 1.0f; LowerDeadZone = 0.2f; ButtonMappings = new[] { new InputControlMapping { Handle = "A", Target = InputControlType.Action1, Source = Button0 }, new InputControlMapping { Handle = "B", Target = InputControlType.Action2, Source = Button1 }, new InputControlMapping { Handle = "X", Target = InputControlType.Action3, Source = Button2 }, new InputControlMapping { Handle = "Y", Target = InputControlType.Action4, Source = Button3 }, new InputControlMapping { Handle = "Left Bumper", Target = InputControlType.LeftBumper, Source = Button4 }, new InputControlMapping { Handle = "Right Bumper", Target = InputControlType.RightBumper, Source = Button5 }, new InputControlMapping { Handle = "Left Stick Button", Target = InputControlType.LeftStickButton, Source = Button9 }, new InputControlMapping { Handle = "Right Stick Button", Target = InputControlType.RightStickButton, Source = Button10 }, new InputControlMapping { Handle = "DPad Left", Target = InputControlType.DPadLeft, Source = Button11, Invert = true }, new InputControlMapping { Handle = "DPad Right", Target = InputControlType.DPadRight, Source = Button12, }, new InputControlMapping { Handle = "DPad Up", Target = InputControlType.DPadUp, Source = Button13, Invert = true }, new InputControlMapping { Handle = "DPad Down", Target = InputControlType.DPadDown, Source = Button14, }, new InputControlMapping { Handle = "Back", Target = InputControlType.Back, Source = Button6 }, new InputControlMapping { Handle = "Start", Target = InputControlType.Start, Source = Button7 }, new InputControlMapping { Handle = "Menu", Target = InputControlType.Menu, Source = Button8 } }; AnalogMappings = new[] { new InputControlMapping { Handle = "Left Stick X", Target = InputControlType.LeftStickX, Source = Analog0 }, new InputControlMapping { Handle = "Left Stick Y", Target = InputControlType.LeftStickY, Source = Analog1, Invert = true }, new InputControlMapping { Handle = "Right Stick X", Target = InputControlType.RightStickX, Source = Analog3 }, new InputControlMapping { Handle = "Right Stick Y", Target = InputControlType.RightStickY, Source = Analog4, Invert = true }, new InputControlMapping { Handle = "DPad Left", Target = InputControlType.DPadLeft, Source = Analog6, SourceRange = InputControlMapping.Range.Negative, TargetRange = InputControlMapping.Range.Negative, Invert = true }, new InputControlMapping { Handle = "DPad Right", Target = InputControlType.DPadRight, Source = Analog6, SourceRange = InputControlMapping.Range.Positive, TargetRange = InputControlMapping.Range.Positive }, new InputControlMapping { Handle = "DPad Up", Target = InputControlType.DPadUp, Source = Analog7, SourceRange = InputControlMapping.Range.Negative, TargetRange = InputControlMapping.Range.Negative, Invert = true }, new InputControlMapping { Handle = "DPad Down", Target = InputControlType.DPadDown, Source = Analog7, SourceRange = InputControlMapping.Range.Positive, TargetRange = InputControlMapping.Range.Positive }, new InputControlMapping { Handle = "Left Trigger", Target = InputControlType.LeftTrigger, Source = Analog2 }, new InputControlMapping { Handle = "Right Trigger", Target = InputControlType.RightTrigger, Source = Analog5 } }; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace AspNetIdentityDependencyInjectionSample.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.Concurrent; using System.Collections.Generic; using System.IO; using Avalonia.Controls; using Avalonia.Controls.Platform.Surfaces; using Avalonia.Direct2D1.Media; using Avalonia.Direct2D1.Media.Imaging; using Avalonia.Media; using Avalonia.Media.Imaging; using Avalonia.Platform; using Avalonia.Visuals.Media.Imaging; using SharpDX.DirectWrite; using GlyphRun = Avalonia.Media.GlyphRun; using TextAlignment = Avalonia.Media.TextAlignment; namespace Avalonia { public static class Direct2DApplicationExtensions { public static T UseDirect2D1<T>(this T builder) where T : AppBuilderBase<T>, new() { builder.UseRenderingSubsystem(Direct2D1.Direct2D1Platform.Initialize, "Direct2D1"); return builder; } } } namespace Avalonia.Direct2D1 { public class Direct2D1Platform : IPlatformRenderInterface { private static readonly Direct2D1Platform s_instance = new Direct2D1Platform(); public static SharpDX.Direct3D11.Device Direct3D11Device { get; private set; } public static SharpDX.Direct2D1.Factory1 Direct2D1Factory { get; private set; } public static SharpDX.Direct2D1.Device Direct2D1Device { get; private set; } public static SharpDX.DirectWrite.Factory1 DirectWriteFactory { get; private set; } public static SharpDX.WIC.ImagingFactory ImagingFactory { get; private set; } public static SharpDX.DXGI.Device1 DxgiDevice { get; private set; } private static readonly object s_initLock = new object(); private static bool s_initialized = false; internal static void InitializeDirect2D() { lock (s_initLock) { if (s_initialized) { return; } #if DEBUG try { Direct2D1Factory = new SharpDX.Direct2D1.Factory1( SharpDX.Direct2D1.FactoryType.MultiThreaded, SharpDX.Direct2D1.DebugLevel.Error); } catch { // } #endif if (Direct2D1Factory == null) { Direct2D1Factory = new SharpDX.Direct2D1.Factory1( SharpDX.Direct2D1.FactoryType.MultiThreaded, SharpDX.Direct2D1.DebugLevel.None); } using (var factory = new SharpDX.DirectWrite.Factory()) { DirectWriteFactory = factory.QueryInterface<SharpDX.DirectWrite.Factory1>(); } ImagingFactory = new SharpDX.WIC.ImagingFactory(); var featureLevels = new[] { SharpDX.Direct3D.FeatureLevel.Level_11_1, SharpDX.Direct3D.FeatureLevel.Level_11_0, SharpDX.Direct3D.FeatureLevel.Level_10_1, SharpDX.Direct3D.FeatureLevel.Level_10_0, SharpDX.Direct3D.FeatureLevel.Level_9_3, SharpDX.Direct3D.FeatureLevel.Level_9_2, SharpDX.Direct3D.FeatureLevel.Level_9_1, }; Direct3D11Device = new SharpDX.Direct3D11.Device( SharpDX.Direct3D.DriverType.Hardware, SharpDX.Direct3D11.DeviceCreationFlags.BgraSupport | SharpDX.Direct3D11.DeviceCreationFlags.VideoSupport, featureLevels); DxgiDevice = Direct3D11Device.QueryInterface<SharpDX.DXGI.Device1>(); Direct2D1Device = new SharpDX.Direct2D1.Device(Direct2D1Factory, DxgiDevice); s_initialized = true; } } public static void Initialize() { InitializeDirect2D(); AvaloniaLocator.CurrentMutable .Bind<IPlatformRenderInterface>().ToConstant(s_instance) .Bind<IFontManagerImpl>().ToConstant(new FontManagerImpl()) .Bind<ITextShaperImpl>().ToConstant(new TextShaperImpl()); SharpDX.Configuration.EnableReleaseOnFinalizer = true; } public IFormattedTextImpl CreateFormattedText( string text, Typeface typeface, double fontSize, TextAlignment textAlignment, TextWrapping wrapping, Size constraint, IReadOnlyList<FormattedTextStyleSpan> spans) { return new FormattedTextImpl( text, typeface, fontSize, textAlignment, wrapping, constraint, spans); } public IRenderTarget CreateRenderTarget(IEnumerable<object> surfaces) { foreach (var s in surfaces) { if (s is IPlatformHandle nativeWindow) { if (nativeWindow.HandleDescriptor != "HWND") { throw new NotSupportedException("Don't know how to create a Direct2D1 renderer from " + nativeWindow.HandleDescriptor); } return new HwndRenderTarget(nativeWindow); } if (s is IExternalDirect2DRenderTargetSurface external) { return new ExternalRenderTarget(external); } if (s is IFramebufferPlatformSurface fb) { return new FramebufferShimRenderTarget(fb); } } throw new NotSupportedException("Don't know how to create a Direct2D1 renderer from any of provided surfaces"); } public IRenderTargetBitmapImpl CreateRenderTargetBitmap(PixelSize size, Vector dpi) { return new WicRenderTargetBitmapImpl(size, dpi); } public IWriteableBitmapImpl CreateWriteableBitmap(PixelSize size, Vector dpi, PixelFormat format, AlphaFormat alphaFormat) { return new WriteableWicBitmapImpl(size, dpi, format, alphaFormat); } public IGeometryImpl CreateEllipseGeometry(Rect rect) => new EllipseGeometryImpl(rect); public IGeometryImpl CreateLineGeometry(Point p1, Point p2) => new LineGeometryImpl(p1, p2); public IGeometryImpl CreateRectangleGeometry(Rect rect) => new RectangleGeometryImpl(rect); public IStreamGeometryImpl CreateStreamGeometry() => new StreamGeometryImpl(); /// <inheritdoc /> public IBitmapImpl LoadBitmap(string fileName) { return new WicBitmapImpl(fileName); } /// <inheritdoc /> public IBitmapImpl LoadBitmap(Stream stream) { return new WicBitmapImpl(stream); } /// <inheritdoc /> public IBitmapImpl LoadBitmapToWidth(Stream stream, int width, BitmapInterpolationMode interpolationMode = BitmapInterpolationMode.HighQuality) { return new WicBitmapImpl(stream, width, true, interpolationMode); } /// <inheritdoc /> public IBitmapImpl LoadBitmapToHeight(Stream stream, int height, BitmapInterpolationMode interpolationMode = BitmapInterpolationMode.HighQuality) { return new WicBitmapImpl(stream, height, false, interpolationMode); } /// <inheritdoc /> public IBitmapImpl ResizeBitmap(IBitmapImpl bitmapImpl, PixelSize destinationSize, BitmapInterpolationMode interpolationMode = BitmapInterpolationMode.HighQuality) { // https://github.com/sharpdx/SharpDX/issues/959 blocks implementation. throw new NotImplementedException(); } /// <inheritdoc /> public IBitmapImpl LoadBitmap(PixelFormat format, AlphaFormat alphaFormat, IntPtr data, PixelSize size, Vector dpi, int stride) { return new WicBitmapImpl(format, alphaFormat, data, size, dpi, stride); } public IGlyphRunImpl CreateGlyphRun(GlyphRun glyphRun, out double width) { var glyphTypeface = (GlyphTypefaceImpl)glyphRun.GlyphTypeface.PlatformImpl; var glyphCount = glyphRun.GlyphIndices.Length; var run = new SharpDX.DirectWrite.GlyphRun { FontFace = glyphTypeface.FontFace, FontSize = (float)glyphRun.FontRenderingEmSize }; var indices = new short[glyphCount]; for (var i = 0; i < glyphCount; i++) { indices[i] = (short)glyphRun.GlyphIndices[i]; } run.Indices = indices; run.Advances = new float[glyphCount]; width = 0; var scale = (float)(glyphRun.FontRenderingEmSize / glyphTypeface.DesignEmHeight); if (glyphRun.GlyphAdvances.IsEmpty) { for (var i = 0; i < glyphCount; i++) { var advance = glyphTypeface.GetGlyphAdvance(glyphRun.GlyphIndices[i]) * scale; run.Advances[i] = advance; width += advance; } } else { for (var i = 0; i < glyphCount; i++) { var advance = (float)glyphRun.GlyphAdvances[i]; run.Advances[i] = advance; width += advance; } } if (glyphRun.GlyphOffsets.IsEmpty) { return new GlyphRunImpl(run); } run.Offsets = new GlyphOffset[glyphCount]; for (var i = 0; i < glyphCount; i++) { var (x, y) = glyphRun.GlyphOffsets[i]; run.Offsets[i] = new GlyphOffset { AdvanceOffset = (float)x, AscenderOffset = (float)y }; } return new GlyphRunImpl(run); } public bool SupportsIndividualRoundRects => false; public AlphaFormat DefaultAlphaFormat => AlphaFormat.Premul; public PixelFormat DefaultPixelFormat => PixelFormat.Bgra8888; } }
/* * DISCLAIMER * * Copyright 2016 ArangoDB GmbH, Cologne, Germany * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Copyright holder is ArangoDB GmbH, Cologne, Germany */ namespace ArangoDB { using global::ArangoDB.Entity; using global::ArangoDB.Internal; using global::ArangoDB.Internal.VelocyStream; using global::ArangoDB.Model; using global::ArangoDB.Velocystream; /// <author>Mark - mark at arangodb.com</author> public class ArangoVertexCollection : InternalArangoVertexCollection <ArangoExecutorSync, Response, ConnectionSync> { protected internal ArangoVertexCollection(ArangoGraph graph, string name) : base(graph.executor(), graph.db(), graph.name(), name) { } /// <summary> /// Removes a vertex collection from the graph and optionally deletes the collection, if it is not used in any other /// graph /// </summary> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Management.html#remove-vertex-collection">API /// * Documentation</a></seealso> /// <exception cref="ArangoDBException"/> /// <exception cref="ArangoDBException"/> public virtual void drop() { this.executor.execute(this.dropRequest(), typeof(java.lang.Void )); } /// <summary>Creates a new vertex in the collection</summary> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Vertices.html#create-a-vertex">API Documentation</a> /// </seealso> /// <param name="value">A representation of a single vertex (POJO, VPackSlice or String for Json) /// </param> /// <returns>information about the vertex</returns> /// <exception cref="ArangoDBException"/> /// <exception cref="ArangoDBException"/> public virtual VertexEntity insertVertex<T>(T value) { return this.executor.execute(this.insertVertexRequest(value, new VertexCreateOptions ()), this.insertVertexResponseDeserializer(value)); } /// <summary>Creates a new vertex in the collection</summary> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Vertices.html#create-a-vertex">API Documentation</a> /// </seealso> /// <param name="value">A representation of a single vertex (POJO, VPackSlice or String for Json) /// </param> /// <param name="options">Additional options, can be null</param> /// <returns>information about the vertex</returns> /// <exception cref="ArangoDBException"/> /// <exception cref="ArangoDBException"/> public virtual VertexEntity insertVertex<T>(T value, VertexCreateOptions options) { return this.executor.execute(this.insertVertexRequest(value, options), this.insertVertexResponseDeserializer (value)); } /// <summary>Fetches an existing vertex</summary> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Vertices.html#get-a-vertex">API Documentation</a> /// </seealso> /// <param name="key">The key of the vertex</param> /// <param name="type">The type of the vertex-document (POJO class, VPackSlice or String for Json) /// </param> /// <returns>the vertex identified by the key</returns> /// <exception cref="ArangoDBException"/> /// <exception cref="com.arangodb.ArangoDBException"/> public virtual T getVertex<T>(string key) { System.Type type = typeof(T); return this.executor.execute(this.getVertexRequest(key, new DocumentReadOptions ()), getVertexResponseDeserializer(type)); } /// <summary>Fetches an existing vertex</summary> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Vertices.html#get-a-vertex">API Documentation</a> /// </seealso> /// <param name="key">The key of the vertex</param> /// <param name="type">The type of the vertex-document (POJO class, VPackSlice or String for Json) /// </param> /// <param name="options">Additional options, can be null</param> /// <returns>the vertex identified by the key</returns> /// <exception cref="ArangoDBException"/> /// <exception cref="com.arangodb.ArangoDBException"/> public virtual T getVertex<T>(string key, DocumentReadOptions options) { System.Type type = typeof(T); return this.executor.execute(this.getVertexRequest(key, options), getVertexResponseDeserializer (type)); } /// <summary> /// Replaces the vertex with key with the one in the body, provided there is such a vertex and no precondition is /// violated /// </summary> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Vertices.html#replace-a-vertex">API /// * Documentation</a></seealso> /// <param name="key">The key of the vertex</param> /// <param name="type">The type of the vertex-document (POJO class, VPackSlice or String for Json) /// </param> /// <returns>information about the vertex</returns> /// <exception cref="ArangoDBException"/> /// <exception cref="com.arangodb.ArangoDBException"/> public virtual VertexUpdateEntity replaceVertex<T>(string key , T value) { return this.executor.execute(this.replaceVertexRequest(key, value, new VertexReplaceOptions ()), this.replaceVertexResponseDeserializer(value)); } /// <summary> /// Replaces the vertex with key with the one in the body, provided there is such a vertex and no precondition is /// violated /// </summary> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Vertices.html#replace-a-vertex">API /// * Documentation</a></seealso> /// <param name="key">The key of the vertex</param> /// <param name="type">The type of the vertex-document (POJO class, VPackSlice or String for Json) /// </param> /// <param name="options">Additional options, can be null</param> /// <returns>information about the vertex</returns> /// <exception cref="ArangoDBException"/> /// <exception cref="com.arangodb.ArangoDBException"/> public virtual VertexUpdateEntity replaceVertex<T>(string key , T value, VertexReplaceOptions options) { return this.executor.execute(this.replaceVertexRequest(key, value, options), this.replaceVertexResponseDeserializer (value)); } /// <summary>Partially updates the vertex identified by document-key.</summary> /// <remarks> /// Partially updates the vertex identified by document-key. The value must contain a document with the attributes to /// patch (the patch document). All attributes from the patch document will be added to the existing document if they /// do not yet exist, and overwritten in the existing document if they do exist there. /// </remarks> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Vertices.html#modify-a-vertex">API Documentation</a> /// </seealso> /// <param name="key">The key of the vertex</param> /// <param name="type">The type of the vertex-document (POJO class, VPackSlice or String for Json) /// </param> /// <returns>information about the vertex</returns> /// <exception cref="ArangoDBException"/> /// <exception cref="com.arangodb.ArangoDBException"/> public virtual VertexUpdateEntity updateVertex<T>(string key, T value) { return this.executor.execute(this.updateVertexRequest(key, value, new VertexUpdateOptions ()), this.updateVertexResponseDeserializer(value)); } /// <summary>Partially updates the vertex identified by document-key.</summary> /// <remarks> /// Partially updates the vertex identified by document-key. The value must contain a document with the attributes to /// patch (the patch document). All attributes from the patch document will be added to the existing document if they /// do not yet exist, and overwritten in the existing document if they do exist there. /// </remarks> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Vertices.html#modify-a-vertex">API Documentation</a> /// </seealso> /// <param name="key">The key of the vertex</param> /// <param name="type">The type of the vertex-document (POJO class, VPackSlice or String for Json) /// </param> /// <param name="options">Additional options, can be null</param> /// <returns>information about the vertex</returns> /// <exception cref="ArangoDBException"/> /// <exception cref="com.arangodb.ArangoDBException"/> public virtual VertexUpdateEntity updateVertex<T>(string key, T value, VertexUpdateOptions options) { return this.executor.execute(this.updateVertexRequest(key, value, options), this.updateVertexResponseDeserializer (value)); } /// <summary>Removes a vertex</summary> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Vertices.html#remove-a-vertex">API Documentation</a> /// </seealso> /// <param name="key">The key of the vertex</param> /// <exception cref="ArangoDBException"/> /// <exception cref="ArangoDBException"/> public virtual void deleteVertex(string key) { this.executor.execute(this.deleteVertexRequest(key, new VertexDeleteOptions ()), typeof(java.lang.Void)); } /// <summary>Removes a vertex</summary> /// <seealso><a href="https://docs.arangodb.com/current/HTTP/Gharial/Vertices.html#remove-a-vertex">API Documentation</a> /// </seealso> /// <param name="key">The key of the vertex</param> /// <param name="options">Additional options, can be null</param> /// <exception cref="ArangoDBException"/> /// <exception cref="ArangoDBException"/> public virtual void deleteVertex(string key, VertexDeleteOptions options) { this.executor.execute(this.deleteVertexRequest(key, options), typeof(java.lang.Void)); } } }
/// This code was generated by /// \ / _ _ _| _ _ /// | (_)\/(_)(_|\/| |(/_ v1.0.0 /// / / using System; using System.Collections.Generic; using Twilio.Base; using Twilio.Converters; namespace Twilio.Rest.Events.V1.Subscription { /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Retrieve a list of all Subscribed Event types for a Subscription. /// </summary> public class ReadSubscribedEventOptions : ReadOptions<SubscribedEventResource> { /// <summary> /// Subscription SID. /// </summary> public string PathSubscriptionSid { get; } /// <summary> /// Construct a new ReadSubscribedEventOptions /// </summary> /// <param name="pathSubscriptionSid"> Subscription SID. </param> public ReadSubscribedEventOptions(string pathSubscriptionSid) { PathSubscriptionSid = pathSubscriptionSid; } /// <summary> /// Generate the necessary parameters /// </summary> public override List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (PageSize != null) { p.Add(new KeyValuePair<string, string>("PageSize", PageSize.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Create a new Subscribed Event type for the subscription /// </summary> public class CreateSubscribedEventOptions : IOptions<SubscribedEventResource> { /// <summary> /// Subscription SID. /// </summary> public string PathSubscriptionSid { get; } /// <summary> /// Type of event being subscribed to. /// </summary> public string Type { get; } /// <summary> /// The schema version that the subscription should use. /// </summary> public int? SchemaVersion { get; set; } /// <summary> /// Construct a new CreateSubscribedEventOptions /// </summary> /// <param name="pathSubscriptionSid"> Subscription SID. </param> /// <param name="type"> Type of event being subscribed to. </param> public CreateSubscribedEventOptions(string pathSubscriptionSid, string type) { PathSubscriptionSid = pathSubscriptionSid; Type = type; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (Type != null) { p.Add(new KeyValuePair<string, string>("Type", Type)); } if (SchemaVersion != null) { p.Add(new KeyValuePair<string, string>("SchemaVersion", SchemaVersion.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Read an Event for a Subscription. /// </summary> public class FetchSubscribedEventOptions : IOptions<SubscribedEventResource> { /// <summary> /// Subscription SID. /// </summary> public string PathSubscriptionSid { get; } /// <summary> /// Type of event being subscribed to. /// </summary> public string PathType { get; } /// <summary> /// Construct a new FetchSubscribedEventOptions /// </summary> /// <param name="pathSubscriptionSid"> Subscription SID. </param> /// <param name="pathType"> Type of event being subscribed to. </param> public FetchSubscribedEventOptions(string pathSubscriptionSid, string pathType) { PathSubscriptionSid = pathSubscriptionSid; PathType = pathType; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Update an Event for a Subscription. /// </summary> public class UpdateSubscribedEventOptions : IOptions<SubscribedEventResource> { /// <summary> /// Subscription SID. /// </summary> public string PathSubscriptionSid { get; } /// <summary> /// Type of event being subscribed to. /// </summary> public string PathType { get; } /// <summary> /// The schema version that the subscription should use. /// </summary> public int? SchemaVersion { get; set; } /// <summary> /// Construct a new UpdateSubscribedEventOptions /// </summary> /// <param name="pathSubscriptionSid"> Subscription SID. </param> /// <param name="pathType"> Type of event being subscribed to. </param> public UpdateSubscribedEventOptions(string pathSubscriptionSid, string pathType) { PathSubscriptionSid = pathSubscriptionSid; PathType = pathType; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); if (SchemaVersion != null) { p.Add(new KeyValuePair<string, string>("SchemaVersion", SchemaVersion.ToString())); } return p; } } /// <summary> /// PLEASE NOTE that this class contains beta products that are subject to change. Use them with caution. /// /// Remove an event type from a subscription. /// </summary> public class DeleteSubscribedEventOptions : IOptions<SubscribedEventResource> { /// <summary> /// Subscription SID. /// </summary> public string PathSubscriptionSid { get; } /// <summary> /// Type of event being subscribed to. /// </summary> public string PathType { get; } /// <summary> /// Construct a new DeleteSubscribedEventOptions /// </summary> /// <param name="pathSubscriptionSid"> Subscription SID. </param> /// <param name="pathType"> Type of event being subscribed to. </param> public DeleteSubscribedEventOptions(string pathSubscriptionSid, string pathType) { PathSubscriptionSid = pathSubscriptionSid; PathType = pathType; } /// <summary> /// Generate the necessary parameters /// </summary> public List<KeyValuePair<string, string>> GetParams() { var p = new List<KeyValuePair<string, string>>(); return p; } } }
/* * CID001d.cs - sv culture handler. * * Copyright (c) 2003 Southern Storm Software, Pty Ltd * * This program is free software; you can redistribute it and/or modify * it under the terms of the GNU General Public License as published by * the Free Software Foundation; either version 2 of the License, or * (at your option) any later version. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ // Generated from "sv.txt". namespace I18N.West { using System; using System.Globalization; using I18N.Common; public class CID001d : RootCulture { public CID001d() : base(0x001D) {} public CID001d(int culture) : base(culture) {} public override String Name { get { return "sv"; } } public override String ThreeLetterISOLanguageName { get { return "swe"; } } public override String ThreeLetterWindowsLanguageName { get { return "SVE"; } } public override String TwoLetterISOLanguageName { get { return "sv"; } } public override DateTimeFormatInfo DateTimeFormat { get { DateTimeFormatInfo dfi = base.DateTimeFormat; dfi.AbbreviatedDayNames = new String[] {"s\u00F6", "m\u00E5", "ti", "on", "to", "fr", "l\u00F6"}; dfi.DayNames = new String[] {"s\u00F6ndag", "m\u00E5ndag", "tisdag", "onsdag", "torsdag", "fredag", "l\u00F6rdag"}; dfi.AbbreviatedMonthNames = new String[] {"jan", "feb", "mar", "apr", "maj", "jun", "jul", "aug", "sep", "okt", "nov", "dec", ""}; dfi.MonthNames = new String[] {"januari", "februari", "mars", "april", "maj", "juni", "juli", "augusti", "september", "oktober", "november", "december", ""}; dfi.DateSeparator = "-"; dfi.TimeSeparator = ":"; dfi.LongDatePattern = "'den 'd MMMM yyyy"; dfi.LongTimePattern = "HH:mm:ss z"; dfi.ShortDatePattern = "yyyy-MM-dd"; dfi.ShortTimePattern = "HH:mm"; dfi.FullDateTimePattern = "'den 'd MMMM yyyy 'kl 'H:mm z"; dfi.I18NSetDateTimePatterns(new String[] { "d:yyyy-MM-dd", "D:'den 'd MMMM yyyy", "f:'den 'd MMMM yyyy 'kl 'H:mm z", "f:'den 'd MMMM yyyy HH:mm:ss z", "f:'den 'd MMMM yyyy HH:mm:ss", "f:'den 'd MMMM yyyy HH:mm", "F:'den 'd MMMM yyyy HH:mm:ss", "g:yyyy-MM-dd 'kl 'H:mm z", "g:yyyy-MM-dd HH:mm:ss z", "g:yyyy-MM-dd HH:mm:ss", "g:yyyy-MM-dd HH:mm", "G:yyyy-MM-dd HH:mm:ss", "m:MMMM dd", "M:MMMM dd", "r:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "R:ddd, dd MMM yyyy HH':'mm':'ss 'GMT'", "s:yyyy'-'MM'-'dd'T'HH':'mm':'ss", "t:'kl 'H:mm z", "t:HH:mm:ss z", "t:HH:mm:ss", "t:HH:mm", "T:HH:mm:ss", "u:yyyy'-'MM'-'dd HH':'mm':'ss'Z'", "U:dddd, dd MMMM yyyy HH:mm:ss", "y:yyyy MMMM", "Y:yyyy MMMM", }); return dfi; } set { base.DateTimeFormat = value; // not used } } public override NumberFormatInfo NumberFormat { get { NumberFormatInfo nfi = base.NumberFormat; nfi.CurrencyDecimalSeparator = ","; nfi.CurrencyGroupSeparator = "\u00A0"; nfi.NumberGroupSeparator = "\u00A0"; nfi.PercentGroupSeparator = "\u00A0"; nfi.NegativeSign = "-"; nfi.NumberDecimalSeparator = ","; nfi.PercentDecimalSeparator = ","; nfi.PercentSymbol = "%"; nfi.PerMilleSymbol = "\u2030"; return nfi; } set { base.NumberFormat = value; // not used } } public override String ResolveLanguage(String name) { switch(name) { case "aa": return "afar"; case "ab": return "abkhaziska"; case "ace": return "achinese"; case "ach": return "acholi"; case "ada": return "adangme"; case "ae": return "avestiska"; case "af": return "afrikaans"; case "ak": return "akan"; case "akk": return "akkadiska"; case "ale": return "aleutiska"; case "am": return "amhariska"; case "ar": return "arabiska"; case "arc": return "arameiska"; case "arn": return "araukanska"; case "arp": return "arapaho"; case "arw": return "arawakiska"; case "as": return "assami"; case "ast": return "asturiska"; case "av": return "avariska"; case "awa": return "awadhi"; case "ay": return "aymara"; case "az": return "azerbadzjanska"; case "ba": return "basjkiriska"; case "bad": return "banda"; case "bal": return "baluchi"; case "bam": return "bambara"; case "ban": return "balinesiska"; case "bas": return "basa"; case "be": return "vitryska"; case "bej": return "beyja"; case "bem": return "bemba"; case "bg": return "bulgariska"; case "bh": return "bihari"; case "bho": return "bhojpuri"; case "bi": return "bislama"; case "bik": return "bikol"; case "bin": return "bini"; case "bla": return "siksika"; case "bn": return "bengali"; case "bo": return "tibetanska"; case "br": return "bretonska"; case "bra": return "braj"; case "bs": return "bosniska"; case "btk": return "batak"; case "bua": return "buriat"; case "bug": return "buginesiska"; case "ca": return "katalanska"; case "cad": return "caddo"; case "car": return "karibiska"; case "ce": return "tjetjenska"; case "ceb": return "cebuano"; case "ch": return "chamorro"; case "chb": return "chibcha"; case "chg": return "chagatai"; case "chk": return "chuukesiska"; case "chm": return "mari"; case "chn": return "chinook"; case "cho": return "choctaw"; case "chr": return "cherokesiska"; case "chy": return "cheyenne"; case "co": return "korsiska"; case "cop": return "koptiska"; case "cr": return "cree"; case "cs": return "tjeckiska"; case "cv": return "tjuvasjiska"; case "cy": return "walesiska"; case "da": return "danska"; case "dak": return "dakota"; case "day": return "dayak"; case "de": return "tyska"; case "del": return "delaware"; case "dgr": return "dogrib"; case "din": return "dinka"; case "doi": return "dogri"; case "dua": return "duala"; case "dv": return "maldiviska"; case "dyu": return "dyula"; case "dz": return "dzongkha"; case "ee": return "ewe"; case "efi": return "efik"; case "eka": return "ekajuk"; case "el": return "grekiska"; case "elx": return "elamitiska"; case "en": return "engelska"; case "eo": return "esperanto"; case "es": return "spanska"; case "et": return "estniska"; case "eu": return "baskiska"; case "ewo": return "ewondo"; case "fa": return "farsi"; case "fan": return "fang"; case "fat": return "fanti"; case "ff": return "fulani"; case "fi": return "finska"; case "fj": return "fidjianska"; case "fo": return "f\u00E4r\u00F6iska"; case "fon": return "fon"; case "fr": return "franska"; case "fur": return "friuilian"; case "fy": return "frisiska"; case "ga": return "irl\u00E4ndsk gaeliska"; case "gaa": return "g\u00E0"; case "gay": return "gayo"; case "gba": return "gbaya"; case "gd": return "skotsk gaeliska"; case "gil": return "gilbertesiska; kiribati"; case "gl": return "galiciska"; case "gn": return "guaran\u00ED"; case "gon": return "gondi"; case "gor": return "gorontalo"; case "got": return "gotiska"; case "grb": return "grebo"; case "gu": return "gujarati"; case "gv": return "manx gaeliska"; case "gwi": return "gwich'in"; case "ha": return "haussa"; case "hai": return "haida"; case "haw": return "hawaiiska"; case "he": return "hebreiska"; case "hi": return "hindi"; case "hil": return "hiligaynon"; case "him": return "himachali"; case "hmn": return "hmong"; case "ho": return "hiri motu"; case "hr": return "kroatiska"; case "hu": return "ungerska"; case "hup": return "hupa"; case "hy": return "armeniska"; case "hz": return "herero"; case "iba": return "iban"; case "id": return "indonesiska"; case "ig": return "ibo"; case "ii": return "yi"; case "ijo": return "ijo"; case "ik": return "inupiaq"; case "ilo": return "iloko"; case "is": return "isl\u00E4ndska"; case "it": return "italienska"; case "iu": return "inuktitut"; case "ja": return "japanska"; case "jv": return "javanska"; case "ka": return "georgiska"; case "kaa": return "karakalpakiska"; case "kab": return "kabyliska"; case "kac": return "kachin"; case "kam": return "kamba"; case "kar": return "karen"; case "kaw": return "kawi"; case "kg": return "kikongo"; case "kha": return "khasi"; case "kho": return "sakiska"; case "ki": return "kikuyu"; case "kj": return "kuanyama"; case "kk": return "kazakiska"; case "kl": return "gr\u00F6nl\u00E4ndska; kalaallisut"; case "km": return "kambodjanska; khmer"; case "kmb": return "kinbundu"; case "kn": return "kanaresiska; kannada"; case "ko": return "koreanska"; case "kok": return "konkani"; case "kos": return "kosreanska"; case "kpe": return "kpelle"; case "kr": return "kanuri"; case "kro": return "kru"; case "kru": return "kurukh"; case "ks": return "kashmiri"; case "ku": return "kurdiska"; case "kum": return "kumyk"; case "kut": return "kutenai"; case "kv": return "kome"; case "kw": return "korniska"; case "ky": return "kirgisiska"; case "la": return "latin"; case "lah": return "lahnda"; case "lam": return "lamba"; case "lb": return "luxemburgiska"; case "lez": return "lezghien"; case "lg": return "luganda"; case "li": return "limburgiska"; case "ln": return "lingala"; case "lo": return "laotiska"; case "lol": return "lolo; mongo"; case "loz": return "lozi"; case "lt": return "litauiska"; case "lu": return "luba-katanga"; case "lua": return "luba-lulua"; case "lui": return "luise\u00F1o"; case "lun": return "lunda"; case "luo": return "luo"; case "lus": return "lushai"; case "lv": return "lettiska"; case "mad": return "madurese"; case "mag": return "magahi"; case "mai": return "maithili"; case "mak": return "makasar"; case "man": return "mande"; case "mas": return "massajiska"; case "mdr": return "mandar"; case "men": return "mende"; case "mg": return "malagassiska"; case "mh": return "marshalliska"; case "mi": return "maori"; case "mic": return "mic-mac"; case "min": return "minangkabau"; case "mk": return "makedonska"; case "ml": return "malayalam"; case "mn": return "mongoliska"; case "mnc": return "manchu"; case "mni": return "manipuri"; case "mo": return "moldaviska"; case "moh": return "mohawk"; case "mos": return "mossi"; case "mr": return "marathi"; case "ms": return "malajiska"; case "mt": return "maltesiska"; case "mus": return "muskogee"; case "mwr": return "marwari"; case "my": return "burmanska"; case "na": return "nauru"; case "nah": return "nahuatl; aztekiska"; case "nap": return "napolitanska"; case "nb": return "norskt bokm\u00E5l"; case "nd": return "nord\u00ADndebele"; case "ne": return "nepali"; case "new": return "newari"; case "ng": return "ndonga"; case "nia": return "nias"; case "niu": return "niuean"; case "nl": return "nederl\u00E4ndska; holl\u00E4ndska"; case "nn": return "ny\u00ADnorsk"; case "no": return "norska"; case "nr": return "syd\u00ADndebele"; case "nso": return "nord\u00ADsotho"; case "nv": return "navaho"; case "ny": return "nyanja"; case "nym": return "nyamwezi"; case "nyn": return "nyankole"; case "nyo": return "nyoro"; case "nzi": return "nzima"; case "oc": return "provensalska"; case "oj": return "odjibwa; chippewa"; case "om": return "oromo; galla"; case "or": return "oriya"; case "os": return "ossetiska"; case "osa": return "osage"; case "pa": return "panjabi"; case "pag": return "pangasinan"; case "pam": return "pampanga"; case "pap": return "papiamento"; case "pau": return "palauan"; case "phn": return "kananeiska; feniciska"; case "pi": return "pali"; case "pl": return "polska"; case "pon": return "ponape"; case "ps": return "pashto; afghanska"; case "pt": return "portugisiska"; case "qu": return "quechua"; case "raj": return "rajasthani"; case "rap": return "rapanui"; case "rar": return "rarotongan"; case "rm": return "r\u00E4to\u00ADromanska"; case "rn": return "rundi"; case "ro": return "rum\u00E4nska"; case "rom": return "romani"; case "ru": return "ryska"; case "rw": return "rwanda; kinjarwanda"; case "sa": return "sanskrit"; case "sad": return "sandawe"; case "sah": return "jakutiska"; case "sam": return "samaritanska"; case "sas": return "sasak"; case "sat": return "santali"; case "sc": return "sardiska"; case "sco": return "skotska"; case "sd": return "sindhi"; case "se": return "nord\u00ADsamiska"; case "sel": return "selkup"; case "sg": return "sango"; case "shn": return "shan"; case "si": return "singalesiska"; case "sid": return "sidamo"; case "sk": return "slovakiska"; case "sl": return "slovenska"; case "sm": return "samoanska"; case "sn": return "shona; manshona"; case "snk": return "soninke"; case "so": return "somali"; case "sog": return "sogdiska"; case "son": return "songhai"; case "sq": return "albanska"; case "sr": return "serbiska"; case "srr": return "serer"; case "ss": return "swati"; case "st": return "syd\u00ADsotho"; case "su": return "sundanesiska"; case "suk": return "sukuma"; case "sus": return "susu"; case "sux": return "sumeriska"; case "sv": return "svenska"; case "sw": return "swahili"; case "syr": return "syriska"; case "ta": return "tamil"; case "te": return "telugu"; case "tem": return "temne"; case "ter": return "tereno"; case "tet": return "tetum"; case "tg": return "tadzjikiska"; case "th": return "thail\u00E4nska"; case "ti": return "tigrinja"; case "tig": return "tigr\u00E9"; case "tiv": return "tivi"; case "tk": return "turkmeniska"; case "tkl": return "tokelau"; case "tl": return "tagalog"; case "tli": return "tlingit"; case "tmh": return "tamashek"; case "tn": return "tswana"; case "to": return "tonga"; case "tog": return "tonga-Nyasa"; case "tpi": return "tok pisin"; case "tr": return "turkiska"; case "ts": return "tsonga"; case "tsi": return "tsimshian"; case "tt": return "tatariska"; case "tum": return "tumbuka"; case "tvl": return "tuvaluan"; case "tw": return "twi"; case "ty": return "tahitiska"; case "tyv": return "tuviniska"; case "ug": return "uiguriska"; case "uga": return "ugaritiska"; case "uk": return "ukrainska"; case "umb": return "umbundu"; case "ur": return "urdu"; case "uz": return "uzbekiska"; case "vai": return "vai"; case "ve": return "venda"; case "vi": return "vietnamesiska"; case "vot": return "votiska"; case "wa": return "walloon"; case "wal": return "walamo"; case "war": return "waray"; case "was": return "washo"; case "wo": return "wolof"; case "xh": return "xhosa"; case "yao": return "yao"; case "yap": return "yap"; case "yi": return "jiddisch"; case "yo": return "yoruba"; case "za": return "zhuang"; case "zap": return "zapotek"; case "zen": return "zenaga"; case "zh": return "kinesiska"; case "znd": return "zand\u00E9"; case "zu": return "zulu"; case "zun": return "zu\u00F1i"; } return base.ResolveLanguage(name); } public override String ResolveCountry(String name) { switch(name) { case "AE": return "F\u00F6renade Arabemiraten"; case "AF": return "Afganistan"; case "AG": return "Antigua och Barbuda"; case "AL": return "Albanien"; case "AM": return "Armenien"; case "AN": return "Nederl\u00E4ndska Antillerna"; case "AQ": return "Antarktis"; case "AS": return "Amerikanska Samoa"; case "AT": return "\u00D6sterrike"; case "AU": return "Australien"; case "AZ": return "Azerbajdzjan"; case "BA": return "Bosnien Herzegovina"; case "BE": return "Belgien"; case "BG": return "Bulgarien"; case "BR": return "Brasilien"; case "BY": return "Vitryssland"; case "CA": return "Kanada"; case "CD": return "Kongo"; case "CF": return "Centralafrikanska republiken"; case "CG": return "Kongo"; case "CH": return "Schweiz"; case "CI": return "Elfenbenskusten"; case "CK": return "Cook\u00F6arna"; case "CM": return "Kamerun"; case "CN": return "Kina"; case "CU": return "Kuba"; case "CV": return "Cap Verde"; case "CX": return "Jul\u00F6n"; case "CY": return "Cypern"; case "CZ": return "Tjeckien"; case "DE": return "Tyskland"; case "DK": return "Danmark"; case "DO": return "Dominikanska republiken"; case "DZ": return "Algeriet"; case "EE": return "Estland"; case "EG": return "Egypten"; case "EH": return "V\u00E4stra Sahara"; case "ES": return "Spanien"; case "ET": return "Etiopien"; case "FK": return "Falklands\u00F6arna"; case "FM": return "Mikronesien"; case "FO": return "F\u00E4r\u00F6arna"; case "FR": return "Frankrike"; case "GB": return "Storbritannien"; case "GE": return "Georgien"; case "GF": return "Franska Guyana"; case "GL": return "Gr\u00F6nland"; case "GP": return "Guadelope"; case "GQ": return "Ekvatorialguinea"; case "GR": return "Grekland"; case "HK": return "Hong Kong"; case "HR": return "Kroatien"; case "HU": return "Ungern"; case "ID": return "Indonesien"; case "IE": return "Irland"; case "IN": return "Indien"; case "IQ": return "Irak"; case "IS": return "Island"; case "IT": return "Italien"; case "JO": return "Jordanien"; case "KG": return "Kirgisistan"; case "KH": return "Kambodja"; case "KM": return "Komorerna"; case "KN": return "S:t Christopher och Nevis"; case "KP": return "Nordkorea"; case "KR": return "Sydkorea"; case "KY": return "Cayman\u00F6arna"; case "KZ": return "Kazachstan"; case "LB": return "Libanon"; case "LC": return "S:t Lucia"; case "LT": return "Litauen"; case "LU": return "Luxemburg"; case "LV": return "Lettland"; case "LY": return "Libyen"; case "MA": return "Marocko"; case "MD": return "Moldavien"; case "MG": return "Madagaskar"; case "MH": return "Marshall\u00F6arna"; case "MK": return "Makedonien"; case "MN": return "Mongoliet"; case "MP": return "Nordmarianerna"; case "MR": return "Mauretanien"; case "MV": return "Maldiverna"; case "MX": return "Mexiko"; case "NC": return "Nya Caledonien"; case "NF": return "Norfolk\u00F6n"; case "NL": return "Nederl\u00E4nderna"; case "NO": return "Norge"; case "NZ": return "Nya Zeeland"; case "PF": return "Franska Polynesien"; case "PG": return "Papua Nya Guinea"; case "PH": return "Filippinerna"; case "PL": return "Polen"; case "PM": return "S:t Pierre och Miquelon"; case "RO": return "Rum\u00E4nien"; case "RU": return "Ryssland"; case "SA": return "Saudi-Arabien"; case "SB": return "Salomon\u00F6arna"; case "SC": return "Seychellerna"; case "SE": return "Sverige"; case "SH": return "S:t Helena"; case "SI": return "Slovenien"; case "SJ": return "Svalbard och Jan Mayen"; case "SK": return "Slovakien"; case "SR": return "Surinam"; case "ST": return "S\u00E3o Tom\u00E9 och Pr\u00EDncipe"; case "SY": return "Syrien"; case "TC": return "Turks- och Caicos\u00F6arna"; case "TD": return "Tchad"; case "TJ": return "Tadzjikistan"; case "TL": return "\u00D6sttimor"; case "TN": return "Tunisien"; case "TR": return "Turkiet"; case "TT": return "Trinidad och Tobago"; case "UA": return "Ukraina"; case "US": return "USA"; case "VA": return "Vatikanstaten"; case "VC": return "S:t Vincent och Grenadinerna"; case "WF": return "Wallis och Futuna"; case "VG": return "Brittiska Jungfru\u00F6arna"; case "VI": return "Amerikanska Jungfru\u00F6arna"; case "YE": return "Jemen"; case "YU": return "Jugoslavien"; case "ZA": return "Sydafrika"; } return base.ResolveCountry(name); } private class PrivateTextInfo : _I18NTextInfo { public PrivateTextInfo(int culture) : base(culture) {} public override int EBCDICCodePage { get { return 20278; } } public override int OEMCodePage { get { return 850; } } public override String ListSeparator { get { return ";"; } } }; // class PrivateTextInfo public override TextInfo TextInfo { get { return new PrivateTextInfo(LCID); } } }; // class CID001d public class CNsv : CID001d { public CNsv() : base() {} }; // class CNsv }; // namespace I18N.West
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /****************************************************************************** * This file is auto-generated from a template file by the GenerateTests.csx * * script in tests\src\JIT\HardwareIntrinsics\X86\Shared. In order to make * * changes, please update the corresponding template and run according to the * * directions listed in the file. * ******************************************************************************/ using System; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Intrinsics; using System.Runtime.Intrinsics.X86; namespace JIT.HardwareIntrinsics.X86 { public static partial class Program { private static void ConvertToVector128Int32UInt16() { var test = new SimpleUnaryOpTest__ConvertToVector128Int32UInt16(); if (test.IsSupported) { // Validates basic functionality works, using Unsafe.Read test.RunBasicScenario_UnsafeRead(); // Validates basic functionality works, using the pointer overload test.RunBasicScenario_Ptr(); if (Sse2.IsSupported) { // Validates basic functionality works, using Load test.RunBasicScenario_Load(); // Validates basic functionality works, using LoadAligned test.RunBasicScenario_LoadAligned(); } // Validates calling via reflection works, using Unsafe.Read test.RunReflectionScenario_UnsafeRead(); // Validates calling via reflection works, using the pointer overload test.RunReflectionScenario_Ptr(); if (Sse2.IsSupported) { // Validates calling via reflection works, using Load test.RunReflectionScenario_Load(); // Validates calling via reflection works, using LoadAligned test.RunReflectionScenario_LoadAligned(); } // Validates passing a static member works test.RunClsVarScenario(); // Validates passing a local works, using Unsafe.Read test.RunLclVarScenario_UnsafeRead(); if (Sse2.IsSupported) { // Validates passing a local works, using Load test.RunLclVarScenario_Load(); // Validates passing a local works, using LoadAligned test.RunLclVarScenario_LoadAligned(); } // Validates passing the field of a local works test.RunLclFldScenario(); // Validates passing an instance member works test.RunFldScenario(); } else { // Validates we throw on unsupported hardware test.RunUnsupportedScenario(); } if (!test.Succeeded) { throw new Exception("One or more scenarios did not complete as expected."); } } } public sealed unsafe class SimpleUnaryOpTest__ConvertToVector128Int32UInt16 { private static readonly int LargestVectorSize = 16; private static readonly int Op1ElementCount = Unsafe.SizeOf<Vector128<UInt16>>() / sizeof(UInt16); private static readonly int RetElementCount = Unsafe.SizeOf<Vector128<Int32>>() / sizeof(Int32); private static UInt16[] _data = new UInt16[Op1ElementCount]; private static Vector128<UInt16> _clsVar; private Vector128<UInt16> _fld; private SimpleUnaryOpTest__DataTable<Int32, UInt16> _dataTable; static SimpleUnaryOpTest__ConvertToVector128Int32UInt16() { var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _clsVar), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); } public SimpleUnaryOpTest__ConvertToVector128Int32UInt16() { Succeeded = true; var random = new Random(); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); } Unsafe.CopyBlockUnaligned(ref Unsafe.As<Vector128<UInt16>, byte>(ref _fld), ref Unsafe.As<UInt16, byte>(ref _data[0]), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); for (var i = 0; i < Op1ElementCount; i++) { _data[i] = (ushort)(random.Next(0, ushort.MaxValue)); } _dataTable = new SimpleUnaryOpTest__DataTable<Int32, UInt16>(_data, new Int32[RetElementCount], LargestVectorSize); } public bool IsSupported => Sse41.IsSupported; public bool Succeeded { get; set; } public void RunBasicScenario_UnsafeRead() { var result = Sse41.ConvertToVector128Int32( Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Ptr() { var result = Sse41.ConvertToVector128Int32( (UInt16*)(_dataTable.inArrayPtr) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_Load() { var result = Sse41.ConvertToVector128Int32( Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunBasicScenario_LoadAligned() { var result = Sse41.ConvertToVector128Int32( Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)) ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_UnsafeRead() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int32), new Type[] { typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Ptr() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int32), new Type[] { typeof(UInt16*) }) .Invoke(null, new object[] { Pointer.Box(_dataTable.inArrayPtr, typeof(UInt16*)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_Load() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int32), new Type[] { typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunReflectionScenario_LoadAligned() { var result = typeof(Sse41).GetMethod(nameof(Sse41.ConvertToVector128Int32), new Type[] { typeof(Vector128<UInt16>) }) .Invoke(null, new object[] { Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)) }); Unsafe.Write(_dataTable.outArrayPtr, (Vector128<Int32>)(result)); ValidateResult(_dataTable.inArrayPtr, _dataTable.outArrayPtr); } public void RunClsVarScenario() { var result = Sse41.ConvertToVector128Int32( _clsVar ); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_clsVar, _dataTable.outArrayPtr); } public void RunLclVarScenario_UnsafeRead() { var firstOp = Unsafe.Read<Vector128<UInt16>>(_dataTable.inArrayPtr); var result = Sse41.ConvertToVector128Int32(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_Load() { var firstOp = Sse2.LoadVector128((UInt16*)(_dataTable.inArrayPtr)); var result = Sse41.ConvertToVector128Int32(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclVarScenario_LoadAligned() { var firstOp = Sse2.LoadAlignedVector128((UInt16*)(_dataTable.inArrayPtr)); var result = Sse41.ConvertToVector128Int32(firstOp); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(firstOp, _dataTable.outArrayPtr); } public void RunLclFldScenario() { var test = new SimpleUnaryOpTest__ConvertToVector128Int32UInt16(); var result = Sse41.ConvertToVector128Int32(test._fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(test._fld, _dataTable.outArrayPtr); } public void RunFldScenario() { var result = Sse41.ConvertToVector128Int32(_fld); Unsafe.Write(_dataTable.outArrayPtr, result); ValidateResult(_fld, _dataTable.outArrayPtr); } public void RunUnsupportedScenario() { Succeeded = false; try { RunBasicScenario_UnsafeRead(); } catch (PlatformNotSupportedException) { Succeeded = true; } } private void ValidateResult(Vector128<UInt16> firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.WriteUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), firstOp); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(void* firstOp, void* result, [CallerMemberName] string method = "") { UInt16[] inArray = new UInt16[Op1ElementCount]; Int32[] outArray = new Int32[RetElementCount]; Unsafe.CopyBlockUnaligned(ref Unsafe.As<UInt16, byte>(ref inArray[0]), ref Unsafe.AsRef<byte>(firstOp), (uint)Unsafe.SizeOf<Vector128<UInt16>>()); Unsafe.CopyBlockUnaligned(ref Unsafe.As<Int32, byte>(ref outArray[0]), ref Unsafe.AsRef<byte>(result), (uint)Unsafe.SizeOf<Vector128<Int32>>()); ValidateResult(inArray, outArray, method); } private void ValidateResult(UInt16[] firstOp, Int32[] result, [CallerMemberName] string method = "") { if (result[0] != firstOp[0]) { Succeeded = false; } else { for (var i = 1; i < RetElementCount; i++) { if (result[i] != firstOp[i]) { Succeeded = false; break; } } } if (!Succeeded) { Console.WriteLine($"{nameof(Sse41)}.{nameof(Sse41.ConvertToVector128Int32)}<Int32>(Vector128<UInt16>): {method} failed:"); Console.WriteLine($" firstOp: ({string.Join(", ", firstOp)})"); Console.WriteLine($" result: ({string.Join(", ", result)})"); Console.WriteLine(); } } } }
#region License //L // 2007 - 2013 Copyright Northwestern University // // Distributed under the OSI-approved BSD 3-Clause License. // See http://ncip.github.com/annotation-and-image-markup/LICENSE.txt for details. //L #endregion using System; using System.Collections; using System.Collections.Generic; using System.Data; using DataServiceUtil; namespace AIMTCGAService { public class AIMTCGAAnnotationOfAnnotation : AIMTCGAQueryBase { public string[] getAnnotationOfAnnotationInfo(AIMQueryParameters queryParameters) { _queryParameters = queryParameters; string[] results = null; var result = getAnnotationOfAnnotationCQLInfo(); if (result != null && result.Items != null && result.Items.Length > 0) results = processCQLObjectResult(result); return results; } public List<aim_dotnet.Annotation> getAnnotationOfAnnotationInfoList(AIMQueryParameters queryParameters) { var annoStr = getAnnotationOfAnnotationInfo(queryParameters); if (annoStr == null) return null; var annotations = new List<aim_dotnet.Annotation>(); var xmlModel = new aim_dotnet.XmlModel(); foreach (var str in annoStr) { var annoAnnotation = xmlModel.ReadAnnotationFromXmlString(str) as aim_dotnet.AnnotationOfAnnotation; if (annoAnnotation != null) annotations.Add(annoAnnotation); } return annotations; } public DataTable codeTable(List<aim_dotnet.Annotation> annotations, string aimObjectType) { var table = new DataTable(); table.Columns.Add("codeValue"); table.Columns.Add("codeMeaning"); table.Columns.Add("codingSchemeDesignator"); foreach (aim_dotnet.AnnotationOfAnnotation annoAnnotation in annotations) { switch (aimObjectType) { case "AnatomicEntity": foreach (var ae in annoAnnotation.AnatomyEntityCollection) { DataRow dr = table.NewRow(); dr["codeValue"] = ae.CodeValue; dr["codeMeaning"] = ae.CodeMeaning; dr["codingSchemeDesignator"] = ae.CodingSchemeDesignator; table.Rows.Add(dr); } break; case "ImagingObservation": foreach (var ae in annoAnnotation.ImagingObservationCollection) { var dr = table.NewRow(); dr["codeValue"] = ae.CodeValue; dr["codeMeaning"] = ae.CodeMeaning; dr["codingSchemeDesignator"] = ae.CodingSchemeDesignator; table.Rows.Add(dr); } break; default: table = null; break; } } return table; } private CQLQueryResults getAnnotationOfAnnotationCQLInfo() { object[] obj = null; Attribute attrTemp = null; Association assoTemp = null; var proxy = new AIM3DataServicePortTypeClient(); proxy.Endpoint.Address = new System.ServiceModel.EndpointAddress(AIMDataServiceSettings.Default.AIMDataServiceUrl); var associationList = new ArrayList(); obj = null; Association aecAssociation = null; foreach (var queryData in _queryParameters.AecQueryParameters) { var results = new ArrayList(); if (!queryData.CodeValue.IsEmpty) results.Add(CreateAttribute("codeValue", queryData.CodeValue)); if (!queryData.CodeMeaning.IsEmpty) results.Add(CreateAttribute("codeMeaning", queryData.CodeMeaning)); if (!queryData.CodingSchemeDesignator.IsEmpty) results.Add(CreateAttribute("codingSchemeDesignator", queryData.CodingSchemeDesignator)); if (!queryData.CodingSchemeVersion.IsEmpty) results.Add(CreateAttribute("codingSchemeVersion", queryData.CodingSchemeVersion)); if (!queryData.Confidence.IsEmpty) results.Add(CreateAttribute("annotatorConfidence", queryData.Confidence)); if (results.Count > 0) obj = (object[])results.ToArray(typeof(object)); if (obj != null && obj.Length > 0) { Group grpAnnatomicEntityCharacteristic = null; if (obj.Length > 1) { grpAnnatomicEntityCharacteristic = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.AND); obj = null; } else attrTemp = obj[0] as Attribute; aecAssociation = CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.AnatomicEntityCharacteristic", "anatomicEntityCharacteristicCollection", grpAnnatomicEntityCharacteristic, attrTemp, null); } } obj = null; if (aecAssociation != null && _queryParameters.AeQueryParameters.Count == 0) { var queryData = new AimAnatomicEntityQueryData(); queryData.CodeMeaning = new QueryData(String.Empty, QueryPredicate.LIKE); _queryParameters.AeQueryParameters.Add(queryData); } foreach (var queryData in _queryParameters.AeQueryParameters) { var results = new ArrayList(); if (!queryData.CodeValue.IsEmpty) results.Add(CreateAttribute("codeValue", queryData.CodeValue)); //if (!queryData.CodeMeaning.IsEmpty) results.Add(CreateAttribute("codeMeaning", queryData.CodeMeaning)); if (!queryData.CodingSchemeDesignator.IsEmpty) results.Add(CreateAttribute("codingSchemeDesignator", queryData.CodingSchemeDesignator)); if (!queryData.CodingSchemeVersion.IsEmpty) results.Add(CreateAttribute("codingSchemeVersion", queryData.CodingSchemeVersion)); if (!queryData.Confidence.IsEmpty) results.Add(CreateAttribute("annotatorConfidence", queryData.Confidence)); if (aecAssociation != null) results.Add(aecAssociation); if (results.Count > 0) obj = (object[])results.ToArray(typeof(object)); if (obj != null && obj.Length > 0) { Group grpAnnatomicEntity = null; if (obj.Length > 1) { grpAnnatomicEntity = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.AND); obj = null; } else attrTemp = obj[0] as Attribute; associationList.Add(CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.AnatomicEntity", "anatomicEntityCollection", grpAnnatomicEntity, attrTemp, null)); } } obj = null; Association iocAssociation = null; foreach (var queryData in _queryParameters.ImcQueryParameters) { var results = new ArrayList(); if (!queryData.CodeValue.IsEmpty) results.Add(CreateAttribute("codeValue", queryData.CodeValue)); if (!queryData.CodeMeaning.IsEmpty) results.Add(CreateAttribute("codeMeaning", queryData.CodeMeaning)); if (!queryData.CodingSchemeDesignator.IsEmpty) results.Add(CreateAttribute("codingSchemeDesignator", queryData.CodingSchemeDesignator)); if (!queryData.CodingSchemeVersion.IsEmpty) results.Add(CreateAttribute("codingSchemeVersion", queryData.CodingSchemeVersion)); if (!queryData.Confidence.IsEmpty) results.Add(CreateAttribute("annotatorConfidence", queryData.Confidence)); if (!queryData.Comment.IsEmpty) results.Add(CreateAttribute("comment", queryData.Comment)); if (results.Count > 0) obj = (object[])results.ToArray(typeof(object)); if (obj != null && obj.Length > 0) { Group grpImagingObservationCharacteristic = null; if (obj.Length > 1) { grpImagingObservationCharacteristic = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.AND); obj = null; } else attrTemp = obj[0] as Attribute; iocAssociation = CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.ImagingObservationCharacteristic", "imagingObservationCharacteristicCollection", grpImagingObservationCharacteristic, attrTemp, null); } } obj = null; if (iocAssociation != null && _queryParameters.ImQueryParameters.Count == 0) { var queryData = new AimImagingObservationQueryData(); queryData.CodeMeaning = new QueryData(String.Empty, QueryPredicate.LIKE); _queryParameters.ImQueryParameters.Add(queryData); } foreach (var queryData in _queryParameters.ImQueryParameters) { var results = new ArrayList(); if (!queryData.CodeValue.IsEmpty) results.Add(CreateAttribute("codeValue", queryData.CodeValue)); //if (!queryData.CodeMeaning.IsEmpty) results.Add(CreateAttribute("codeMeaning", queryData.CodeMeaning)); if (!queryData.CodingSchemeDesignator.IsEmpty) results.Add(CreateAttribute("codingSchemeDesignator", queryData.CodingSchemeDesignator)); if (!queryData.CodingSchemeVersion.IsEmpty) results.Add(CreateAttribute("codingSchemeVersion", queryData.CodingSchemeVersion)); if (!queryData.Comment.IsEmpty) results.Add(CreateAttribute("comment", queryData.Comment)); if (!queryData.Confidence.IsEmpty) results.Add(CreateAttribute("annotatorConfidence", queryData.Confidence)); if (iocAssociation != null) results.Add(iocAssociation); if (results.Count > 0) obj = (object[])results.ToArray(typeof(object)); if (obj != null && obj.Length > 0) { attrTemp = null; Group grpImagingObservation = null; if (obj.Length > 1) { grpImagingObservation = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.AND); obj = null; } else attrTemp = obj[0] as Attribute; associationList.Add(CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.ImagingObservation", "imagingObservationCollection", grpImagingObservation, attrTemp, null)); } } obj = null; foreach (var queryData in _queryParameters.UserParameters) { var results = new ArrayList(); if (!queryData.IsEmpty) { results.Add(CreateAttribute("loginName", queryData)); results.Add(CreateAttribute("name", queryData)); } if (results.Count > 0) obj = (object[])results.ToArray(typeof(Attribute)); if (obj != null && obj.Length > 0) { Group grpAnnatomicEntityCharacteristic = null; if (obj.Length > 1) { grpAnnatomicEntityCharacteristic = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.OR); obj = null; } else attrTemp = obj[0] as Attribute; associationList.Add(CreateQRAttrAssoGroup.createAssociation("edu.northwestern.radiology.aim.User", "user", grpAnnatomicEntityCharacteristic, attrTemp, null)); } } obj = null; Group grpAnnotationOfAnnotation = null; if (associationList.Count > 0) obj = (object[])associationList.ToArray(typeof(Association)); if (obj != null && obj.Length > 0) { assoTemp = null; if (obj.Length > 1) grpAnnotationOfAnnotation = CreateQRAttrAssoGroup.createGroup(obj, LogicalOperator.AND); else assoTemp = obj[0] as Association; } var arg = CreateQRAttrAssoGroup.createQueryRequestCqlQuery("edu.northwestern.radiology.aim.AnnotationOfAnnotation", null, null, assoTemp, grpAnnotationOfAnnotation); var doc = XMLSerializingDeserializing.Serialize(arg); Console.WriteLine(doc.InnerXml); CQLQueryResults result; try { result = proxy.query(arg); } catch (System.Net.WebException ex) { Console.WriteLine(ex.Message); result = null; } catch (Exception e) { Console.WriteLine(e.Message); result = null; throw new GridServicerException("Error querying AIM data service", e); } return result; } } }
#region Copyright & License // // Author: Ian Davis <ian.f.davis@gmail.com> // Copyright (c) 2007, Ian Davs // // Portions of this software were developed for NUnit. // See NOTICE.txt for more information. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // #endregion using System; using System.Collections; using Ensurance.MessageWriters; using Ensurance.SyntaxHelpers; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Ensurance.Tests { /// <summary> /// Summary description for ArrayEqualsFailureMessageFixture. /// </summary> [TestClass] public class ArrayEqualsFailureMessageFixture : MessageChecker { [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void ArraysHaveDifferentRanks() { int[] expected = new int[] {1, 2, 3, 4}; int[,] actual = new int[,] {{1, 2}, {3, 4}}; expectedMessage = " Expected is <System.Int32[4]>, actual is <System.Int32[2,2]>" + Environment.NewLine; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void ExpectedArrayIsLonger() { int[] expected = new int[] {1, 2, 3, 4, 5}; int[] actual = new int[] {1, 2, 3}; expectedMessage = " Expected is <System.Int32[5]>, actual is <System.Int32[3]>" + Environment.NewLine + " Values differ at index [3]" + Environment.NewLine + " Missing: < 4, 5 >"; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void ActualArrayIsLonger() { int[] expected = new int[] {1, 2, 3}; int[] actual = new int[] {1, 2, 3, 4, 5, 6, 7}; expectedMessage = " Expected is <System.Int32[3]>, actual is <System.Int32[7]>" + Environment.NewLine + " Values differ at index [3]" + Environment.NewLine + " Extra: < 4, 5, 6... >"; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void FailureOnSingleDimensionedArrays() { int[] expected = new int[] {1, 2, 3}; int[] actual = new int[] {1, 5, 3}; expectedMessage = " Expected and actual are both <System.Int32[3]>" + Environment.NewLine + " Values differ at index [1]" + Environment.NewLine + TextMessageWriter.Pfx_Expected + "2" + Environment.NewLine + TextMessageWriter.Pfx_Actual + "5" + Environment.NewLine; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void DoubleDimensionedArrays() { int[,] expected = new int[,] {{1, 2, 3}, {4, 5, 6}}; int[,] actual = new int[,] {{1, 3, 2}, {4, 0, 6}}; expectedMessage = " Expected and actual are both <System.Int32[2,3]>" + Environment.NewLine + " Values differ at index [0,1]" + Environment.NewLine + TextMessageWriter.Pfx_Expected + "2" + Environment.NewLine + TextMessageWriter.Pfx_Actual + "3" + Environment.NewLine; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void TripleDimensionedArrays() { int[,,] expected = new int[,,] {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}; int[,,] actual = new int[,,] {{{1, 2}, {3, 4}}, {{0, 6}, {7, 8}}}; expectedMessage = " Expected and actual are both <System.Int32[2,2,2]>" + Environment.NewLine + " Values differ at index [1,0,0]" + Environment.NewLine + TextMessageWriter.Pfx_Expected + "5" + Environment.NewLine + TextMessageWriter.Pfx_Actual + "0" + Environment.NewLine; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void FiveDimensionedArrays() { int[,,,,] expected = new int[2,2,2,2,2] {{{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}, {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}}, {{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}, {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}}}; int[,,,,] actual = new int[2,2,2,2,2] {{{{{1, 2}, {4, 3}}, {{5, 6}, {7, 8}}}, {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}}, {{{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}, {{{1, 2}, {3, 4}}, {{5, 6}, {7, 8}}}}}; expectedMessage = " Expected and actual are both <System.Int32[2,2,2,2,2]>" + Environment.NewLine + " Values differ at index [0,0,0,1,0]" + Environment.NewLine + TextMessageWriter.Pfx_Expected + "3" + Environment.NewLine + TextMessageWriter.Pfx_Actual + "4" + Environment.NewLine; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void JaggedArrays() { int[][] expected = new int[][] {new int[] {1, 2, 3}, new int[] {4, 5, 6, 7}, new int[] {8, 9}}; int[][] actual = new int[][] {new int[] {1, 2, 3}, new int[] {4, 5, 0, 7}, new int[] {8, 9}}; expectedMessage = " Expected and actual are both <System.Int32[3][]>" + Environment.NewLine + " Values differ at index [1]" + Environment.NewLine + " Expected and actual are both <System.Int32[4]>" + Environment.NewLine + " Values differ at index [2]" + Environment.NewLine + TextMessageWriter.Pfx_Expected + "6" + Environment.NewLine + TextMessageWriter.Pfx_Actual + "0" + Environment.NewLine; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void JaggedArrayComparedToSimpleArray() { int[] expected = new int[] {1, 2, 3, 4, 5, 6, 7, 8, 9}; int[][] actual = new int[][] {new int[] {1, 2, 3}, new int[] {4, 5, 0, 7}, new int[] {8, 9}}; expectedMessage = " Expected is <System.Int32[9]>, actual is <System.Int32[3][]>" + Environment.NewLine + " Values differ at index [0]" + Environment.NewLine + TextMessageWriter.Pfx_Expected + "1" + Environment.NewLine + TextMessageWriter.Pfx_Actual + "< 1, 2, 3 >" + Environment.NewLine; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void ArraysWithDifferentRanksAsCollection() { int[] expected = new int[] {1, 2, 3, 4}; int[,] actual = new int[,] {{1, 0}, {3, 4}}; expectedMessage = " Expected is <System.Int32[4]>, actual is <System.Int32[2,2]>" + Environment.NewLine + " Values differ at expected index [1], actual index [0,1]" + Environment.NewLine + TextMessageWriter.Pfx_Expected + "2" + Environment.NewLine + TextMessageWriter.Pfx_Actual + "0" + Environment.NewLine; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ).AsCollection ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void ArraysWithDifferentDimensionsAsCollection() { int[,] expected = new int[,] {{1, 2, 3}, {4, 5, 6}}; int[,] actual = new int[,] {{1, 2}, {3, 0}, {5, 6}}; expectedMessage = " Expected is <System.Int32[2,3]>, actual is <System.Int32[3,2]>" + Environment.NewLine + " Values differ at expected index [1,0], actual index [1,1]" + Environment.NewLine + TextMessageWriter.Pfx_Expected + "4" + Environment.NewLine + TextMessageWriter.Pfx_Actual + "0" + Environment.NewLine; EnsuranceHelper.Expect( actual, Is.EqualTo( expected ).AsCollection ); } // [TestMethod,ExpectedException(typeof(EnsuranceException))] // public void ExpectedArrayIsLonger() // { // string[] array1 = { "one", "two", "three" }; // string[] array2 = { "one", "two", "three", "four", "five" }; // // expectedMessage = // " Expected is <System.String[5]>, actual is <System.String[3]>" + Environment.NewLine + // " Values differ at index [3]" + Environment.NewLine + // " Missing: < \"four\", \"five\" >"; // EnsuranceHelper.Expect(array1, Is.EqualTo(array2)); // } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void SameLengthDifferentContent() { string[] array1 = {"one", "two", "three"}; string[] array2 = {"one", "two", "ten"}; expectedMessage = " Expected and actual are both <System.String[3]>" + Environment.NewLine + " Values differ at index [2]" + Environment.NewLine + " Expected string length 3 but was 5. Strings differ at index 1." + Environment.NewLine + " Expected: \"ten\"" + Environment.NewLine + " But was: \"three\"" + Environment.NewLine + " ------------^" + Environment.NewLine; EnsuranceHelper.Expect( array1, Is.EqualTo( array2 ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void ArraysDeclaredAsDifferentTypes() { string[] array1 = {"one", "two", "three"}; object[] array2 = {"one", "three", "two"}; expectedMessage = " Expected is <System.Object[3]>, actual is <System.String[3]>" + Environment.NewLine + " Values differ at index [1]" + Environment.NewLine + " Expected string length 5 but was 3. Strings differ at index 1." + Environment.NewLine + " Expected: \"three\"" + Environment.NewLine + " But was: \"two\"" + Environment.NewLine + " ------------^" + Environment.NewLine; EnsuranceHelper.Expect( array1, Is.EqualTo( array2 ) ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void ArrayAndCollection_Failure() { int[] a = new int[] {1, 2, 3}; ArrayList b = new ArrayList(); b.Add( 1 ); b.Add( 3 ); Ensure.AreEqual( a, b ); } [TestMethod, ExpectedException( typeof (EnsuranceException) )] public void DifferentArrayTypesEqualFails() { string[] array1 = {"one", "two", "three"}; object[] array2 = {"one", "three", "two"}; expectedMessage = " Expected is <System.String[3]>, actual is <System.Object[3]>" + Environment.NewLine + " Values differ at index [1]" + Environment.NewLine + " Expected string length 3 but was 5. Strings differ at index 1." + Environment.NewLine + " Expected: \"two\"" + Environment.NewLine + " But was: \"three\"" + Environment.NewLine + " ------------^" + Environment.NewLine; Ensure.AreEqual( array1, array2 ); } } }
#region License /* * All content copyright Terracotta, Inc., unless otherwise indicated. 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. * */ #endregion using System; using System.Collections; using System.Collections.Generic; using System.Globalization; using System.Runtime.Serialization; namespace Quartz.Util { /// <summary> /// An implementation of <see cref="IDictionary" /> that wraps another <see cref="IDictionary" /> /// and flags itself 'dirty' when it is modified, enforces that all keys are /// strings. /// </summary> /// <author>Marko Lahma (.NET)</author> [Serializable] public class StringKeyDirtyFlagMap : DirtyFlagMap<string, object> { /// <summary> /// Initializes a new instance of the <see cref="StringKeyDirtyFlagMap"/> class. /// </summary> public StringKeyDirtyFlagMap() { } /// <summary> /// Initializes a new instance of the <see cref="StringKeyDirtyFlagMap"/> class. /// </summary> /// <param name="initialCapacity">The initial capacity.</param> public StringKeyDirtyFlagMap(int initialCapacity) : base(initialCapacity) { } /// <summary> /// Serialization constructor. /// </summary> /// <param name="info"></param> /// <param name="context"></param> protected StringKeyDirtyFlagMap(SerializationInfo info, StreamingContext context) : base(info, context) { } /// <summary> /// Determines whether the specified <see cref="T:System.Object"/> is equal to the current <see cref="T:System.Object"/>. /// </summary> /// <param name="obj">The <see cref="T:System.Object"/> to compare with the current <see cref="T:System.Object"/>.</param> /// <returns> /// <see langword="true"/> if the specified <see cref="T:System.Object"/> is equal to the /// current <see cref="T:System.Object"/>; otherwise, <see langword="false"/>. /// </returns> public override bool Equals(Object obj) { return base.Equals(obj); } /// <summary> /// Serves as a hash function for a particular type, suitable /// for use in hashing algorithms and data structures like a hash table. /// </summary> /// <returns> /// A hash code for the current <see cref="T:System.Object"/>. /// </returns> public override int GetHashCode() { return WrappedMap.GetHashCode(); } /// <summary> /// Gets the keys. /// </summary> /// <returns></returns> public virtual IList<string> GetKeys() { return new List<string>(KeySet()); } /// <summary> /// Adds the name-value pairs in the given <see cref="IDictionary" /> to the <see cref="JobDataMap" />. /// <para> /// All keys must be <see cref="String" />s, and all values must be serializable. /// </para> /// </summary> public override void PutAll(IDictionary<string, object> map) { foreach (KeyValuePair<string, object> pair in map) { Put(pair.Key, pair.Value); // will throw ArgumentException if value not serializable } } /// <summary> /// Adds the given <see cref="int" /> value to the <see cref="IJob" />'s /// data map. /// </summary> public virtual void Put(string key, int value) { base.Put(key, value); } /// <summary> /// Adds the given <see cref="long" /> value to the <see cref="IJob" />'s /// data map. /// </summary> public virtual void Put(string key, long value) { base.Put(key, value); } /// <summary> /// Adds the given <see cref="float" /> value to the <see cref="IJob" />'s /// data map. /// </summary> public virtual void Put(string key, float value) { base.Put(key, value); } /// <summary> /// Adds the given <see cref="double" /> value to the <see cref="IJob" />'s /// data map. /// </summary> public virtual void Put(string key, double value) { base.Put(key, value); } /// <summary> /// Adds the given <see cref="bool" /> value to the <see cref="IJob" />'s /// data map. /// </summary> public virtual void Put(string key, bool value) { base.Put(key, value); } /// <summary> /// Adds the given <see cref="char" /> value to the <see cref="IJob" />'s /// data map. /// </summary> public virtual void Put(string key, char value) { base.Put(key, value); } /// <summary> /// Adds the given <see cref="String" /> value to the <see cref="IJob" />'s /// data map. /// </summary> public virtual void Put(string key, string value) { base.Put(key, value); } /// <summary> /// Retrieve the identified <see cref="int" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual int GetInt(string key) { object obj = this[key]; try { return Convert.ToInt32(obj); } catch (Exception) { throw new InvalidCastException("Identified object is not an Integer."); } } /// <summary> /// Retrieve the identified <see cref="long" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual long GetLong(string key) { object obj = this[key]; try { return Convert.ToInt64(obj); } catch (Exception) { throw new InvalidCastException("Identified object is not a Long."); } } /// <summary> /// Retrieve the identified <see cref="float" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual float GetFloat(string key) { object obj = this[key]; try { return Convert.ToSingle(obj); } catch (Exception) { throw new InvalidCastException("Identified object is not a Float."); } } /// <summary> /// Retrieve the identified <see cref="double" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual double GetDouble(string key) { object obj = this[key]; try { return Convert.ToDouble(obj); } catch (Exception) { throw new InvalidCastException("Identified object is not a Double."); } } /// <summary> /// Retrieve the identified <see cref="bool" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual bool GetBoolean(string key) { object obj = this[key]; try { return Convert.ToBoolean(obj); } catch (Exception) { throw new InvalidCastException("Identified object is not a Boolean."); } } /// <summary> /// Retrieve the identified <see cref="char" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual char GetChar(string key) { object obj = this[key]; try { return Convert.ToChar(obj); } catch (Exception) { throw new InvalidCastException("Identified object is not a Character."); } } /// <summary> /// Retrieve the identified <see cref="String" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual string GetString(string key) { object obj = this[key]; try { return (string) obj; } catch (Exception) { throw new InvalidCastException("Identified object is not a String."); } } /// <summary> /// Retrieve the identified <see cref="DateTime" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual DateTime GetDateTime(string key) { object obj = this[key]; try { return Convert.ToDateTime(obj, CultureInfo.InvariantCulture); } catch (Exception) { throw new InvalidCastException("Identified object is not a DateTime."); } } /// <summary> /// Retrieve the identified <see cref="DateTimeOffset" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual DateTimeOffset GetDateTimeOffset(string key) { object obj = this[key]; return (DateTimeOffset) obj; } /// <summary> /// Retrieve the identified <see cref="TimeSpan" /> value from the <see cref="JobDataMap" />. /// </summary> public virtual TimeSpan GetTimeSpan(string key) { object obj = this[key]; return (TimeSpan) obj; } } }
// 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 Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.ReorderParameters { public partial class ReorderParametersTests { #region Methods [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeBeforeMethodName() { var markup = @" using System; class MyClass { public void $$Foo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeInParameterList() { var markup = @" using System; class MyClass { public void Foo(int x, $$string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeAfterParameterList() { var markup = @" using System; class MyClass { public void Foo(int x, string y)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeBeforeMethodDeclaration() { var markup = @" using System; class MyClass { $$public void Foo(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnMetadataReference_InIdentifier_ShouldFail() { var markup = @" class C { static void Main(string[] args) { ((System.IFormattable)null).ToSt$$ring(""test"", null); } }"; TestReorderParameters(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.TheMemberIsDefinedInMetadata); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnMetadataReference_AtBeginningOfInvocation_ShouldFail() { var markup = @" class C { static void Main(string[] args) { $$((System.IFormattable)null).ToString(""test"", null); } }"; TestReorderParameters(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.TheMemberIsDefinedInMetadata); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnMetadataReference_InArgumentsOfInvocation_ShouldFail() { var markup = @" class C { static void Main(string[] args) { ((System.IFormattable)null).ToString(""test"",$$ null); } }"; TestReorderParameters(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.TheMemberIsDefinedInMetadata); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnMetadataReference_AfterInvocation_ShouldFail() { var markup = @" class C { string s = ((System.IFormattable)null).ToString(""test"", null)$$; }"; TestReorderParameters(LanguageNames.CSharp, markup, expectedSuccess: false, expectedErrorText: FeaturesResources.YouCanOnlyChangeTheSignatureOfAConstructorIndexerMethodOrDelegate); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeInMethodBody() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { $$ } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(string y, int x) { } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnReference_BeginningOfIdentifier() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { $$Bar(x, y); } public void Bar(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, x); } public void Bar(string y, int x) { } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnReference_ArgumentList() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { $$Bar(x, y); } public void Bar(int x, string y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, x); } public void Bar(string y, int x) { } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnReference_NestedCalls1() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { Bar($$Baz(x, y), y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(Baz(y, x), y); } public void Bar(int x, string y) { } public int Baz(string y, int x) { return 1; } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnReference_NestedCalls2() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { Bar$$(Baz(x, y), y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, Baz(x, y)); } public void Bar(string y, int x) { } public int Baz(int x, string y) { return 1; } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnReference_NestedCalls3() { var markup = @" using System; class MyClass { public void Foo(int x, string y) { Bar(Baz(x, y), $$y); } public void Bar(int x, string y) { } public int Baz(int x, string y) { return 1; } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; class MyClass { public void Foo(int x, string y) { Bar(y, Baz(x, y)); } public void Bar(string y, int x) { } public int Baz(int x, string y) { return 1; } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnReference_Attribute() { var markup = @" using System; [$$My(1, 2)] class MyAttribute : Attribute { public MyAttribute(int x, int y) { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" using System; [My(2, 1)] class MyAttribute : Attribute { public MyAttribute(int y, int x) { } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnReference_OnlyHasCandidateSymbols() { var markup = @" class Test { void M(int x, string y) { } void M(int x, double y) { } void M2() { $$M(""s"", 1); } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Test { void M(string y, int x) { } void M(int x, double y) { } void M2() { M(1, ""s""); } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnReference_CallToOtherConstructor() { var markup = @" class Program { public Program(int x, int y) : this(1, 2, 3)$$ { } public Program(int x, int y, int z) { } }"; var permutation = new[] { 2, 1, 0 }; var updatedCode = @" class Program { public Program(int x, int y) : this(3, 2, 1) { } public Program(int z, int y, int x) { } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderMethodParameters_InvokeOnReference_CallToBaseConstructor() { var markup = @" class B { public B(int a, int b) { } } class D : B { public D(int x, int y) : base(1, 2)$$ { } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class B { public B(int b, int a) { } } class D : B { public D(int x, int y) : base(2, 1) { } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion #region Indexers [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderIndexerParameters_InvokeAtBeginningOfDeclaration() { var markup = @" class Program { $$int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderIndexerParameters_InParameters() { var markup = @" class Program { int this[int x, $$string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderIndexerParameters_InvokeAtEndOfDeclaration() { var markup = @" class Program { int this[int x, string y]$$ { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderIndexerParameters_InvokeInAccessor() { var markup = @" class Program { int this[int x, string y] { get { return $$5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { int this[string y, int x] { get { return 5; } set { } } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderIndexerParameters_InvokeOnReference_BeforeTarget() { var markup = @" class Program { void M(Program p) { var t = $$p[5, ""test""]; } int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(Program p) { var t = p[""test"", 5]; } int this[string y, int x] { get { return 5; } set { } } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } [Fact, Trait(Traits.Feature, Traits.Features.ReorderParameters)] public void ReorderIndexerParameters_InvokeOnReference_InArgumentList() { var markup = @" class Program { void M(Program p) { var t = p[5, ""test""$$]; } int this[int x, string y] { get { return 5; } set { } } }"; var permutation = new[] { 1, 0 }; var updatedCode = @" class Program { void M(Program p) { var t = p[""test"", 5]; } int this[string y, int x] { get { return 5; } set { } } }"; TestReorderParameters(LanguageNames.CSharp, markup, permutation: permutation, expectedUpdatedInvocationDocumentCode: updatedCode); } #endregion } }
// // 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.Globalization; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Xml.Linq; using Hyak.Common; using Hyak.Common.Internals; using Microsoft.Azure; using Microsoft.WindowsAzure.Management.Scheduler; using Microsoft.WindowsAzure.Management.Scheduler.Models; namespace Microsoft.WindowsAzure.Management.Scheduler { internal partial class JobCollectionOperations : IServiceOperations<SchedulerManagementClient>, IJobCollectionOperations { /// <summary> /// Initializes a new instance of the JobCollectionOperations class. /// </summary> /// <param name='client'> /// Reference to the service client. /// </param> internal JobCollectionOperations(SchedulerManagementClient client) { this._client = client; } private SchedulerManagementClient _client; /// <summary> /// Gets a reference to the /// Microsoft.WindowsAzure.Management.Scheduler.SchedulerManagementClient. /// </summary> public SchedulerManagementClient Client { get { return this._client; } } /// <summary> /// Create a job collection. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service containing the job /// collection. /// </param> /// <param name='jobCollectionName'> /// Required. The name of the job collection to create. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Job Collection /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Create Job Collection operation response. /// </returns> public async Task<JobCollectionCreateResponse> BeginCreatingAsync(string cloudServiceName, string jobCollectionName, JobCollectionCreateParameters parameters, CancellationToken cancellationToken) { // Validate if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (jobCollectionName == null) { throw new ArgumentNullException("jobCollectionName"); } if (jobCollectionName.Length > 100) { throw new ArgumentOutOfRangeException("jobCollectionName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("jobCollectionName", jobCollectionName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginCreatingAsync", tracingParameters); } // Construct URL string url = ""; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(cloudServiceName); url = url + "/resources/"; url = url + "scheduler"; url = url + "/"; url = url + "JobCollections"; url = url + "/"; url = url + Uri.EscapeDataString(jobCollectionName); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(resourceElement); if (parameters.SchemaVersion != null) { XElement schemaVersionElement = new XElement(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure")); schemaVersionElement.Value = parameters.SchemaVersion; resourceElement.Add(schemaVersionElement); } if (parameters.IntrinsicSettings != null) { XElement intrinsicSettingsElement = new XElement(XName.Get("IntrinsicSettings", "http://schemas.microsoft.com/windowsazure")); resourceElement.Add(intrinsicSettingsElement); XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure")); planElement.Value = parameters.IntrinsicSettings.Plan.ToString(); intrinsicSettingsElement.Add(planElement); if (parameters.IntrinsicSettings.Quota != null) { XElement quotaElement = new XElement(XName.Get("Quota", "http://schemas.microsoft.com/windowsazure")); intrinsicSettingsElement.Add(quotaElement); if (parameters.IntrinsicSettings.Quota.MaxJobCount != null) { XElement maxJobCountElement = new XElement(XName.Get("MaxJobCount", "http://schemas.microsoft.com/windowsazure")); maxJobCountElement.Value = parameters.IntrinsicSettings.Quota.MaxJobCount.ToString(); quotaElement.Add(maxJobCountElement); } if (parameters.IntrinsicSettings.Quota.MaxJobOccurrence != null) { XElement maxJobOccurrenceElement = new XElement(XName.Get("MaxJobOccurrence", "http://schemas.microsoft.com/windowsazure")); maxJobOccurrenceElement.Value = parameters.IntrinsicSettings.Quota.MaxJobOccurrence.ToString(); quotaElement.Add(maxJobOccurrenceElement); } if (parameters.IntrinsicSettings.Quota.MaxRecurrence != null) { XElement maxRecurrenceElement = new XElement(XName.Get("MaxRecurrence", "http://schemas.microsoft.com/windowsazure")); quotaElement.Add(maxRecurrenceElement); XElement frequencyElement = new XElement(XName.Get("Frequency", "http://schemas.microsoft.com/windowsazure")); frequencyElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Frequency.ToString(); maxRecurrenceElement.Add(frequencyElement); XElement intervalElement = new XElement(XName.Get("Interval", "http://schemas.microsoft.com/windowsazure")); intervalElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Interval.ToString(); maxRecurrenceElement.Add(intervalElement); } } } if (parameters.Label != null) { XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = TypeConversion.ToBase64String(parameters.Label); resourceElement.Add(labelElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobCollectionCreateResponse result = null; // Deserialize Response result = new JobCollectionCreateResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Deletes a job collection. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service. /// </param> /// <param name='jobCollectionName'> /// Required. The name of the job collection to delete. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// A standard service response including an HTTP status code and /// request ID. /// </returns> public async Task<AzureOperationResponse> BeginDeletingAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken) { // Validate if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (jobCollectionName == null) { throw new ArgumentNullException("jobCollectionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("jobCollectionName", jobCollectionName); TracingAdapter.Enter(invocationId, this, "BeginDeletingAsync", tracingParameters); } // Construct URL string url = ""; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(cloudServiceName); url = url + "/resources/"; url = url + "scheduler"; url = url + "/"; url = url + "JobCollections"; url = url + "/"; url = url + Uri.EscapeDataString(jobCollectionName); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Delete; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result AzureOperationResponse result = null; // Deserialize Response result = new AzureOperationResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update a job collection. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service containing the job /// collection. /// </param> /// <param name='jobCollectionName'> /// Required. The name of the job collection to update. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Job Collection /// operation. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Update Job Collection operation response. /// </returns> public async Task<JobCollectionUpdateResponse> BeginUpdatingAsync(string cloudServiceName, string jobCollectionName, JobCollectionUpdateParameters parameters, CancellationToken cancellationToken) { // Validate if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (jobCollectionName == null) { throw new ArgumentNullException("jobCollectionName"); } if (jobCollectionName.Length > 100) { throw new ArgumentOutOfRangeException("jobCollectionName"); } if (parameters == null) { throw new ArgumentNullException("parameters"); } if (parameters.ETag == null) { throw new ArgumentNullException("parameters.ETag"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("jobCollectionName", jobCollectionName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "BeginUpdatingAsync", tracingParameters); } // Construct URL string url = ""; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(cloudServiceName); url = url + "/resources/"; url = url + "scheduler"; url = url + "/"; url = url + "JobCollections"; url = url + "/"; url = url + Uri.EscapeDataString(jobCollectionName); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Put; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.TryAddWithoutValidation("If-Match", parameters.ETag); httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Serialize Request string requestContent = null; XDocument requestDoc = new XDocument(); XElement resourceElement = new XElement(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure")); requestDoc.Add(resourceElement); if (parameters.SchemaVersion != null) { XElement schemaVersionElement = new XElement(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure")); schemaVersionElement.Value = parameters.SchemaVersion; resourceElement.Add(schemaVersionElement); } XElement eTagElement = new XElement(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure")); resourceElement.Add(eTagElement); if (parameters.IntrinsicSettings != null) { XElement intrinsicSettingsElement = new XElement(XName.Get("IntrinsicSettings", "http://schemas.microsoft.com/windowsazure")); resourceElement.Add(intrinsicSettingsElement); XElement planElement = new XElement(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure")); planElement.Value = parameters.IntrinsicSettings.Plan.ToString(); intrinsicSettingsElement.Add(planElement); if (parameters.IntrinsicSettings.Quota != null) { XElement quotaElement = new XElement(XName.Get("Quota", "http://schemas.microsoft.com/windowsazure")); intrinsicSettingsElement.Add(quotaElement); if (parameters.IntrinsicSettings.Quota.MaxJobCount != null) { XElement maxJobCountElement = new XElement(XName.Get("MaxJobCount", "http://schemas.microsoft.com/windowsazure")); maxJobCountElement.Value = parameters.IntrinsicSettings.Quota.MaxJobCount.ToString(); quotaElement.Add(maxJobCountElement); } if (parameters.IntrinsicSettings.Quota.MaxJobOccurrence != null) { XElement maxJobOccurrenceElement = new XElement(XName.Get("MaxJobOccurrence", "http://schemas.microsoft.com/windowsazure")); maxJobOccurrenceElement.Value = parameters.IntrinsicSettings.Quota.MaxJobOccurrence.ToString(); quotaElement.Add(maxJobOccurrenceElement); } if (parameters.IntrinsicSettings.Quota.MaxRecurrence != null) { XElement maxRecurrenceElement = new XElement(XName.Get("MaxRecurrence", "http://schemas.microsoft.com/windowsazure")); quotaElement.Add(maxRecurrenceElement); XElement frequencyElement = new XElement(XName.Get("Frequency", "http://schemas.microsoft.com/windowsazure")); frequencyElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Frequency.ToString(); maxRecurrenceElement.Add(frequencyElement); XElement intervalElement = new XElement(XName.Get("Interval", "http://schemas.microsoft.com/windowsazure")); intervalElement.Value = parameters.IntrinsicSettings.Quota.MaxRecurrence.Interval.ToString(); maxRecurrenceElement.Add(intervalElement); } } } if (parameters.Label != null) { XElement labelElement = new XElement(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); labelElement.Value = TypeConversion.ToBase64String(parameters.Label); resourceElement.Add(labelElement); } requestContent = requestDoc.ToString(); httpRequest.Content = new StringContent(requestContent, Encoding.UTF8); httpRequest.Content.Headers.ContentType = MediaTypeHeaderValue.Parse("application/xml"); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.Accepted) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, requestContent, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobCollectionUpdateResponse result = null; // Deserialize Response result = new JobCollectionUpdateResponse(); result.StatusCode = statusCode; if (httpResponse.Headers.Contains("ETag")) { result.ETag = httpResponse.Headers.GetValues("ETag").FirstOrDefault(); } if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Determine if the JobCollection name is available to be used. /// JobCollection names must be unique within a cloud-service. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service. /// </param> /// <param name='jobCollectionName'> /// Required. A name for the JobCollection. The name must be unique as /// scoped within the CloudService. The name can be up to 100 /// characters in length. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Check Name Availability operation response. /// </returns> public async Task<JobCollectionCheckNameAvailabilityResponse> CheckNameAvailabilityAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken) { // Validate if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (jobCollectionName == null) { throw new ArgumentNullException("jobCollectionName"); } if (jobCollectionName.Length > 100) { throw new ArgumentOutOfRangeException("jobCollectionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("jobCollectionName", jobCollectionName); TracingAdapter.Enter(invocationId, this, "CheckNameAvailabilityAsync", tracingParameters); } // Construct URL string url = ""; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(cloudServiceName); url = url + "/resources/"; url = url + "scheduler"; url = url + "/"; url = url + "JobCollections"; url = url + "/"; List<string> queryParameters = new List<string>(); queryParameters.Add("op=checknameavailability"); queryParameters.Add("resourceName=" + Uri.EscapeDataString(jobCollectionName)); if (queryParameters.Count > 0) { url = url + "?" + string.Join("&", queryParameters); } string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobCollectionCheckNameAvailabilityResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobCollectionCheckNameAvailabilityResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement resourceNameAvailabilityResponseElement = responseDoc.Element(XName.Get("ResourceNameAvailabilityResponse", "http://schemas.microsoft.com/windowsazure")); if (resourceNameAvailabilityResponseElement != null) { XElement isAvailableElement = resourceNameAvailabilityResponseElement.Element(XName.Get("IsAvailable", "http://schemas.microsoft.com/windowsazure")); if (isAvailableElement != null) { bool isAvailableInstance = bool.Parse(isAvailableElement.Value); result.IsAvailable = isAvailableInstance; } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Create a job collection. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service containing the job /// collection. /// </param> /// <param name='jobCollectionName'> /// Required. The name of the job collection to create. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Create Job Collection /// operation. /// </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<SchedulerOperationStatusResponse> CreateAsync(string cloudServiceName, string jobCollectionName, JobCollectionCreateParameters parameters, CancellationToken cancellationToken) { SchedulerManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("jobCollectionName", jobCollectionName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "CreateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); JobCollectionCreateResponse response = await client.JobCollections.BeginCreatingAsync(cloudServiceName, jobCollectionName, parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); SchedulerOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 15; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != SchedulerOperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 10; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != SchedulerOperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } result.ETag = response.ETag; return result; } /// <summary> /// Deletes a job collection. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service. /// </param> /// <param name='jobCollectionName'> /// Required. The name of the job collection to delete. /// </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<SchedulerOperationStatusResponse> DeleteAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken) { SchedulerManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("jobCollectionName", jobCollectionName); TracingAdapter.Enter(invocationId, this, "DeleteAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); AzureOperationResponse response = await client.JobCollections.BeginDeletingAsync(cloudServiceName, jobCollectionName, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); SchedulerOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 15; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != SchedulerOperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 10; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != SchedulerOperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } return result; } /// <summary> /// Retreive a job collection. /// </summary> /// <param name='cloudServiceName'> /// Required. Name of the cloud service. /// </param> /// <param name='jobCollectionName'> /// Required. Name of the job collection. /// </param> /// <param name='cancellationToken'> /// Cancellation token. /// </param> /// <returns> /// The Get Job Collection operation response. /// </returns> public async Task<JobCollectionGetResponse> GetAsync(string cloudServiceName, string jobCollectionName, CancellationToken cancellationToken) { // Validate if (cloudServiceName == null) { throw new ArgumentNullException("cloudServiceName"); } if (jobCollectionName == null) { throw new ArgumentNullException("jobCollectionName"); } // Tracing bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("jobCollectionName", jobCollectionName); TracingAdapter.Enter(invocationId, this, "GetAsync", tracingParameters); } // Construct URL string url = ""; if (this.Client.Credentials.SubscriptionId != null) { url = url + Uri.EscapeDataString(this.Client.Credentials.SubscriptionId); } url = url + "/cloudservices/"; url = url + Uri.EscapeDataString(cloudServiceName); url = url + "/resources/"; url = url + "scheduler"; url = url + "/~/"; url = url + "JobCollections"; url = url + "/"; url = url + Uri.EscapeDataString(jobCollectionName); string baseUrl = this.Client.BaseUri.AbsoluteUri; // Trim '/' character from the end of baseUrl and beginning of url. if (baseUrl[baseUrl.Length - 1] == '/') { baseUrl = baseUrl.Substring(0, baseUrl.Length - 1); } if (url[0] == '/') { url = url.Substring(1); } url = baseUrl + "/" + url; url = url.Replace(" ", "%20"); // Create HTTP transport objects HttpRequestMessage httpRequest = null; try { httpRequest = new HttpRequestMessage(); httpRequest.Method = HttpMethod.Get; httpRequest.RequestUri = new Uri(url); // Set Headers httpRequest.Headers.Add("x-ms-version", "2013-03-01"); // Set Credentials cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(httpRequest, cancellationToken).ConfigureAwait(false); // Send Request HttpResponseMessage httpResponse = null; try { if (shouldTrace) { TracingAdapter.SendRequest(invocationId, httpRequest); } cancellationToken.ThrowIfCancellationRequested(); httpResponse = await this.Client.HttpClient.SendAsync(httpRequest, cancellationToken).ConfigureAwait(false); if (shouldTrace) { TracingAdapter.ReceiveResponse(invocationId, httpResponse); } HttpStatusCode statusCode = httpResponse.StatusCode; if (statusCode != HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); CloudException ex = CloudException.Create(httpRequest, null, httpResponse, await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false)); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } // Create Result JobCollectionGetResponse result = null; // Deserialize Response if (statusCode == HttpStatusCode.OK) { cancellationToken.ThrowIfCancellationRequested(); string responseContent = await httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); result = new JobCollectionGetResponse(); XDocument responseDoc = XDocument.Parse(responseContent); XElement resourceElement = responseDoc.Element(XName.Get("Resource", "http://schemas.microsoft.com/windowsazure")); if (resourceElement != null) { XElement nameElement = resourceElement.Element(XName.Get("Name", "http://schemas.microsoft.com/windowsazure")); if (nameElement != null) { string nameInstance = nameElement.Value; result.Name = nameInstance; } XElement eTagElement = resourceElement.Element(XName.Get("ETag", "http://schemas.microsoft.com/windowsazure")); if (eTagElement != null) { string eTagInstance = eTagElement.Value; result.ETag = eTagInstance; } XElement stateElement = resourceElement.Element(XName.Get("State", "http://schemas.microsoft.com/windowsazure")); if (stateElement != null) { JobCollectionState stateInstance = ((JobCollectionState)Enum.Parse(typeof(JobCollectionState), stateElement.Value, true)); result.State = stateInstance; } XElement schemaVersionElement = resourceElement.Element(XName.Get("SchemaVersion", "http://schemas.microsoft.com/windowsazure")); if (schemaVersionElement != null) { string schemaVersionInstance = schemaVersionElement.Value; result.SchemaVersion = schemaVersionInstance; } XElement promotionCodeElement = resourceElement.Element(XName.Get("PromotionCode", "http://schemas.microsoft.com/windowsazure")); if (promotionCodeElement != null) { string promotionCodeInstance = promotionCodeElement.Value; result.PromotionCode = promotionCodeInstance; } XElement intrinsicSettingsElement = resourceElement.Element(XName.Get("IntrinsicSettings", "http://schemas.microsoft.com/windowsazure")); if (intrinsicSettingsElement != null) { JobCollectionIntrinsicSettings intrinsicSettingsInstance = new JobCollectionIntrinsicSettings(); result.IntrinsicSettings = intrinsicSettingsInstance; XElement planElement = intrinsicSettingsElement.Element(XName.Get("Plan", "http://schemas.microsoft.com/windowsazure")); if (planElement != null) { JobCollectionPlan planInstance = ((JobCollectionPlan)Enum.Parse(typeof(JobCollectionPlan), planElement.Value, true)); intrinsicSettingsInstance.Plan = planInstance; } XElement quotaElement = intrinsicSettingsElement.Element(XName.Get("Quota", "http://schemas.microsoft.com/windowsazure")); if (quotaElement != null) { JobCollectionQuota quotaInstance = new JobCollectionQuota(); intrinsicSettingsInstance.Quota = quotaInstance; XElement maxJobCountElement = quotaElement.Element(XName.Get("MaxJobCount", "http://schemas.microsoft.com/windowsazure")); if (maxJobCountElement != null && !string.IsNullOrEmpty(maxJobCountElement.Value)) { int maxJobCountInstance = int.Parse(maxJobCountElement.Value, CultureInfo.InvariantCulture); quotaInstance.MaxJobCount = maxJobCountInstance; } XElement maxJobOccurrenceElement = quotaElement.Element(XName.Get("MaxJobOccurrence", "http://schemas.microsoft.com/windowsazure")); if (maxJobOccurrenceElement != null && !string.IsNullOrEmpty(maxJobOccurrenceElement.Value)) { int maxJobOccurrenceInstance = int.Parse(maxJobOccurrenceElement.Value, CultureInfo.InvariantCulture); quotaInstance.MaxJobOccurrence = maxJobOccurrenceInstance; } XElement maxRecurrenceElement = quotaElement.Element(XName.Get("MaxRecurrence", "http://schemas.microsoft.com/windowsazure")); if (maxRecurrenceElement != null) { JobCollectionMaxRecurrence maxRecurrenceInstance = new JobCollectionMaxRecurrence(); quotaInstance.MaxRecurrence = maxRecurrenceInstance; XElement frequencyElement = maxRecurrenceElement.Element(XName.Get("Frequency", "http://schemas.microsoft.com/windowsazure")); if (frequencyElement != null) { JobCollectionRecurrenceFrequency frequencyInstance = ((JobCollectionRecurrenceFrequency)Enum.Parse(typeof(JobCollectionRecurrenceFrequency), frequencyElement.Value, true)); maxRecurrenceInstance.Frequency = frequencyInstance; } XElement intervalElement = maxRecurrenceElement.Element(XName.Get("Interval", "http://schemas.microsoft.com/windowsazure")); if (intervalElement != null) { int intervalInstance = int.Parse(intervalElement.Value, CultureInfo.InvariantCulture); maxRecurrenceInstance.Interval = intervalInstance; } } } } XElement labelElement = resourceElement.Element(XName.Get("Label", "http://schemas.microsoft.com/windowsazure")); if (labelElement != null) { string labelInstance = TypeConversion.FromBase64String(labelElement.Value); result.Label = labelInstance; } XElement operationStatusElement = resourceElement.Element(XName.Get("OperationStatus", "http://schemas.microsoft.com/windowsazure")); if (operationStatusElement != null) { JobCollectionGetResponse.OperationStatus operationStatusInstance = new JobCollectionGetResponse.OperationStatus(); result.LastOperationStatus = operationStatusInstance; XElement errorElement = operationStatusElement.Element(XName.Get("Error", "http://schemas.microsoft.com/windowsazure")); if (errorElement != null) { JobCollectionGetResponse.OperationStatusResponseDetails errorInstance = new JobCollectionGetResponse.OperationStatusResponseDetails(); operationStatusInstance.ResponseDetails = errorInstance; XElement httpCodeElement = errorElement.Element(XName.Get("HttpCode", "http://schemas.microsoft.com/windowsazure")); if (httpCodeElement != null) { HttpStatusCode httpCodeInstance = ((HttpStatusCode)Enum.Parse(typeof(HttpStatusCode), httpCodeElement.Value, true)); errorInstance.StatusCode = httpCodeInstance; } XElement messageElement = errorElement.Element(XName.Get("Message", "http://schemas.microsoft.com/windowsazure")); if (messageElement != null) { string messageInstance = messageElement.Value; errorInstance.Message = messageInstance; } } XElement resultElement = operationStatusElement.Element(XName.Get("Result", "http://schemas.microsoft.com/windowsazure")); if (resultElement != null) { SchedulerOperationStatus resultInstance = ((SchedulerOperationStatus)Enum.Parse(typeof(SchedulerOperationStatus), resultElement.Value, true)); operationStatusInstance.Status = resultInstance; } } } } result.StatusCode = statusCode; if (httpResponse.Headers.Contains("x-ms-request-id")) { result.RequestId = httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } return result; } finally { if (httpResponse != null) { httpResponse.Dispose(); } } } finally { if (httpRequest != null) { httpRequest.Dispose(); } } } /// <summary> /// Update a job collection. /// </summary> /// <param name='cloudServiceName'> /// Required. The name of the cloud service containing the job /// collection. /// </param> /// <param name='jobCollectionName'> /// Required. The name of the job collection to update. /// </param> /// <param name='parameters'> /// Required. Parameters supplied to the Update Job Collection /// operation. /// </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<SchedulerOperationStatusResponse> UpdateAsync(string cloudServiceName, string jobCollectionName, JobCollectionUpdateParameters parameters, CancellationToken cancellationToken) { SchedulerManagementClient client = this.Client; bool shouldTrace = TracingAdapter.IsEnabled; string invocationId = null; if (shouldTrace) { invocationId = TracingAdapter.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("cloudServiceName", cloudServiceName); tracingParameters.Add("jobCollectionName", jobCollectionName); tracingParameters.Add("parameters", parameters); TracingAdapter.Enter(invocationId, this, "UpdateAsync", tracingParameters); } cancellationToken.ThrowIfCancellationRequested(); JobCollectionUpdateResponse response = await client.JobCollections.BeginUpdatingAsync(cloudServiceName, jobCollectionName, parameters, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); SchedulerOperationStatusResponse result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); int delayInSeconds = 15; if (client.LongRunningOperationInitialTimeout >= 0) { delayInSeconds = client.LongRunningOperationInitialTimeout; } while ((result.Status != SchedulerOperationStatus.InProgress) == false) { cancellationToken.ThrowIfCancellationRequested(); await TaskEx.Delay(delayInSeconds * 1000, cancellationToken).ConfigureAwait(false); cancellationToken.ThrowIfCancellationRequested(); result = await client.GetOperationStatusAsync(response.RequestId, cancellationToken).ConfigureAwait(false); delayInSeconds = 10; if (client.LongRunningOperationRetryTimeout >= 0) { delayInSeconds = client.LongRunningOperationRetryTimeout; } } if (shouldTrace) { TracingAdapter.Exit(invocationId, result); } if (result.Status != SchedulerOperationStatus.Succeeded) { if (result.Error != null) { CloudException ex = new CloudException(result.Error.Code + " : " + result.Error.Message); ex.Error = new CloudError(); ex.Error.Code = result.Error.Code; ex.Error.Message = result.Error.Message; if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } else { CloudException ex = new CloudException(""); if (shouldTrace) { TracingAdapter.Error(invocationId, ex); } throw ex; } } result.ETag = response.ETag; return result; } } }
// Copyright 2011 Microsoft Corporation // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. namespace Microsoft.Data.OData.Atom { #region Namespaces using System; using System.Diagnostics; using System.Xml; #endregion Namespaces /// <summary> /// OData ATOM deserializer for error payloads. /// </summary> internal sealed class ODataAtomErrorDeserializer : ODataAtomDeserializer { /// <summary> /// Constructor. /// </summary> /// <param name="atomInputContext">The ATOM input context to read from.</param> internal ODataAtomErrorDeserializer(ODataAtomInputContext atomInputContext) : base(atomInputContext) { DebugUtils.CheckNoExternalCallers(); } /// <summary> /// An enumeration of the various kinds of elements in an m:error element. /// </summary> [Flags] private enum DuplicateErrorElementPropertyBitMask { /// <summary>No duplicates.</summary> None = 0, /// <summary>The 'code' element of the error element.</summary> Code = 1, /// <summary>The 'message' element of the error element.</summary> Message = 2, /// <summary>The 'innererror' element of the error element.</summary> InnerError = 4, } /// <summary> /// An enumeration of the various kinds of elements in an internal error element. /// </summary> [Flags] private enum DuplicateInnerErrorElementPropertyBitMask { /// <summary>No duplicates.</summary> None = 0, /// <summary>The 'message' element of the inner error element.</summary> Message = 1, /// <summary>The 'type' element of the inner error element.</summary> TypeName = 2, /// <summary>The 'stacktrace' element of the inner error element.</summary> StackTrace = 4, /// <summary>The 'internalexception' element of the inner error element.</summary> InternalException = 8, } /// <summary> /// Reads the content of an error element. /// </summary> /// <param name="xmlReader">The Xml reader to read the error payload from.</param> /// <param name="maxInnerErrorDepth">The maximumum number of recursive internalexception elements to allow.</param> /// <returns>The <see cref="ODataError"/> representing the error.</returns> /// <remarks> /// This method is used to read top-level errors as well as in-stream errors (from inside the buffering Xml reader). /// Pre-Condition: XmlNodeType.Element - The m:error start element. /// Post-Condition: XmlNodeType.EndElement - The m:error end-element. /// XmlNodeType.Element - The empty m:error start element. /// </remarks> internal static ODataError ReadErrorElement(BufferingXmlReader xmlReader, int maxInnerErrorDepth) { DebugUtils.CheckNoExternalCallers(); Debug.Assert(xmlReader != null, "this.XmlReader != null"); Debug.Assert(xmlReader.NodeType == XmlNodeType.Element, "xmlReader.NodeType == XmlNodeType.Element"); Debug.Assert(xmlReader.LocalName == AtomConstants.ODataErrorElementName, "Expected reader to be positioned on <m:error> element."); Debug.Assert(xmlReader.NamespaceEquals(xmlReader.ODataMetadataNamespace), "this.XmlReader.NamespaceEquals(atomizedMetadataNamespace)"); ODataError error = new ODataError(); DuplicateErrorElementPropertyBitMask elementsReadBitmask = DuplicateErrorElementPropertyBitMask.None; if (!xmlReader.IsEmptyElement) { // Move to the first child node of the element. xmlReader.Read(); do { switch (xmlReader.NodeType) { case XmlNodeType.EndElement: // end of the <m:error> element continue; case XmlNodeType.Element: if (xmlReader.NamespaceEquals(xmlReader.ODataMetadataNamespace)) { switch (xmlReader.LocalName) { // <m:code> case AtomConstants.ODataErrorCodeElementName: VerifyErrorElementNotFound( ref elementsReadBitmask, DuplicateErrorElementPropertyBitMask.Code, AtomConstants.ODataErrorCodeElementName); error.ErrorCode = xmlReader.ReadElementValue(); continue; // <m:message lang="..."> case AtomConstants.ODataErrorMessageElementName: VerifyErrorElementNotFound( ref elementsReadBitmask, DuplicateErrorElementPropertyBitMask.Message, AtomConstants.ODataErrorMessageElementName); error.MessageLanguage = xmlReader.GetAttribute(xmlReader.XmlLangAttributeName, xmlReader.XmlNamespace); error.Message = xmlReader.ReadElementValue(); continue; // <m:innererror> case AtomConstants.ODataInnerErrorElementName: VerifyErrorElementNotFound( ref elementsReadBitmask, DuplicateErrorElementPropertyBitMask.InnerError, AtomConstants.ODataInnerErrorElementName); error.InnerError = ReadInnerErrorElement(xmlReader, 0 /* recursionDepth */, maxInnerErrorDepth); continue; default: break; } } break; default: break; } xmlReader.Skip(); } while (xmlReader.NodeType != XmlNodeType.EndElement); } return error; } /// <summary> /// Reads a top-level error. /// </summary> /// <returns>An <see cref="ODataError"/> representing the read error.</returns> /// <remarks> /// Pre-Condition: XmlNodeType.None - assumes that the Xml reader has not been used yet. /// Post-Condition: Any - the next node after the m:error end element or the empty m:error element node. /// </remarks> internal ODataError ReadTopLevelError() { DebugUtils.CheckNoExternalCallers(); Debug.Assert(this.ReadingResponse, "Top-level errors are only supported in responses."); Debug.Assert(this.XmlReader != null, "this.XmlReader != null"); Debug.Assert(!this.XmlReader.DisableInStreamErrorDetection, "!this.XmlReader.DetectInStreamErrors"); try { this.XmlReader.DisableInStreamErrorDetection = true; this.ReadPayloadStart(); this.AssertXmlCondition(XmlNodeType.Element); // check for the <m:error> element if (!this.XmlReader.NamespaceEquals(this.XmlReader.ODataMetadataNamespace) || !this.XmlReader.LocalNameEquals(this.XmlReader.ODataErrorElementName)) { throw new ODataErrorException( Strings.ODataAtomErrorDeserializer_InvalidRootElement(this.XmlReader.Name, this.XmlReader.NamespaceURI)); } ODataError error = ReadErrorElement(this.XmlReader, this.MessageReaderSettings.MessageQuotas.MaxNestingDepth); // The ReadErrorElement leaves the reader on the m:error end element or empty start element. // So read over that to consume the entire m:error element. this.XmlReader.Read(); this.ReadPayloadEnd(); return error; } finally { this.XmlReader.DisableInStreamErrorDetection = false; } } /// <summary> /// Verifies that the specified element was not yet found in a top-level error element. /// </summary> /// <param name="elementsFoundBitField"> /// The bit field which stores which elements of an error were found so far. /// </param> /// <param name="elementFoundBitMask">The bit mask for the element to check.</param> /// <param name="elementName">The name of the element to check (used for error reporting).</param> private static void VerifyErrorElementNotFound( ref DuplicateErrorElementPropertyBitMask elementsFoundBitField, DuplicateErrorElementPropertyBitMask elementFoundBitMask, string elementName) { Debug.Assert(((int)elementFoundBitMask & (((int)elementFoundBitMask) - 1)) == 0, "elementFoundBitMask is not a power of 2."); Debug.Assert(!string.IsNullOrEmpty(elementName), "!string.IsNullOrEmpty(elementName)"); if ((elementsFoundBitField & elementFoundBitMask) == elementFoundBitMask) { throw new ODataException(Strings.ODataAtomErrorDeserializer_MultipleErrorElementsWithSameName(elementName)); } elementsFoundBitField |= elementFoundBitMask; } /// <summary> /// Verifies that the specified element was not yet found in an inner error element. /// </summary> /// <param name="elementsFoundBitField"> /// The bit field which stores which elements of an inner error were found so far. /// </param> /// <param name="elementFoundBitMask">The bit mask for the element to check.</param> /// <param name="elementName">The name of the element to check (used for error reporting).</param> private static void VerifyInnerErrorElementNotFound( ref DuplicateInnerErrorElementPropertyBitMask elementsFoundBitField, DuplicateInnerErrorElementPropertyBitMask elementFoundBitMask, string elementName) { Debug.Assert(((int)elementFoundBitMask & (((int)elementFoundBitMask) - 1)) == 0, "elementFoundBitMask is not a power of 2."); Debug.Assert(!string.IsNullOrEmpty(elementName), "!string.IsNullOrEmpty(elementName)"); if ((elementsFoundBitField & elementFoundBitMask) == elementFoundBitMask) { throw new ODataException(Strings.ODataAtomErrorDeserializer_MultipleInnerErrorElementsWithSameName(elementName)); } elementsFoundBitField |= elementFoundBitMask; } /// <summary> /// Reads the content of an inner error element. /// </summary> /// <param name="xmlReader">The (buffering) Xml reader to read the error payload from.</param> /// <param name="recursionDepth">The number of times this function has been called recursively.</param> /// <param name="maxInnerErrorDepth">The maximumum number of recursive internalexception elements to allow.</param> /// <returns>The <see cref="ODataInnerError"/> representing the inner error.</returns> /// <remarks> /// Pre-Condition: XmlNodeType.Element - the m:innererror or m:internalexception element /// Post-Condition: Any - the node after the m:innererror/m:internalexception end element or the node after the empty m:innererror/m:internalexception element node. /// </remarks> private static ODataInnerError ReadInnerErrorElement(BufferingXmlReader xmlReader, int recursionDepth, int maxInnerErrorDepth) { Debug.Assert(xmlReader != null, "this.XmlReader != null"); Debug.Assert(xmlReader.NodeType == XmlNodeType.Element, "xmlReader.NodeType == XmlNodeType.Element"); Debug.Assert( xmlReader.LocalName == AtomConstants.ODataInnerErrorElementName || xmlReader.LocalName == AtomConstants.ODataInnerErrorInnerErrorElementName, "Expected reader to be positioned on 'm:innererror' or 'm:internalexception' element."); Debug.Assert(xmlReader.NamespaceEquals(xmlReader.ODataMetadataNamespace), "this.XmlReader.NamespaceEquals(this.ODataMetadataNamespace)"); ValidationUtils.IncreaseAndValidateRecursionDepth(ref recursionDepth, maxInnerErrorDepth); ODataInnerError innerError = new ODataInnerError(); DuplicateInnerErrorElementPropertyBitMask elementsReadBitmask = DuplicateInnerErrorElementPropertyBitMask.None; if (!xmlReader.IsEmptyElement) { // Move to the first child node of the element. xmlReader.Read(); do { switch (xmlReader.NodeType) { case XmlNodeType.EndElement: // end of the <m:innererror> or <m:internalexception> element continue; case XmlNodeType.Element: if (xmlReader.NamespaceEquals(xmlReader.ODataMetadataNamespace)) { switch (xmlReader.LocalName) { // <m:message> case AtomConstants.ODataInnerErrorMessageElementName: VerifyInnerErrorElementNotFound( ref elementsReadBitmask, DuplicateInnerErrorElementPropertyBitMask.Message, AtomConstants.ODataInnerErrorMessageElementName); innerError.Message = xmlReader.ReadElementValue(); continue; // <m:type> case AtomConstants.ODataInnerErrorTypeElementName: VerifyInnerErrorElementNotFound( ref elementsReadBitmask, DuplicateInnerErrorElementPropertyBitMask.TypeName, AtomConstants.ODataInnerErrorTypeElementName); innerError.TypeName = xmlReader.ReadElementValue(); continue; // <m:stacktrace> case AtomConstants.ODataInnerErrorStackTraceElementName: VerifyInnerErrorElementNotFound( ref elementsReadBitmask, DuplicateInnerErrorElementPropertyBitMask.StackTrace, AtomConstants.ODataInnerErrorStackTraceElementName); innerError.StackTrace = xmlReader.ReadElementValue(); continue; // <m:internalexception> case AtomConstants.ODataInnerErrorInnerErrorElementName: VerifyInnerErrorElementNotFound( ref elementsReadBitmask, DuplicateInnerErrorElementPropertyBitMask.InternalException, AtomConstants.ODataInnerErrorInnerErrorElementName); innerError.InnerError = ReadInnerErrorElement(xmlReader, recursionDepth, maxInnerErrorDepth); continue; default: break; } } break; default: break; } xmlReader.Skip(); } while (xmlReader.NodeType != XmlNodeType.EndElement); } // Read over the end element, or empty start element. xmlReader.Read(); return innerError; } } }
namespace java.io { [global::MonoJavaBridge.JavaClass()] public partial class ObjectOutputStream : java.io.OutputStream, ObjectOutput, ObjectStreamConstants { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected ObjectOutputStream(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } [global::MonoJavaBridge.JavaClass(typeof(global::java.io.ObjectOutputStream.PutField_))] public abstract partial class PutField : java.lang.Object { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; protected PutField(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public abstract void put(java.lang.String arg0, bool arg1); private static global::MonoJavaBridge.MethodId _m1; public abstract void put(java.lang.String arg0, byte arg1); private static global::MonoJavaBridge.MethodId _m2; public abstract void put(java.lang.String arg0, char arg1); private static global::MonoJavaBridge.MethodId _m3; public abstract void put(java.lang.String arg0, short arg1); private static global::MonoJavaBridge.MethodId _m4; public abstract void put(java.lang.String arg0, long arg1); private static global::MonoJavaBridge.MethodId _m5; public abstract void put(java.lang.String arg0, float arg1); private static global::MonoJavaBridge.MethodId _m6; public abstract void put(java.lang.String arg0, double arg1); private static global::MonoJavaBridge.MethodId _m7; public abstract void put(java.lang.String arg0, java.lang.Object arg1); private static global::MonoJavaBridge.MethodId _m8; public abstract void put(java.lang.String arg0, int arg1); private static global::MonoJavaBridge.MethodId _m9; public abstract void write(java.io.ObjectOutput arg0); private static global::MonoJavaBridge.MethodId _m10; public PutField() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.io.ObjectOutputStream.PutField._m10.native == global::System.IntPtr.Zero) global::java.io.ObjectOutputStream.PutField._m10 = @__env.GetMethodIDNoThrow(global::java.io.ObjectOutputStream.PutField.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.io.ObjectOutputStream.PutField.staticClass, global::java.io.ObjectOutputStream.PutField._m10); Init(@__env, handle); } static PutField() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.io.ObjectOutputStream.PutField.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/io/ObjectOutputStream$PutField")); } } [global::MonoJavaBridge.JavaProxy(typeof(global::java.io.ObjectOutputStream.PutField))] internal sealed partial class PutField_ : java.io.ObjectOutputStream.PutField { internal new static global::MonoJavaBridge.JniGlobalHandle staticClass; internal PutField_(global::MonoJavaBridge.JNIEnv @__env) : base(@__env) { } private static global::MonoJavaBridge.MethodId _m0; public override void put(java.lang.String arg0, bool arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.PutField_.staticClass, "put", "(Ljava/lang/String;Z)V", ref global::java.io.ObjectOutputStream.PutField_._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m1; public override void put(java.lang.String arg0, byte arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.PutField_.staticClass, "put", "(Ljava/lang/String;B)V", ref global::java.io.ObjectOutputStream.PutField_._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m2; public override void put(java.lang.String arg0, char arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.PutField_.staticClass, "put", "(Ljava/lang/String;C)V", ref global::java.io.ObjectOutputStream.PutField_._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m3; public override void put(java.lang.String arg0, short arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.PutField_.staticClass, "put", "(Ljava/lang/String;S)V", ref global::java.io.ObjectOutputStream.PutField_._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m4; public override void put(java.lang.String arg0, long arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.PutField_.staticClass, "put", "(Ljava/lang/String;J)V", ref global::java.io.ObjectOutputStream.PutField_._m4, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m5; public override void put(java.lang.String arg0, float arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.PutField_.staticClass, "put", "(Ljava/lang/String;F)V", ref global::java.io.ObjectOutputStream.PutField_._m5, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m6; public override void put(java.lang.String arg0, double arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.PutField_.staticClass, "put", "(Ljava/lang/String;D)V", ref global::java.io.ObjectOutputStream.PutField_._m6, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m7; public override void put(java.lang.String arg0, java.lang.Object arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.PutField_.staticClass, "put", "(Ljava/lang/String;Ljava/lang/Object;)V", ref global::java.io.ObjectOutputStream.PutField_._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m8; public override void put(java.lang.String arg0, int arg1) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.PutField_.staticClass, "put", "(Ljava/lang/String;I)V", ref global::java.io.ObjectOutputStream.PutField_._m8, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1)); } private static global::MonoJavaBridge.MethodId _m9; public override void write(java.io.ObjectOutput arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.PutField_.staticClass, "write", "(Ljava/io/ObjectOutput;)V", ref global::java.io.ObjectOutputStream.PutField_._m9, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } static PutField_() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.io.ObjectOutputStream.PutField_.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/io/ObjectOutputStream$PutField")); } } private static global::MonoJavaBridge.MethodId _m0; public override void write(byte[] arg0, int arg1, int arg2) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "write", "([BII)V", ref global::java.io.ObjectOutputStream._m0, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg1), global::MonoJavaBridge.JavaBridge.ConvertToValue(arg2)); } private static global::MonoJavaBridge.MethodId _m1; public override void write(byte[] arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "write", "([B)V", ref global::java.io.ObjectOutputStream._m1, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m2; public override void write(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "write", "(I)V", ref global::java.io.ObjectOutputStream._m2, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m3; public virtual void writeObject(java.lang.Object arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeObject", "(Ljava/lang/Object;)V", ref global::java.io.ObjectOutputStream._m3, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m4; public virtual void defaultWriteObject() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "defaultWriteObject", "()V", ref global::java.io.ObjectOutputStream._m4); } private static global::MonoJavaBridge.MethodId _m5; public override void flush() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "flush", "()V", ref global::java.io.ObjectOutputStream._m5); } private static global::MonoJavaBridge.MethodId _m6; public override void close() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "close", "()V", ref global::java.io.ObjectOutputStream._m6); } private static global::MonoJavaBridge.MethodId _m7; public virtual void writeInt(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeInt", "(I)V", ref global::java.io.ObjectOutputStream._m7, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m8; public virtual global::java.io.ObjectOutputStream.PutField putFields() { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.ObjectOutputStream.staticClass, "putFields", "()Ljava/io/ObjectOutputStream$PutField;", ref global::java.io.ObjectOutputStream._m8) as java.io.ObjectOutputStream.PutField; } private static global::MonoJavaBridge.MethodId _m9; public virtual void writeFields() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeFields", "()V", ref global::java.io.ObjectOutputStream._m9); } private static global::MonoJavaBridge.MethodId _m10; public virtual void reset() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "reset", "()V", ref global::java.io.ObjectOutputStream._m10); } private static global::MonoJavaBridge.MethodId _m11; public virtual void writeChar(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeChar", "(I)V", ref global::java.io.ObjectOutputStream._m11, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m12; public virtual void writeBytes(java.lang.String arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeBytes", "(Ljava/lang/String;)V", ref global::java.io.ObjectOutputStream._m12, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m13; public virtual void writeUTF(java.lang.String arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeUTF", "(Ljava/lang/String;)V", ref global::java.io.ObjectOutputStream._m13, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m14; public virtual void writeLong(long arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeLong", "(J)V", ref global::java.io.ObjectOutputStream._m14, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m15; public virtual void writeByte(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeByte", "(I)V", ref global::java.io.ObjectOutputStream._m15, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m16; public virtual void writeShort(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeShort", "(I)V", ref global::java.io.ObjectOutputStream._m16, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m17; public virtual void writeFloat(float arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeFloat", "(F)V", ref global::java.io.ObjectOutputStream._m17, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m18; public virtual void writeDouble(double arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeDouble", "(D)V", ref global::java.io.ObjectOutputStream._m18, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m19; public virtual void useProtocolVersion(int arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "useProtocolVersion", "(I)V", ref global::java.io.ObjectOutputStream._m19, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m20; protected virtual void writeObjectOverride(java.lang.Object arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeObjectOverride", "(Ljava/lang/Object;)V", ref global::java.io.ObjectOutputStream._m20, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m21; public virtual void writeUnshared(java.lang.Object arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeUnshared", "(Ljava/lang/Object;)V", ref global::java.io.ObjectOutputStream._m21, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m22; protected virtual void annotateClass(java.lang.Class arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "annotateClass", "(Ljava/lang/Class;)V", ref global::java.io.ObjectOutputStream._m22, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m23; protected virtual void annotateProxyClass(java.lang.Class arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "annotateProxyClass", "(Ljava/lang/Class;)V", ref global::java.io.ObjectOutputStream._m23, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m24; protected virtual global::java.lang.Object replaceObject(java.lang.Object arg0) { return global::MonoJavaBridge.JavaBridge.CallObjectMethod(this, global::java.io.ObjectOutputStream.staticClass, "replaceObject", "(Ljava/lang/Object;)Ljava/lang/Object;", ref global::java.io.ObjectOutputStream._m24, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)) as java.lang.Object; } private static global::MonoJavaBridge.MethodId _m25; protected virtual bool enableReplaceObject(bool arg0) { return global::MonoJavaBridge.JavaBridge.CallBooleanMethod(this, global::java.io.ObjectOutputStream.staticClass, "enableReplaceObject", "(Z)Z", ref global::java.io.ObjectOutputStream._m25, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m26; protected virtual void writeStreamHeader() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeStreamHeader", "()V", ref global::java.io.ObjectOutputStream._m26); } private static global::MonoJavaBridge.MethodId _m27; protected virtual void writeClassDescriptor(java.io.ObjectStreamClass arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeClassDescriptor", "(Ljava/io/ObjectStreamClass;)V", ref global::java.io.ObjectOutputStream._m27, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m28; protected virtual void drain() { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "drain", "()V", ref global::java.io.ObjectOutputStream._m28); } private static global::MonoJavaBridge.MethodId _m29; public virtual void writeBoolean(bool arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeBoolean", "(Z)V", ref global::java.io.ObjectOutputStream._m29, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m30; public virtual void writeChars(java.lang.String arg0) { global::MonoJavaBridge.JavaBridge.CallVoidMethod(this, global::java.io.ObjectOutputStream.staticClass, "writeChars", "(Ljava/lang/String;)V", ref global::java.io.ObjectOutputStream._m30, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); } private static global::MonoJavaBridge.MethodId _m31; public ObjectOutputStream(java.io.OutputStream arg0) : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.io.ObjectOutputStream._m31.native == global::System.IntPtr.Zero) global::java.io.ObjectOutputStream._m31 = @__env.GetMethodIDNoThrow(global::java.io.ObjectOutputStream.staticClass, "<init>", "(Ljava/io/OutputStream;)V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.io.ObjectOutputStream.staticClass, global::java.io.ObjectOutputStream._m31, global::MonoJavaBridge.JavaBridge.ConvertToValue(arg0)); Init(@__env, handle); } private static global::MonoJavaBridge.MethodId _m32; protected ObjectOutputStream() : base(global::MonoJavaBridge.JNIEnv.ThreadEnv) { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; if (global::java.io.ObjectOutputStream._m32.native == global::System.IntPtr.Zero) global::java.io.ObjectOutputStream._m32 = @__env.GetMethodIDNoThrow(global::java.io.ObjectOutputStream.staticClass, "<init>", "()V"); global::MonoJavaBridge.JniLocalHandle handle = @__env.NewObject(java.io.ObjectOutputStream.staticClass, global::java.io.ObjectOutputStream._m32); Init(@__env, handle); } static ObjectOutputStream() { global::MonoJavaBridge.JNIEnv @__env = global::MonoJavaBridge.JNIEnv.ThreadEnv; global::java.io.ObjectOutputStream.staticClass = @__env.NewGlobalRef(@__env.FindClass("java/io/ObjectOutputStream")); } } }
// // Copyright (c) 2004-2017 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Threading; using NLog.Common; using NLog.Internal.NetworkSenders; using NLog.Layouts; /// <summary> /// Sends log messages over the network. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/Network-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Network/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Network/Simple/Example.cs" /> /// <p> /// To print the results, use any application that's able to receive messages over /// TCP or UDP. <a href="http://m.nu/program/util/netcat/netcat.html">NetCat</a> is /// a simple but very powerful command-line tool that can be used for that. This image /// demonstrates the NetCat tool receiving log messages from Network target. /// </p> /// <img src="examples/targets/Screenshots/Network/Output.gif" /> /// <p> /// NOTE: If your receiver application is ever likely to be off-line, don't use TCP protocol /// or you'll get TCP timeouts and your application will be very slow. /// Either switch to UDP transport or use <a href="target.AsyncWrapper.html">AsyncWrapper</a> target /// so that your application threads will not be blocked by the timing-out connection attempts. /// </p> /// <p> /// There are two specialized versions of the Network target: <a href="target.Chainsaw.html">Chainsaw</a> /// and <a href="target.NLogViewer.html">NLogViewer</a> which write to instances of Chainsaw log4j viewer /// or NLogViewer application respectively. /// </p> /// </example> [Target("Network")] public class NetworkTarget : TargetWithLayout { private readonly Dictionary<string, LinkedListNode<NetworkSender>> _currentSenderCache = new Dictionary<string, LinkedListNode<NetworkSender>>(); private readonly LinkedList<NetworkSender> _openNetworkSenders = new LinkedList<NetworkSender>(); /// <summary> /// Initializes a new instance of the <see cref="NetworkTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> public NetworkTarget() { SenderFactory = NetworkSenderFactory.Default; Encoding = Encoding.UTF8; OnOverflow = NetworkTargetOverflowAction.Split; KeepConnection = true; MaxMessageSize = 65000; ConnectionCacheSize = 5; LineEnding = LineEndingMode.CRLF; } /// <summary> /// Initializes a new instance of the <see cref="NetworkTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> /// <param name="name">Name of the target.</param> public NetworkTarget(string name) : this() { Name = name; } /// <summary> /// Gets or sets the network address. /// </summary> /// <remarks> /// The network address can be: /// <ul> /// <li>tcp://host:port - TCP (auto select IPv4/IPv6) (not supported on Windows Phone 7.0)</li> /// <li>tcp4://host:port - force TCP/IPv4 (not supported on Windows Phone 7.0)</li> /// <li>tcp6://host:port - force TCP/IPv6 (not supported on Windows Phone 7.0)</li> /// <li>udp://host:port - UDP (auto select IPv4/IPv6, not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>udp4://host:port - force UDP/IPv4 (not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>udp6://host:port - force UDP/IPv6 (not supported on Silverlight and on Windows Phone 7.0)</li> /// <li>http://host:port/pageName - HTTP using POST verb</li> /// <li>https://host:port/pageName - HTTPS using POST verb</li> /// </ul> /// For SOAP-based webservice support over HTTP use WebService target. /// </remarks> /// <docgen category='Connection Options' order='10' /> public Layout Address { get; set; } /// <summary> /// Gets or sets a value indicating whether to keep connection open whenever possible. /// </summary> /// <docgen category='Connection Options' order='10' /> [DefaultValue(true)] public bool KeepConnection { get; set; } /// <summary> /// Gets or sets a value indicating whether to append newline at the end of log message. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue(false)] public bool NewLine { get; set; } /// <summary> /// Gets or sets the end of line value if a newline is appended at the end of log message <see cref="NewLine"/>. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue("CRLF")] public LineEndingMode LineEnding { get; set; } /// <summary> /// Gets or sets the maximum message size in bytes. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue(65000)] public int MaxMessageSize { get; set; } /// <summary> /// Gets or sets the size of the connection cache (number of connections which are kept alive). /// </summary> /// <docgen category="Connection Options" order="10"/> [DefaultValue(5)] public int ConnectionCacheSize { get; set; } /// <summary> /// Gets or sets the maximum current connections. 0 = no maximum. /// </summary> /// <docgen category="Connection Options" order="10"/> public int MaxConnections { get; set; } /// <summary> /// Gets or sets the action that should be taken if the will be more connections than <see cref="MaxConnections"/>. /// </summary> /// <docgen category='Layout Options' order='10' /> public NetworkTargetConnectionsOverflowAction OnConnectionOverflow { get; set; } /// <summary> /// Gets or sets the maximum queue size. /// </summary> [DefaultValue(0)] public int MaxQueueSize { get; set; } /// <summary> /// Gets or sets the action that should be taken if the message is larger than /// maxMessageSize. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue(NetworkTargetOverflowAction.Split)] public NetworkTargetOverflowAction OnOverflow { get; set; } /// <summary> /// Gets or sets the encoding to be used. /// </summary> /// <docgen category='Layout Options' order='10' /> [DefaultValue("utf-8")] public Encoding Encoding { get; set; } internal INetworkSenderFactory SenderFactory { get; set; } /// <summary> /// Flush any pending log messages asynchronously (in case of asynchronous targets). /// </summary> /// <param name="asyncContinuation">The asynchronous continuation.</param> protected override void FlushAsync(AsyncContinuation asyncContinuation) { int remainingCount = 0; AsyncContinuation continuation = ex => { // ignore exception if (Interlocked.Decrement(ref remainingCount) == 0) { asyncContinuation(null); } }; lock (_openNetworkSenders) { remainingCount = _openNetworkSenders.Count; if (remainingCount == 0) { // nothing to flush asyncContinuation(null); } else { // otherwise call FlushAsync() on all senders // and invoke continuation at the very end foreach (var openSender in _openNetworkSenders) { openSender.FlushAsync(continuation); } } } } /// <summary> /// Closes the target. /// </summary> protected override void CloseTarget() { base.CloseTarget(); lock (_openNetworkSenders) { foreach (var openSender in _openNetworkSenders) { openSender.Close(ex => { }); } _openNetworkSenders.Clear(); } } /// <summary> /// Sends the /// rendered logging event over the network optionally concatenating it with a newline character. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(AsyncLogEventInfo logEvent) { string address = Address.Render(logEvent.LogEvent); InternalLogger.Trace("Sending to address: '{0}'", address); byte[] bytes = GetBytesToWrite(logEvent.LogEvent); if (KeepConnection) { var senderNode = GetCachedNetworkSender(address); ChunkedSend( senderNode.Value, bytes, ex => { if (ex != null) { InternalLogger.Error(ex, "Error when sending."); ReleaseCachedConnection(senderNode); } logEvent.Continuation(ex); }); } else { NetworkSender sender; LinkedListNode<NetworkSender> linkedListNode; lock (_openNetworkSenders) { //handle too many connections var tooManyConnections = _openNetworkSenders.Count >= MaxConnections; if (tooManyConnections && MaxConnections > 0) { switch (OnConnectionOverflow) { case NetworkTargetConnectionsOverflowAction.DiscardMessage: InternalLogger.Warn("Discarding message otherwise to many connections."); logEvent.Continuation(null); return; case NetworkTargetConnectionsOverflowAction.AllowNewConnnection: InternalLogger.Debug("Too may connections, but this is allowed"); break; case NetworkTargetConnectionsOverflowAction.Block: while (_openNetworkSenders.Count >= MaxConnections) { InternalLogger.Debug("Blocking networktarget otherwhise too many connections."); Monitor.Wait(_openNetworkSenders); InternalLogger.Trace("Entered critical section."); } InternalLogger.Trace("Limit ok."); break; } } sender = SenderFactory.Create(address, MaxQueueSize); sender.Initialize(); linkedListNode = _openNetworkSenders.AddLast(sender); } ChunkedSend( sender, bytes, ex => { lock (_openNetworkSenders) { TryRemove(_openNetworkSenders, linkedListNode); if (OnConnectionOverflow == NetworkTargetConnectionsOverflowAction.Block) { Monitor.PulseAll(_openNetworkSenders); } } if (ex != null) { InternalLogger.Error(ex, "Error when sending."); } sender.Close(ex2 => { }); logEvent.Continuation(ex); }); } } /// <summary> /// Try to remove. /// </summary> /// <typeparam name="T"></typeparam> /// <param name="list"></param> /// <param name="node"></param> /// <returns>removed something?</returns> private static bool TryRemove<T>(LinkedList<T> list, LinkedListNode<T> node) { if (node == null || list != node.List) { return false; } list.Remove(node); return true; } /// <summary> /// Gets the bytes to be written. /// </summary> /// <param name="logEvent">Log event.</param> /// <returns>Byte array.</returns> protected virtual byte[] GetBytesToWrite(LogEventInfo logEvent) { string text; var rendered = Layout.Render(logEvent); InternalLogger.Trace("Sending: {0}", rendered); if (NewLine) { text = rendered + LineEnding.NewLineCharacters; } else { text = rendered; } return Encoding.GetBytes(text); } private LinkedListNode<NetworkSender> GetCachedNetworkSender(string address) { lock (_currentSenderCache) { LinkedListNode<NetworkSender> senderNode; // already have address if (_currentSenderCache.TryGetValue(address, out senderNode)) { senderNode.Value.CheckSocket(); return senderNode; } if (_currentSenderCache.Count >= ConnectionCacheSize) { // make room in the cache by closing the least recently used connection int minAccessTime = int.MaxValue; LinkedListNode<NetworkSender> leastRecentlyUsed = null; foreach (var pair in _currentSenderCache) { var networkSender = pair.Value.Value; if (networkSender.LastSendTime < minAccessTime) { minAccessTime = networkSender.LastSendTime; leastRecentlyUsed = pair.Value; } } if (leastRecentlyUsed != null) { ReleaseCachedConnection(leastRecentlyUsed); } } var sender = SenderFactory.Create(address, MaxQueueSize); sender.Initialize(); lock (_openNetworkSenders) { senderNode = _openNetworkSenders.AddLast(sender); } _currentSenderCache.Add(address, senderNode); return senderNode; } } private void ReleaseCachedConnection(LinkedListNode<NetworkSender> senderNode) { lock (_currentSenderCache) { var networkSender = senderNode.Value; lock (_openNetworkSenders) { if (TryRemove(_openNetworkSenders, senderNode)) { // only remove it once networkSender.Close(ex => { }); } } LinkedListNode<NetworkSender> sender2; // make sure the current sender for this address is the one we want to remove if (_currentSenderCache.TryGetValue(networkSender.Address, out sender2)) { if (ReferenceEquals(senderNode, sender2)) { _currentSenderCache.Remove(networkSender.Address); } } } } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA2204:Literals should be spelled correctly", Justification = "Using property names in message.")] private void ChunkedSend(NetworkSender sender, byte[] buffer, AsyncContinuation continuation) { int tosend = buffer.Length; int pos = 0; AsyncContinuation sendNextChunk = null; sendNextChunk = ex => { if (ex != null) { continuation(ex); return; } InternalLogger.Trace("Sending chunk, position: {0}, length: {1}", pos, tosend); if (tosend <= 0) { continuation(null); return; } int chunksize = tosend; if (chunksize > MaxMessageSize) { if (OnOverflow == NetworkTargetOverflowAction.Discard) { InternalLogger.Trace("discard because chunksize > this.MaxMessageSize"); continuation(null); return; } if (OnOverflow == NetworkTargetOverflowAction.Error) { continuation(new OverflowException($"Attempted to send a message larger than MaxMessageSize ({MaxMessageSize}). Actual size was: {buffer.Length}. Adjust OnOverflow and MaxMessageSize parameters accordingly.")); return; } chunksize = MaxMessageSize; } int pos0 = pos; tosend -= chunksize; pos += chunksize; sender.Send(buffer, pos0, chunksize, sendNextChunk); }; sendNextChunk(null); } } }
using System; using System.Collections.Generic; using System.ComponentModel.Composition; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using EnvDTE; using EnvDTE80; using Microsoft.VisualStudio; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.Shell.Interop; namespace NuGet.VisualStudio { [PartCreationPolicy(CreationPolicy.Shared)] [Export(typeof(ISolutionManager))] public class SolutionManager : ISolutionManager, IVsSelectionEvents { private readonly DTE _dte; private readonly SolutionEvents _solutionEvents; private readonly IVsMonitorSelection _vsMonitorSelection; private readonly uint _solutionLoadedUICookie; private readonly IVsSolution _vsSolution; private ProjectCache _projectCache; public SolutionManager() : this( ServiceLocator.GetInstance<DTE>(), ServiceLocator.GetGlobalService<SVsSolution, IVsSolution>(), ServiceLocator.GetGlobalService<SVsShellMonitorSelection, IVsMonitorSelection>()) { } internal SolutionManager(DTE dte, IVsSolution vsSolution, IVsMonitorSelection vsMonitorSelection) { if (dte == null) { throw new ArgumentNullException("dte"); } _dte = dte; _vsSolution = vsSolution; _vsMonitorSelection = vsMonitorSelection; // Keep a reference to SolutionEvents so that it doesn't get GC'ed. Otherwise, we won't receive events. _solutionEvents = _dte.Events.SolutionEvents; // can be null in unit tests if (vsMonitorSelection != null) { Guid solutionLoadedGuid = VSConstants.UICONTEXT.SolutionExistsAndFullyLoaded_guid; _vsMonitorSelection.GetCmdUIContextCookie(ref solutionLoadedGuid, out _solutionLoadedUICookie); uint cookie; int hr = _vsMonitorSelection.AdviseSelectionEvents(this, out cookie); ErrorHandler.ThrowOnFailure(hr); } _solutionEvents.BeforeClosing += OnBeforeClosing; _solutionEvents.AfterClosing += OnAfterClosing; _solutionEvents.ProjectAdded += OnProjectAdded; _solutionEvents.ProjectRemoved += OnProjectRemoved; _solutionEvents.ProjectRenamed += OnProjectRenamed; if (_dte.Solution.IsOpen) { OnSolutionOpened(); } } public string DefaultProjectName { get; set; } public Project DefaultProject { get { if (String.IsNullOrEmpty(DefaultProjectName)) { return null; } Project project = GetProject(DefaultProjectName); Debug.Assert(project != null, "Invalid default project"); return project; } } [Import] internal Lazy<IDeleteOnRestartManager> DeleteOnRestartManager { get; set; } public event EventHandler SolutionOpened; public event EventHandler SolutionClosing; public event EventHandler SolutionClosed; public event EventHandler<ProjectEventArgs> ProjectAdded; /// <summary> /// Gets a value indicating whether there is a solution open in the IDE. /// </summary> public bool IsSolutionOpen { get { return _dte != null && _dte.Solution != null && _dte.Solution.IsOpen && !IsSolutionSavedAsRequired(); } } /// <summary> /// Checks whether the current solution is saved to disk, as opposed to be in memory. /// </summary> private bool IsSolutionSavedAsRequired() { // Check if user is doing File - New File without saving the solution. object value; _vsSolution.GetProperty((int)(__VSPROPID.VSPROPID_IsSolutionSaveAsRequired), out value); if ((bool)value) { return true; } // Check if user unchecks the "Tools - Options - Project & Soltuions - Save new projects when created" option _vsSolution.GetProperty((int)(__VSPROPID2.VSPROPID_DeferredSaveSolution), out value); return (bool)value; } public string SolutionDirectory { get { if (!IsSolutionOpen) { return null; } string solutionFilePath = GetSolutionFilePath(); if (String.IsNullOrEmpty(solutionFilePath)) { return null; } return Path.GetDirectoryName(solutionFilePath); } } public IFileSystem SolutionFileSystem { get { string path = SolutionDirectory; if (string.IsNullOrEmpty(path)) { return null; } return new PhysicalFileSystem(path); } } private string GetSolutionFilePath() { // Use .Properties.Item("Path") instead of .FullName because .FullName might not be // available if the solution is just being created string solutionFilePath = null; Property property = _dte.Solution.Properties.Item("Path"); if (property == null) { return null; } try { // When using a temporary solution, (such as by saying File -> New File), querying this value throws. // Since we wouldn't be able to do manage any packages at this point, we return null. Consumers of this property typically // use a String.IsNullOrEmpty check either way, so it's alright. solutionFilePath = property.Value; } catch (COMException) { return null; } return solutionFilePath; } public bool IsSourceControlBound { get { return GetIsSourceControlBound(); } } private bool GetIsSourceControlBound() { if (!IsSolutionOpen) { return false; } string solutionFilePath = GetSolutionFilePath(); Debug.Assert(!String.IsNullOrEmpty(solutionFilePath)); SourceControl2 sourceControl = (SourceControl2)_dte.SourceControl; if (sourceControl != null) { try { return sourceControl.GetBindings(solutionFilePath) != null; } catch (NotImplementedException) { } } return false; } /// <summary> /// Gets a list of supported projects currently loaded in the solution /// </summary> /// <returns></returns> [System.Diagnostics.CodeAnalysis.SuppressMessage( "Microsoft.Design", "CA1024:UsePropertiesWhereAppropriate", Justification = "This method is potentially expensive if the cache is not constructed yet.")] public IEnumerable<Project> GetProjects() { if (IsSolutionOpen) { EnsureProjectCache(); return _projectCache.GetProjects(); } else { return Enumerable.Empty<Project>(); } } public string GetProjectSafeName(Project project) { if (project == null) { throw new ArgumentNullException("project"); } // Try searching for simple names first string name = project.Name; if (GetProject(name) == project) { return name; } return project.GetCustomUniqueName(); } public Project GetProject(string projectSafeName) { if (IsSolutionOpen) { EnsureProjectCache(); Project project; if (_projectCache.TryGetProject(projectSafeName, out project)) { return project; } } return null; } private void OnAfterClosing() { if (SolutionClosed != null) { SolutionClosed(this, EventArgs.Empty); } } private void OnBeforeClosing() { DefaultProjectName = null; _projectCache = null; if (SolutionClosing != null) { SolutionClosing(this, EventArgs.Empty); } } private void OnProjectRenamed(Project project, string oldName) { if (!String.IsNullOrEmpty(oldName)) { EnsureProjectCache(); if (project.IsSupported()) { RemoveProjectFromCache(oldName); AddProjectToCache(project); } else if (project.IsSolutionFolder()) { // In the case where a solution directory was changed, project FullNames are unchanged. // We only need to invalidate the projects under the current tree so as to sync the CustomUniqueNames. foreach (var item in project.GetSupportedChildProjects()) { RemoveProjectFromCache(item.FullName); AddProjectToCache(item); } } } } private void OnProjectRemoved(Project project) { RemoveProjectFromCache(project.FullName); } private void OnProjectAdded(Project project) { if (project.IsSupported() && !project.IsParentProjectExplicitlyUnsupported()) { EnsureProjectCache(); AddProjectToCache(project); if (ProjectAdded != null) { ProjectAdded(this, new ProjectEventArgs(project)); } } } private void OnSolutionOpened() { // although the SolutionOpened event fires, the solution may be only in memory (e.g. when // doing File - New File). In that case, we don't want to act on the event. if (!IsSolutionOpen) { return; } EnsureProjectCache(); SetDefaultProject(); if (SolutionOpened != null) { SolutionOpened(this, EventArgs.Empty); } } private void EnsureProjectCache() { if (IsSolutionOpen && _projectCache == null) { _projectCache = new ProjectCache(); var allProjects = _dte.Solution.GetAllProjects(); foreach (Project project in allProjects) { AddProjectToCache(project); } } } private void AddProjectToCache(Project project) { if (!project.IsSupported()) { return; } ProjectName oldProjectName; _projectCache.TryGetProjectNameByShortName(project.Name, out oldProjectName); ProjectName newProjectName = _projectCache.AddProject(project); if (String.IsNullOrEmpty(DefaultProjectName) || newProjectName.ShortName.Equals(DefaultProjectName, StringComparison.OrdinalIgnoreCase)) { DefaultProjectName = oldProjectName != null ? oldProjectName.CustomUniqueName : newProjectName.ShortName; } } private void RemoveProjectFromCache(string name) { // Do nothing if the cache hasn't been set up if (_projectCache == null) { return; } ProjectName projectName; _projectCache.TryGetProjectName(name, out projectName); // Remove the project from the cache _projectCache.RemoveProject(name); if (!_projectCache.Contains(DefaultProjectName)) { DefaultProjectName = null; } // for LightSwitch project, the main project is not added to _projectCache, but it is called on removal. // in that case, projectName is null. if (projectName != null && projectName.CustomUniqueName.Equals(DefaultProjectName, StringComparison.OrdinalIgnoreCase) && !_projectCache.IsAmbiguous(projectName.ShortName)) { DefaultProjectName = projectName.ShortName; } } private void SetDefaultProject() { // when a new solution opens, we set its startup project as the default project in NuGet Console var solutionBuild = (SolutionBuild2)_dte.Solution.SolutionBuild; if (solutionBuild.StartupProjects != null) { IEnumerable<object> startupProjects = solutionBuild.StartupProjects; string startupProjectName = startupProjects.Cast<string>().FirstOrDefault(); if (!String.IsNullOrEmpty(startupProjectName)) { ProjectName projectName; if (_projectCache.TryGetProjectName(startupProjectName, out projectName)) { DefaultProjectName = _projectCache.IsAmbiguous(projectName.ShortName) ? projectName.CustomUniqueName : projectName.ShortName; } } } } // REVIEW: This might be inefficient, see what we can do with caching projects until references change public IEnumerable<Project> GetDependentProjects(Project project) { if (project == null) { throw new ArgumentNullException("project"); } var dependentProjects = new Dictionary<string, List<Project>>(); // Get all of the projects in the solution and build the reverse graph. i.e. // if A has a project reference to B (A -> B) the this will return B -> A // We need to run this on the ui thread so that it doesn't freeze for websites. Since there might be a // large number of references. ThreadHelper.Generic.Invoke(() => { foreach (var proj in GetProjects()) { if (project.SupportsReferences()) { foreach (var referencedProject in proj.GetReferencedProjects()) { AddDependentProject(dependentProjects, referencedProject, proj); } } } }); List<Project> dependents; if (dependentProjects.TryGetValue(project.GetUniqueName(), out dependents)) { return dependents; } return Enumerable.Empty<Project>(); } private static void AddDependentProject(IDictionary<string, List<Project>> dependentProjects, Project project, Project dependent) { List<Project> dependents; if (!dependentProjects.TryGetValue(project.GetUniqueName(), out dependents)) { dependents = new List<Project>(); dependentProjects[project.UniqueName] = dependents; } dependents.Add(dependent); } #region IVsSelectionEvents implementation public int OnCmdUIContextChanged(uint dwCmdUICookie, int fActive) { if (dwCmdUICookie == _solutionLoadedUICookie && fActive == 1) { OnSolutionOpened(); // We must call DeleteMarkedPackageDirectories outside of OnSolutionOpened, because OnSolutionOpened might be called in the constructor // and DeleteOnRestartManager requires VsFileSystemProvider and RepositorySetings which both have dependencies on SolutionManager. // In practice, this code gets executed even when a solution is opened directly during Visual Studio startup. DeleteOnRestartManager.Value.DeleteMarkedPackageDirectories(); } return VSConstants.S_OK; } public int OnElementValueChanged(uint elementid, object varValueOld, object varValueNew) { return VSConstants.S_OK; } public int OnSelectionChanged(IVsHierarchy pHierOld, uint itemidOld, IVsMultiItemSelect pMISOld, ISelectionContainer pSCOld, IVsHierarchy pHierNew, uint itemidNew, IVsMultiItemSelect pMISNew, ISelectionContainer pSCNew) { return VSConstants.S_OK; } #endregion } }
#region Copyright notice and license // Copyright 2015, Google 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. // * Neither the name of Google Inc. 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.Diagnostics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; using Grpc.Core.Internal; using Grpc.Core.Logging; using Grpc.Core.Utils; namespace Grpc.Core.Internal { /// <summary> /// Manages client side native call lifecycle. /// </summary> internal class AsyncCall<TRequest, TResponse> : AsyncCallBase<TRequest, TResponse> { static readonly ILogger Logger = GrpcEnvironment.Logger.ForType<AsyncCall<TRequest, TResponse>>(); readonly CallInvocationDetails<TRequest, TResponse> details; readonly INativeCall injectedNativeCall; // for testing // Completion of a pending unary response if not null. TaskCompletionSource<TResponse> unaryResponseTcs; // Indicates that steaming call has finished. TaskCompletionSource<object> streamingCallFinishedTcs = new TaskCompletionSource<object>(); // Response headers set here once received. TaskCompletionSource<Metadata> responseHeadersTcs = new TaskCompletionSource<Metadata>(); // Set after status is received. Used for both unary and streaming response calls. ClientSideStatus? finishedStatus; public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails) : base(callDetails.RequestMarshaller.Serializer, callDetails.ResponseMarshaller.Deserializer, callDetails.Channel.Environment) { this.details = callDetails.WithOptions(callDetails.Options.Normalize()); this.initialMetadataSent = true; // we always send metadata at the very beginning of the call. } /// <summary> /// This constructor should only be used for testing. /// </summary> public AsyncCall(CallInvocationDetails<TRequest, TResponse> callDetails, INativeCall injectedNativeCall) : this(callDetails) { this.injectedNativeCall = injectedNativeCall; } // TODO: this method is not Async, so it shouldn't be in AsyncCall class, but // it is reusing fair amount of code in this class, so we are leaving it here. /// <summary> /// Blocking unary request - unary response call. /// </summary> public TResponse UnaryCall(TRequest msg) { using (CompletionQueueSafeHandle cq = CompletionQueueSafeHandle.Create()) { byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); lock (myLock) { Preconditions.CheckState(!started); started = true; Initialize(cq); halfcloseRequested = true; readingDone = true; } using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { using (var ctx = BatchContextSafeHandle.Create()) { call.StartUnary(ctx, payload, metadataArray, GetWriteFlagsForCall()); var ev = cq.Pluck(ctx.Handle); bool success = (ev.success != 0); try { HandleUnaryResponse(success, ctx.GetReceivedStatusOnClient(), ctx.GetReceivedMessage(), ctx.GetReceivedInitialMetadata()); } catch (Exception e) { Logger.Error(e, "Exception occured while invoking completion delegate."); } } } // Once the blocking call returns, the result should be available synchronously. // Note that GetAwaiter().GetResult() doesn't wrap exceptions in AggregateException. return unaryResponseTcs.Task.GetAwaiter().GetResult(); } } /// <summary> /// Starts a unary request - unary response call. /// </summary> public Task<TResponse> UnaryCallAsync(TRequest msg) { lock (myLock) { Preconditions.CheckState(!started); started = true; Initialize(environment.CompletionQueue); halfcloseRequested = true; readingDone = true; byte[] payload = UnsafeSerialize(msg); unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartUnary(HandleUnaryResponse, payload, metadataArray, GetWriteFlagsForCall()); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a streamed request - unary response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public Task<TResponse> ClientStreamingCallAsync() { lock (myLock) { Preconditions.CheckState(!started); started = true; Initialize(environment.CompletionQueue); readingDone = true; unaryResponseTcs = new TaskCompletionSource<TResponse>(); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartClientStreaming(HandleUnaryResponse, metadataArray); } return unaryResponseTcs.Task; } } /// <summary> /// Starts a unary request - streamed response call. /// </summary> public void StartServerStreamingCall(TRequest msg) { lock (myLock) { Preconditions.CheckState(!started); started = true; Initialize(environment.CompletionQueue); halfcloseRequested = true; byte[] payload = UnsafeSerialize(msg); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartServerStreaming(HandleFinished, payload, metadataArray, GetWriteFlagsForCall()); } call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders); } } /// <summary> /// Starts a streaming request - streaming response call. /// Use StartSendMessage and StartSendCloseFromClient to stream requests. /// </summary> public void StartDuplexStreamingCall() { lock (myLock) { Preconditions.CheckState(!started); started = true; Initialize(environment.CompletionQueue); using (var metadataArray = MetadataArraySafeHandle.Create(details.Options.Headers)) { call.StartDuplexStreaming(HandleFinished, metadataArray); } call.StartReceiveInitialMetadata(HandleReceivedResponseHeaders); } } /// <summary> /// Sends a streaming request. Only one pending send action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartSendMessage(TRequest msg, WriteFlags writeFlags, AsyncCompletionDelegate<object> completionDelegate) { StartSendMessageInternal(msg, writeFlags, completionDelegate); } /// <summary> /// Receives a streaming response. Only one pending read action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartReadMessage(AsyncCompletionDelegate<TResponse> completionDelegate) { StartReadMessageInternal(completionDelegate); } /// <summary> /// Sends halfclose, indicating client is done with streaming requests. /// Only one pending send action is allowed at any given time. /// completionDelegate is called when the operation finishes. /// </summary> public void StartSendCloseFromClient(AsyncCompletionDelegate<object> completionDelegate) { lock (myLock) { Preconditions.CheckNotNull(completionDelegate, "Completion delegate cannot be null"); CheckSendingAllowed(); call.StartSendCloseFromClient(HandleHalfclosed); halfcloseRequested = true; sendCompletionDelegate = completionDelegate; } } /// <summary> /// Get the task that completes once if streaming call finishes with ok status and throws RpcException with given status otherwise. /// </summary> public Task StreamingCallFinishedTask { get { return streamingCallFinishedTcs.Task; } } /// <summary> /// Get the task that completes once response headers are received. /// </summary> public Task<Metadata> ResponseHeadersAsync { get { return responseHeadersTcs.Task; } } /// <summary> /// Gets the resulting status if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Status GetStatus() { lock (myLock) { Preconditions.CheckState(finishedStatus.HasValue, "Status can only be accessed once the call has finished."); return finishedStatus.Value.Status; } } /// <summary> /// Gets the trailing metadata if the call has already finished. /// Throws InvalidOperationException otherwise. /// </summary> public Metadata GetTrailers() { lock (myLock) { Preconditions.CheckState(finishedStatus.HasValue, "Trailers can only be accessed once the call has finished."); return finishedStatus.Value.Trailers; } } public CallInvocationDetails<TRequest, TResponse> Details { get { return this.details; } } protected override void OnAfterReleaseResources() { details.Channel.RemoveCallReference(this); } private void Initialize(CompletionQueueSafeHandle cq) { var call = CreateNativeCall(cq); details.Channel.AddCallReference(this); InitializeInternal(call); RegisterCancellationCallback(); } private INativeCall CreateNativeCall(CompletionQueueSafeHandle cq) { if (injectedNativeCall != null) { return injectedNativeCall; // allows injecting a mock INativeCall in tests. } var parentCall = details.Options.PropagationToken != null ? details.Options.PropagationToken.ParentCall : CallSafeHandle.NullInstance; return details.Channel.Handle.CreateCall(environment.CompletionRegistry, parentCall, ContextPropagationToken.DefaultMask, cq, details.Method, details.Host, Timespec.FromDateTime(details.Options.Deadline.Value)); } // Make sure that once cancellationToken for this call is cancelled, Cancel() will be called. private void RegisterCancellationCallback() { var token = details.Options.CancellationToken; if (token.CanBeCanceled) { token.Register(() => this.Cancel()); } } /// <summary> /// Gets WriteFlags set in callDetails.Options.WriteOptions /// </summary> private WriteFlags GetWriteFlagsForCall() { var writeOptions = details.Options.WriteOptions; return writeOptions != null ? writeOptions.Flags : default(WriteFlags); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleReceivedResponseHeaders(bool success, Metadata responseHeaders) { responseHeadersTcs.SetResult(responseHeaders); } /// <summary> /// Handler for unary response completion. /// </summary> private void HandleUnaryResponse(bool success, ClientSideStatus receivedStatus, byte[] receivedMessage, Metadata responseHeaders) { lock (myLock) { finished = true; finishedStatus = receivedStatus; ReleaseResourcesIfPossible(); } responseHeadersTcs.SetResult(responseHeaders); var status = receivedStatus.Status; if (!success || status.StatusCode != StatusCode.OK) { unaryResponseTcs.SetException(new RpcException(status)); return; } // TODO: handle deserialization error TResponse msg; TryDeserialize(receivedMessage, out msg); unaryResponseTcs.SetResult(msg); } /// <summary> /// Handles receive status completion for calls with streaming response. /// </summary> private void HandleFinished(bool success, ClientSideStatus receivedStatus) { lock (myLock) { finished = true; finishedStatus = receivedStatus; ReleaseResourcesIfPossible(); } var status = receivedStatus.Status; if (!success || status.StatusCode != StatusCode.OK) { streamingCallFinishedTcs.SetException(new RpcException(status)); return; } streamingCallFinishedTcs.SetResult(null); } } }
using System; using System.Text; using System.Data; using System.Data.SqlClient; using System.Data.Common; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.Xml; using System.Xml.Serialization; using SubSonic; using SubSonic.Utilities; namespace DalSic { /// <summary> /// Strongly-typed collection for the GuardiaRegistrosClasificacione class. /// </summary> [Serializable] public partial class GuardiaRegistrosClasificacioneCollection : ActiveList<GuardiaRegistrosClasificacione, GuardiaRegistrosClasificacioneCollection> { public GuardiaRegistrosClasificacioneCollection() {} /// <summary> /// Filters an existing collection based on the set criteria. This is an in-memory filter /// Thanks to developingchris for this! /// </summary> /// <returns>GuardiaRegistrosClasificacioneCollection</returns> public GuardiaRegistrosClasificacioneCollection Filter() { for (int i = this.Count - 1; i > -1; i--) { GuardiaRegistrosClasificacione o = this[i]; foreach (SubSonic.Where w in this.wheres) { bool remove = false; System.Reflection.PropertyInfo pi = o.GetType().GetProperty(w.ColumnName); if (pi.CanRead) { object val = pi.GetValue(o, null); switch (w.Comparison) { case SubSonic.Comparison.Equals: if (!val.Equals(w.ParameterValue)) { remove = true; } break; } } if (remove) { this.Remove(o); break; } } } return this; } } /// <summary> /// This is an ActiveRecord class which wraps the Guardia_Registros_Clasificaciones table. /// </summary> [Serializable] public partial class GuardiaRegistrosClasificacione : ActiveRecord<GuardiaRegistrosClasificacione>, IActiveRecord { #region .ctors and Default Settings public GuardiaRegistrosClasificacione() { SetSQLProps(); InitSetDefaults(); MarkNew(); } private void InitSetDefaults() { SetDefaults(); } public GuardiaRegistrosClasificacione(bool useDatabaseDefaults) { SetSQLProps(); if(useDatabaseDefaults) ForceDefaults(); MarkNew(); } public GuardiaRegistrosClasificacione(object keyID) { SetSQLProps(); InitSetDefaults(); LoadByKey(keyID); } public GuardiaRegistrosClasificacione(string columnName, object columnValue) { SetSQLProps(); InitSetDefaults(); LoadByParam(columnName,columnValue); } protected static void SetSQLProps() { GetTableSchema(); } #endregion #region Schema and Query Accessor public static Query CreateQuery() { return new Query(Schema); } public static TableSchema.Table Schema { get { if (BaseSchema == null) SetSQLProps(); return BaseSchema; } } private static void GetTableSchema() { if(!IsSchemaInitialized) { //Schema declaration TableSchema.Table schema = new TableSchema.Table("Guardia_Registros_Clasificaciones", TableType.Table, DataService.GetInstance("sicProvider")); schema.Columns = new TableSchema.TableColumnCollection(); schema.SchemaName = @"dbo"; //columns TableSchema.TableColumn colvarId = new TableSchema.TableColumn(schema); colvarId.ColumnName = "id"; colvarId.DataType = DbType.Int32; colvarId.MaxLength = 0; colvarId.AutoIncrement = false; colvarId.IsNullable = false; colvarId.IsPrimaryKey = true; colvarId.IsForeignKey = false; colvarId.IsReadOnly = false; colvarId.DefaultSetting = @""; colvarId.ForeignKeyTableName = ""; schema.Columns.Add(colvarId); TableSchema.TableColumn colvarNombre = new TableSchema.TableColumn(schema); colvarNombre.ColumnName = "nombre"; colvarNombre.DataType = DbType.AnsiString; colvarNombre.MaxLength = 50; colvarNombre.AutoIncrement = false; colvarNombre.IsNullable = false; colvarNombre.IsPrimaryKey = false; colvarNombre.IsForeignKey = false; colvarNombre.IsReadOnly = false; colvarNombre.DefaultSetting = @""; colvarNombre.ForeignKeyTableName = ""; schema.Columns.Add(colvarNombre); BaseSchema = schema; //add this schema to the provider //so we can query it later DataService.Providers["sicProvider"].AddSchema("Guardia_Registros_Clasificaciones",schema); } } #endregion #region Props [XmlAttribute("Id")] [Bindable(true)] public int Id { get { return GetColumnValue<int>(Columns.Id); } set { SetColumnValue(Columns.Id, value); } } [XmlAttribute("Nombre")] [Bindable(true)] public string Nombre { get { return GetColumnValue<string>(Columns.Nombre); } set { SetColumnValue(Columns.Nombre, value); } } #endregion //no foreign key tables defined (0) //no ManyToMany tables defined (0) #region ObjectDataSource support /// <summary> /// Inserts a record, can be used with the Object Data Source /// </summary> public static void Insert(int varId,string varNombre) { GuardiaRegistrosClasificacione item = new GuardiaRegistrosClasificacione(); item.Id = varId; item.Nombre = varNombre; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } /// <summary> /// Updates a record, can be used with the Object Data Source /// </summary> public static void Update(int varId,string varNombre) { GuardiaRegistrosClasificacione item = new GuardiaRegistrosClasificacione(); item.Id = varId; item.Nombre = varNombre; item.IsNew = false; if (System.Web.HttpContext.Current != null) item.Save(System.Web.HttpContext.Current.User.Identity.Name); else item.Save(System.Threading.Thread.CurrentPrincipal.Identity.Name); } #endregion #region Typed Columns public static TableSchema.TableColumn IdColumn { get { return Schema.Columns[0]; } } public static TableSchema.TableColumn NombreColumn { get { return Schema.Columns[1]; } } #endregion #region Columns Struct public struct Columns { public static string Id = @"id"; public static string Nombre = @"nombre"; } #endregion #region Update PK Collections #endregion #region Deep Save #endregion } }
/* * This file is part of UniERM ReportDesigner, based on reportFU by Josh Wilson, * the work of Kim Sheffield and the fyiReporting project. * * Prior Copyrights: * _________________________________________________________ * |Copyright (C) 2010 devFU Pty Ltd, Josh Wilson and Others| * | (http://reportfu.org) | * ========================================================= * _________________________________________________________ * |Copyright (C) 2004-2008 fyiReporting Software, LLC | * |For additional information, email info@fyireporting.com | * |or visit the website www.fyiReporting.com. | * ========================================================= * * License: * * 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.ComponentModel; using System.Drawing; using System.Data; using System.Windows.Forms; namespace Reporting.RdlDesign { internal class DGCBColumn : DataGridColumnStyle { private ComboBox _cb = new ComboBox(); private bool editing = false; private string originalText; CurrencyManager _CM; int _Row; public DGCBColumn() : this(ComboBoxStyle.DropDownList) { } public DGCBColumn(ComboBoxStyle cbs) { _cb.Visible = false; _cb.DropDownStyle = cbs; } protected override void Abort(int row) { RollBack(); HideComboBox(); EndEdit(); } internal ComboBox CB { get {return _cb;} } protected override bool Commit(CurrencyManager cm, int row) { // if (!editing) // return true; try { object o = _cb.Text; if (NullText.Equals(o)) o = System.Convert.DBNull; SetColumnValueAtRow(cm, row, o); } catch { // EndEdit(); return false; } // HideComboBox(); // EndEdit(); return true; } protected override void ConcedeFocus() { if (editing) { object o = _cb.Text; if (NullText.Equals(o)) o = System.Convert.DBNull; SetColumnValueAtRow(_CM, _Row, o); } HideComboBox(); EndEdit(); } protected override void Edit(CurrencyManager cm, int row, Rectangle rect, bool readOnly, string text, bool visible) { _CM = cm; _Row = row; originalText = _cb.Text; _cb.Text = string.Empty; _cb.Bounds = rect; _cb.RightToLeft = DataGridTableStyle.DataGrid.RightToLeft; _cb.Visible = visible; if (text != null) _cb.Text = text; else { string temp = GetText(GetColumnValueAtRow(cm, row)); _cb.Text = temp; } _cb.Select(_cb.Text.Length, 0); if (_cb.Visible) DataGridTableStyle.DataGrid.Invalidate(_cb.Bounds); if (ReadOnly) _cb.Enabled = false; editing = true; } protected override int GetMinimumHeight() { return _cb.PreferredHeight; } protected override int GetPreferredHeight(Graphics g, object o) { return 0; } protected override Size GetPreferredSize(Graphics g, object o) { return new Size(0, 0); } protected override void Paint(Graphics g, Rectangle rect, CurrencyManager cm, int row) { Paint(g, rect, cm, row, false); } protected override void Paint(Graphics g, Rectangle rect, CurrencyManager cm, int row, bool alignToRight) { string text = GetText(GetColumnValueAtRow(cm, row)); PaintText(g, rect, text, alignToRight); } protected override void Paint(Graphics g, Rectangle rect, CurrencyManager cm, int row, Brush backBrush, Brush foreBrush, bool alignToRight) { string text = GetText(GetColumnValueAtRow(cm, row)); PaintText(g, rect, text, backBrush, foreBrush, alignToRight); } protected override void SetDataGridInColumn(DataGrid dg) { base.SetDataGridInColumn(dg); if (_cb.Parent != dg) { if (_cb.Parent != null) { _cb.Parent.Controls.Remove(_cb); } } if (dg != null) dg.Controls.Add(_cb); } protected override void UpdateUI(CurrencyManager cm, int row, string text) { _cb.Text = GetText(GetColumnValueAtRow(cm, row)); if (text != null) _cb.Text = text; } private int DataGridTableGridLineWidth { get { return (DataGridTableStyle.GridLineStyle == DataGridLineStyle.Solid) ? 1 : 0; } } public void EndEdit() { editing = false; Invalidate(); } private string GetText(object o) { if (o == System.DBNull.Value) return NullText; if (o != null) return o.ToString(); else return string.Empty; } private void HideComboBox() { if (_cb.Focused) DataGridTableStyle.DataGrid.Focus(); _cb.Visible = false; } private void RollBack() { _cb.Text = originalText; } protected virtual void PaintText(Graphics g, Rectangle rect, string text, bool alignToRight) { Brush backBrush = new SolidBrush(DataGridTableStyle.BackColor); Brush foreBrush = new SolidBrush(DataGridTableStyle.ForeColor); PaintText(g, rect, text, backBrush, foreBrush, alignToRight); } protected virtual void PaintText(Graphics g, Rectangle rect, string text, Brush backBrush, Brush foreBrush, bool alignToRight) { StringFormat format = new StringFormat(); if (alignToRight) format.FormatFlags = StringFormatFlags.DirectionRightToLeft; switch (Alignment) { case HorizontalAlignment.Left: format.Alignment = StringAlignment.Near; break; case HorizontalAlignment.Right: format.Alignment = StringAlignment.Far; break; case HorizontalAlignment.Center: format.Alignment = StringAlignment.Center; break; } format.LineAlignment = StringAlignment.Center; format.FormatFlags = StringFormatFlags.NoWrap; g.FillRectangle(backBrush, rect); g.DrawString(text, DataGridTableStyle.DataGrid.Font, foreBrush, rect, format); format.Dispose(); } } }
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Numerics; using System.Text; using ParquetSharp.IO.Api; namespace ParquetHadoopTests.Statistics { public class RandomValues { private const string ALPHABET = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz1234567890"; public abstract class RandomValueGenerator<T> where T : IComparable<T> { private readonly Random random; protected RandomValueGenerator(int seed) { this.random = new Random(seed); } public bool shouldGenerateNull() { return (random.Next(10) == 0); } public int randomInt() { return randomInt(int.MaxValue - 1); } public int randomInt(int maximum) { // Maximum may be a random number (which may be negative). return random.Next(Math.Abs(maximum) + 1); } public long randomLong() { return (long)(((ulong)random.Next()) << 32 | (uint)random.Next()); } public long randomLong(long maximum) { return randomLong() % maximum; } public float randomFloat() { return (float)random.NextDouble(); } public float randomFloat(float maximum) { return randomFloat() % maximum; } public double randomDouble() { return random.NextDouble(); } public double randomDouble(double maximum) { return randomDouble() % maximum; } public BigInteger randomInt96() { byte[] bytes = new byte[12]; random.NextBytes(bytes); return new BigInteger(bytes); } public BigInteger randomInt96(BigInteger maximum) { BigInteger result; while ((result = randomInt96()).CompareTo(maximum) > 0) ; return result; } public char randomLetter() { return ALPHABET[randomInt() % ALPHABET.Length]; } public string randomString(int maxLength) { return randomFixedLengthString(randomInt(maxLength)); } public string randomFixedLengthString(int length) { StringBuilder builder = new StringBuilder(); for (int index = 0; index < length; index++) { builder.Append(randomLetter()); } return builder.ToString(); } public abstract T nextValue(); } public abstract class RandomBinaryBase<T> : RandomValueGenerator<T> where T : IComparable<T> { protected readonly int bufferLength; protected readonly byte[] buffer; public RandomBinaryBase(int seed, int bufferLength) : base(seed) { this.bufferLength = bufferLength; this.buffer = new byte[bufferLength]; } public abstract Binary nextBinaryValue(); public Binary asReusedBinary(byte[] data) { int length = Math.Min(data.Length, bufferLength); Array.Copy(data, 0, buffer, 0, length); return Binary.fromReusedByteArray(data, 0, length); } } public class IntGenerator : RandomValueGenerator<int> { private readonly RandomRange<int> randomRange; private readonly int minimum; private readonly int maximum; private readonly int range; public IntGenerator(int seed) : base(seed) { randomRange = new RandomRange<int>(randomInt(), randomInt()); minimum = randomRange.minimum(); maximum = randomRange.maximum(); range = (maximum - minimum); } public override int nextValue() { return (minimum + randomInt(range)); } } public class LongGenerator : RandomValueGenerator<long> { private readonly RandomRange<long> randomRange; private readonly long minimum; private readonly long maximum; private readonly long range; public LongGenerator(int seed) : base(seed) { randomRange = new RandomRange<long>(randomLong(), randomLong()); minimum = randomRange.minimum(); maximum = randomRange.maximum(); range = (maximum - minimum); } public override long nextValue() { return (minimum + randomLong(range)); } } public class Int96Generator : RandomBinaryBase<BigInteger> { private readonly RandomRange<BigInteger> randomRange; private readonly BigInteger minimum; private readonly BigInteger maximum; private readonly BigInteger range; private const int INT_96_LENGTH = 12; public Int96Generator(int seed) : base(seed, INT_96_LENGTH) { randomRange = new RandomRange<BigInteger>(randomInt96(), randomInt96()); minimum = randomRange.minimum(); maximum = randomRange.maximum(); range = maximum - minimum; } public override BigInteger nextValue() { return minimum + randomInt96(range); } public override Binary nextBinaryValue() { return asReusedBinary(nextValue().ToByteArray()); } } public class FloatGenerator : RandomValueGenerator<float> { private readonly RandomRange<float> randomRange; private readonly float minimum; private readonly float maximum; private readonly float range; public FloatGenerator(int seed) : base(seed) { randomRange = new RandomRange<float>(randomFloat(), randomFloat()); minimum = randomRange.minimum(); maximum = randomRange.maximum(); range = (maximum - minimum); } public override float nextValue() { return (minimum + randomFloat(range)); } } public class DoubleGenerator : RandomValueGenerator<double> { private readonly RandomRange<double> randomRange; private readonly double minimum; private readonly double maximum; private readonly double range; public DoubleGenerator(int seed) : base(seed) { randomRange = new RandomRange<double>(randomDouble(), randomDouble()); minimum = randomRange.minimum(); maximum = randomRange.maximum(); range = (maximum - minimum); } public override double nextValue() { return (minimum + randomDouble(range)); } } public class StringGenerator : RandomBinaryBase<string> { private const int MAX_STRING_LENGTH = 16; public StringGenerator(int seed) : base(seed, MAX_STRING_LENGTH) { } public override string nextValue() { int stringLength = randomInt(15) + 1; return randomString(stringLength); } public override Binary nextBinaryValue() { return asReusedBinary(Encoding.UTF8.GetBytes(nextValue())); } } public class BinaryGenerator : RandomBinaryBase<Binary> { private const int MAX_STRING_LENGTH = 16; public BinaryGenerator(int seed) : base(seed, MAX_STRING_LENGTH) { } public override Binary nextValue() { // use a random length, but ensure it is at least a few bytes int length = 5 + randomInt(buffer.Length - 5); for (int index = 0; index < length; index++) { buffer[index] = (byte)randomInt(); } return Binary.fromReusedByteArray(buffer, 0, length); } public override Binary nextBinaryValue() { return nextValue(); } } public class FixedGenerator : RandomBinaryBase<Binary> { public FixedGenerator(int seed, int length) : base(seed, length) { } public override Binary nextValue() { for (int index = 0; index < buffer.Length; index++) { buffer[index] = (byte)randomInt(); } return Binary.fromReusedByteArray(buffer); } public override Binary nextBinaryValue() { return nextValue(); } } class RandomRange<T> where T : IComparable<T> { private T _minimum; private T _maximum; public RandomRange(T lhs, T rhs) { this._minimum = lhs; this._maximum = rhs; if (_minimum.CompareTo(rhs) > 0) { T temporary = _minimum; _minimum = _maximum; _maximum = temporary; } } public T minimum() { return this._minimum; } public T maximum() { return this._maximum; } } } }
// This file was generated by CSLA Object Generator - CslaGenFork v4.5 // // Filename: DocListGetter // ObjectType: DocListGetter // CSLAType: UnitOfWork using System; using Csla; using DocStore.Business.Admin; namespace DocStore.Business { /// <summary> /// DocListGetter (getter unit of work pattern).<br/> /// This is a generated <see cref="DocListGetter"/> business object. /// This class is a root object that implements the Unit of Work pattern. /// </summary> [Serializable] public partial class DocListGetter : ReadOnlyBase<DocListGetter> { #region Business Properties /// <summary> /// Maintains metadata about unit of work (child) <see cref="DocList"/> property. /// </summary> public static readonly PropertyInfo<DocList> DocListProperty = RegisterProperty<DocList>(p => p.DocList, "Doc List"); /// <summary> /// Gets the Doc List object (unit of work child property). /// </summary> /// <value>The Doc List.</value> public DocList DocList { get { return GetProperty(DocListProperty); } private set { LoadProperty(DocListProperty, value); } } /// <summary> /// Maintains metadata about unit of work (child) <see cref="DocClassNVL"/> property. /// </summary> public static readonly PropertyInfo<DocClassNVL> DocClassNVLProperty = RegisterProperty<DocClassNVL>(p => p.DocClassNVL, "Doc Class NVL"); /// <summary> /// Gets the Doc Class NVL object (unit of work child property). /// </summary> /// <value>The Doc Class NVL.</value> public DocClassNVL DocClassNVL { get { return GetProperty(DocClassNVLProperty); } private set { LoadProperty(DocClassNVLProperty, value); } } /// <summary> /// Maintains metadata about unit of work (child) <see cref="DocTypeNVL"/> property. /// </summary> public static readonly PropertyInfo<DocTypeNVL> DocTypeNVLProperty = RegisterProperty<DocTypeNVL>(p => p.DocTypeNVL, "Doc Type NVL"); /// <summary> /// Gets the Doc Type NVL object (unit of work child property). /// </summary> /// <value>The Doc Type NVL.</value> public DocTypeNVL DocTypeNVL { get { return GetProperty(DocTypeNVLProperty); } private set { LoadProperty(DocTypeNVLProperty, value); } } /// <summary> /// Maintains metadata about unit of work (child) <see cref="DocStatusNVL"/> property. /// </summary> public static readonly PropertyInfo<DocStatusNVL> DocStatusNVLProperty = RegisterProperty<DocStatusNVL>(p => p.DocStatusNVL, "Doc Status NVL"); /// <summary> /// Gets the Doc Status NVL object (unit of work child property). /// </summary> /// <value>The Doc Status NVL.</value> public DocStatusNVL DocStatusNVL { get { return GetProperty(DocStatusNVLProperty); } private set { LoadProperty(DocStatusNVLProperty, value); } } /// <summary> /// Maintains metadata about unit of work (child) <see cref="UserNVL"/> property. /// </summary> public static readonly PropertyInfo<UserNVL> UserNVLProperty = RegisterProperty<UserNVL>(p => p.UserNVL, "User NVL"); /// <summary> /// Gets the User NVL object (unit of work child property). /// </summary> /// <value>The User NVL.</value> public UserNVL UserNVL { get { return GetProperty(UserNVLProperty); } private set { LoadProperty(UserNVLProperty, value); } } #endregion #region Factory Methods /// <summary> /// Factory method. Loads a <see cref="DocListGetter"/> unit of objects. /// </summary> /// <returns>A reference to the fetched <see cref="DocListGetter"/> unit of objects.</returns> public static DocListGetter GetDocListGetter() { return DataPortal.Fetch<DocListGetter>(); } /// <summary> /// Factory method. Loads a <see cref="DocListGetter"/> unit of objects, based on given parameters. /// </summary> /// <param name="docListFilteredCriteria">The DocListFilteredCriteria parameter of the DocListGetter to fetch.</param> /// <returns>A reference to the fetched <see cref="DocListGetter"/> unit of objects.</returns> public static DocListGetter GetDocListGetter(DocListFilteredCriteria docListFilteredCriteria) { return DataPortal.Fetch<DocListGetter>(docListFilteredCriteria); } /// <summary> /// Factory method. Asynchronously loads a <see cref="DocListGetter"/> unit of objects. /// </summary> /// <param name="callback">The completion callback method.</param> public static void GetDocListGetter(EventHandler<DataPortalResult<DocListGetter>> callback) { DataPortal.BeginFetch<DocListGetter>((o, e) => { if (e.Error != null) throw e.Error; if (!DocClassNVL.IsCached) DocClassNVL.SetCache(e.Object.DocClassNVL); if (!DocTypeNVL.IsCached) DocTypeNVL.SetCache(e.Object.DocTypeNVL); if (!DocStatusNVL.IsCached) DocStatusNVL.SetCache(e.Object.DocStatusNVL); if (!UserNVL.IsCached) UserNVL.SetCache(e.Object.UserNVL); callback(o, e); }); } /// <summary> /// Factory method. Asynchronously loads a <see cref="DocListGetter"/> unit of objects, based on given parameters. /// </summary> /// <param name="docListFilteredCriteria">The DocListFilteredCriteria parameter of the DocListGetter to fetch.</param> /// <param name="callback">The completion callback method.</param> public static void GetDocListGetter(DocListFilteredCriteria docListFilteredCriteria, EventHandler<DataPortalResult<DocListGetter>> callback) { DataPortal.BeginFetch<DocListGetter>(docListFilteredCriteria, (o, e) => { if (e.Error != null) throw e.Error; if (!DocClassNVL.IsCached) DocClassNVL.SetCache(e.Object.DocClassNVL); if (!DocTypeNVL.IsCached) DocTypeNVL.SetCache(e.Object.DocTypeNVL); if (!DocStatusNVL.IsCached) DocStatusNVL.SetCache(e.Object.DocStatusNVL); if (!UserNVL.IsCached) UserNVL.SetCache(e.Object.UserNVL); callback(o, e); }); } #endregion #region Constructor /// <summary> /// Initializes a new instance of the <see cref="DocListGetter"/> class. /// </summary> /// <remarks> Do not use to create a Unit of Work. Use factory methods instead.</remarks> [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public DocListGetter() { // Use factory methods and do not use direct creation. } #endregion #region Data Access /// <summary> /// Loads a <see cref="DocListGetter"/> unit of objects. /// </summary> protected void DataPortal_Fetch() { LoadProperty(DocListProperty, DocList.GetDocList()); LoadProperty(DocClassNVLProperty, DocClassNVL.GetDocClassNVL()); LoadProperty(DocTypeNVLProperty, DocTypeNVL.GetDocTypeNVL()); LoadProperty(DocStatusNVLProperty, DocStatusNVL.GetDocStatusNVL()); LoadProperty(UserNVLProperty, UserNVL.GetUserNVL()); } /// <summary> /// Loads a <see cref="DocListGetter"/> unit of objects, based on given criteria. /// </summary> /// <param name="docListFilteredCriteria">The fetch criteria.</param> protected void DataPortal_Fetch(DocListFilteredCriteria docListFilteredCriteria) { LoadProperty(DocListProperty, DocList.GetDocList(docListFilteredCriteria)); LoadProperty(DocClassNVLProperty, DocClassNVL.GetDocClassNVL()); LoadProperty(DocTypeNVLProperty, DocTypeNVL.GetDocTypeNVL()); LoadProperty(DocStatusNVLProperty, DocStatusNVL.GetDocStatusNVL()); LoadProperty(UserNVLProperty, UserNVL.GetUserNVL()); } #endregion } }
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for details. using System; using System.IO; using System.Drawing; using System.Diagnostics; using System.Collections; using System.ComponentModel; using System.Windows.Forms; using OpenLiveWriter.CoreServices; using OpenLiveWriter.Controls; using OpenLiveWriter.Api; using OpenLiveWriter.Localization; namespace OpenLiveWriter.InternalWriterPlugin { internal class MapOptionsDialog : ApplicationDialog { private System.Windows.Forms.Button buttonOK; private System.Windows.Forms.Button buttonCancel; private System.Windows.Forms.GroupBox groupBoxPushpins; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.Label labelPushpinUrl; private System.Windows.Forms.TextBox textBoxPushpinUrl; private System.Windows.Forms.Label label1; private System.Windows.Forms.LinkLabel linkLabelViewPushpin; /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.Container components = null; private MapOptions _mapOptions; public MapOptionsDialog(MapOptions mapOptions) { // // Required for Windows Form Designer support // InitializeComponent(); _mapOptions = mapOptions; textBoxPushpinUrl.Text = _mapOptions.PushpinUrl; linkLabelViewPushpin.Visible = _mapOptions.MoreAboutPushpinsUrl != String.Empty; } /// <summary> /// Clean up any resources being used. /// </summary> protected override void Dispose(bool disposing) { if (disposing) { if (components != null) { components.Dispose(); } } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Resources.ResourceManager resources = new System.Resources.ResourceManager(typeof(MapOptionsDialog)); this.buttonOK = new System.Windows.Forms.Button(); this.buttonCancel = new System.Windows.Forms.Button(); this.groupBoxPushpins = new System.Windows.Forms.GroupBox(); this.linkLabelViewPushpin = new System.Windows.Forms.LinkLabel(); this.label1 = new System.Windows.Forms.Label(); this.labelPushpinUrl = new System.Windows.Forms.Label(); this.textBoxPushpinUrl = new System.Windows.Forms.TextBox(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.groupBoxPushpins.SuspendLayout(); this.SuspendLayout(); // // buttonOK // this.buttonOK.AccessibleDescription = resources.GetString("buttonOK.AccessibleDescription"); this.buttonOK.AccessibleName = resources.GetString("buttonOK.AccessibleName"); this.buttonOK.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("buttonOK.Anchor"))); this.buttonOK.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("buttonOK.BackgroundImage"))); this.buttonOK.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("buttonOK.Dock"))); this.buttonOK.Enabled = ((bool)(resources.GetObject("buttonOK.Enabled"))); this.buttonOK.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("buttonOK.FlatStyle"))); this.buttonOK.Font = ((System.Drawing.Font)(resources.GetObject("buttonOK.Font"))); this.buttonOK.Image = ((System.Drawing.Image)(resources.GetObject("buttonOK.Image"))); this.buttonOK.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("buttonOK.ImageAlign"))); this.buttonOK.ImageIndex = ((int)(resources.GetObject("buttonOK.ImageIndex"))); this.buttonOK.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("buttonOK.ImeMode"))); this.buttonOK.Location = ((System.Drawing.Point)(resources.GetObject("buttonOK.Location"))); this.buttonOK.Name = "buttonOK"; this.buttonOK.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("buttonOK.RightToLeft"))); this.buttonOK.Size = ((System.Drawing.Size)(resources.GetObject("buttonOK.Size"))); this.buttonOK.TabIndex = ((int)(resources.GetObject("buttonOK.TabIndex"))); this.buttonOK.Text = resources.GetString("buttonOK.Text"); this.buttonOK.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("buttonOK.TextAlign"))); this.buttonOK.Visible = ((bool)(resources.GetObject("buttonOK.Visible"))); this.buttonOK.Click += new System.EventHandler(this.buttonOK_Click); // // buttonCancel // this.buttonCancel.AccessibleDescription = resources.GetString("buttonCancel.AccessibleDescription"); this.buttonCancel.AccessibleName = resources.GetString("buttonCancel.AccessibleName"); this.buttonCancel.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("buttonCancel.Anchor"))); this.buttonCancel.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("buttonCancel.BackgroundImage"))); this.buttonCancel.DialogResult = System.Windows.Forms.DialogResult.Cancel; this.buttonCancel.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("buttonCancel.Dock"))); this.buttonCancel.Enabled = ((bool)(resources.GetObject("buttonCancel.Enabled"))); this.buttonCancel.FlatStyle = ((System.Windows.Forms.FlatStyle)(resources.GetObject("buttonCancel.FlatStyle"))); this.buttonCancel.Font = ((System.Drawing.Font)(resources.GetObject("buttonCancel.Font"))); this.buttonCancel.Image = ((System.Drawing.Image)(resources.GetObject("buttonCancel.Image"))); this.buttonCancel.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("buttonCancel.ImageAlign"))); this.buttonCancel.ImageIndex = ((int)(resources.GetObject("buttonCancel.ImageIndex"))); this.buttonCancel.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("buttonCancel.ImeMode"))); this.buttonCancel.Location = ((System.Drawing.Point)(resources.GetObject("buttonCancel.Location"))); this.buttonCancel.Name = "buttonCancel"; this.buttonCancel.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("buttonCancel.RightToLeft"))); this.buttonCancel.Size = ((System.Drawing.Size)(resources.GetObject("buttonCancel.Size"))); this.buttonCancel.TabIndex = ((int)(resources.GetObject("buttonCancel.TabIndex"))); this.buttonCancel.Text = resources.GetString("buttonCancel.Text"); this.buttonCancel.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("buttonCancel.TextAlign"))); this.buttonCancel.Visible = ((bool)(resources.GetObject("buttonCancel.Visible"))); // // groupBoxPushpins // this.groupBoxPushpins.AccessibleDescription = resources.GetString("groupBoxPushpins.AccessibleDescription"); this.groupBoxPushpins.AccessibleName = resources.GetString("groupBoxPushpins.AccessibleName"); this.groupBoxPushpins.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("groupBoxPushpins.Anchor"))); this.groupBoxPushpins.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("groupBoxPushpins.BackgroundImage"))); this.groupBoxPushpins.Controls.Add(this.linkLabelViewPushpin); this.groupBoxPushpins.Controls.Add(this.label1); this.groupBoxPushpins.Controls.Add(this.labelPushpinUrl); this.groupBoxPushpins.Controls.Add(this.textBoxPushpinUrl); this.groupBoxPushpins.Controls.Add(this.pictureBox1); this.groupBoxPushpins.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("groupBoxPushpins.Dock"))); this.groupBoxPushpins.Enabled = ((bool)(resources.GetObject("groupBoxPushpins.Enabled"))); this.groupBoxPushpins.FlatStyle = System.Windows.Forms.FlatStyle.System; this.groupBoxPushpins.Font = ((System.Drawing.Font)(resources.GetObject("groupBoxPushpins.Font"))); this.groupBoxPushpins.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("groupBoxPushpins.ImeMode"))); this.groupBoxPushpins.Location = ((System.Drawing.Point)(resources.GetObject("groupBoxPushpins.Location"))); this.groupBoxPushpins.Name = "groupBoxPushpins"; this.groupBoxPushpins.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("groupBoxPushpins.RightToLeft"))); this.groupBoxPushpins.Size = ((System.Drawing.Size)(resources.GetObject("groupBoxPushpins.Size"))); this.groupBoxPushpins.TabIndex = ((int)(resources.GetObject("groupBoxPushpins.TabIndex"))); this.groupBoxPushpins.TabStop = false; this.groupBoxPushpins.Text = resources.GetString("groupBoxPushpins.Text"); this.groupBoxPushpins.Visible = ((bool)(resources.GetObject("groupBoxPushpins.Visible"))); // // linkLabelViewPushpin // this.linkLabelViewPushpin.AccessibleDescription = resources.GetString("linkLabelViewPushpin.AccessibleDescription"); this.linkLabelViewPushpin.AccessibleName = resources.GetString("linkLabelViewPushpin.AccessibleName"); this.linkLabelViewPushpin.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("linkLabelViewPushpin.Anchor"))); this.linkLabelViewPushpin.AutoSize = ((bool)(resources.GetObject("linkLabelViewPushpin.AutoSize"))); this.linkLabelViewPushpin.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("linkLabelViewPushpin.Dock"))); this.linkLabelViewPushpin.Enabled = ((bool)(resources.GetObject("linkLabelViewPushpin.Enabled"))); this.linkLabelViewPushpin.FlatStyle = System.Windows.Forms.FlatStyle.System; this.linkLabelViewPushpin.Font = ((System.Drawing.Font)(resources.GetObject("linkLabelViewPushpin.Font"))); this.linkLabelViewPushpin.Image = ((System.Drawing.Image)(resources.GetObject("linkLabelViewPushpin.Image"))); this.linkLabelViewPushpin.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("linkLabelViewPushpin.ImageAlign"))); this.linkLabelViewPushpin.ImageIndex = ((int)(resources.GetObject("linkLabelViewPushpin.ImageIndex"))); this.linkLabelViewPushpin.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("linkLabelViewPushpin.ImeMode"))); this.linkLabelViewPushpin.LinkArea = ((System.Windows.Forms.LinkArea)(resources.GetObject("linkLabelViewPushpin.LinkArea"))); this.linkLabelViewPushpin.LinkBehavior = LinkBehavior.HoverUnderline; this.linkLabelViewPushpin.Location = ((System.Drawing.Point)(resources.GetObject("linkLabelViewPushpin.Location"))); this.linkLabelViewPushpin.Name = "linkLabelViewPushpin"; this.linkLabelViewPushpin.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("linkLabelViewPushpin.RightToLeft"))); this.linkLabelViewPushpin.Size = ((System.Drawing.Size)(resources.GetObject("linkLabelViewPushpin.Size"))); this.linkLabelViewPushpin.TabIndex = ((int)(resources.GetObject("linkLabelViewPushpin.TabIndex"))); this.linkLabelViewPushpin.TabStop = true; this.linkLabelViewPushpin.Text = resources.GetString("linkLabelViewPushpin.Text"); this.linkLabelViewPushpin.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("linkLabelViewPushpin.TextAlign"))); this.linkLabelViewPushpin.Visible = ((bool)(resources.GetObject("linkLabelViewPushpin.Visible"))); this.linkLabelViewPushpin.LinkColor = SystemColors.HotTrack; this.linkLabelViewPushpin.LinkClicked += new System.Windows.Forms.LinkLabelLinkClickedEventHandler(this.linkLabelViewPushpin_LinkClicked); // // label1 // this.label1.AccessibleDescription = resources.GetString("label1.AccessibleDescription"); this.label1.AccessibleName = resources.GetString("label1.AccessibleName"); this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("label1.Anchor"))); this.label1.AutoSize = ((bool)(resources.GetObject("label1.AutoSize"))); this.label1.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("label1.Dock"))); this.label1.Enabled = ((bool)(resources.GetObject("label1.Enabled"))); this.label1.FlatStyle = System.Windows.Forms.FlatStyle.System; this.label1.Font = ((System.Drawing.Font)(resources.GetObject("label1.Font"))); this.label1.Image = ((System.Drawing.Image)(resources.GetObject("label1.Image"))); this.label1.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label1.ImageAlign"))); this.label1.ImageIndex = ((int)(resources.GetObject("label1.ImageIndex"))); this.label1.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("label1.ImeMode"))); this.label1.Location = ((System.Drawing.Point)(resources.GetObject("label1.Location"))); this.label1.Name = "label1"; this.label1.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("label1.RightToLeft"))); this.label1.Size = ((System.Drawing.Size)(resources.GetObject("label1.Size"))); this.label1.TabIndex = ((int)(resources.GetObject("label1.TabIndex"))); this.label1.Text = resources.GetString("label1.Text"); this.label1.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("label1.TextAlign"))); this.label1.Visible = ((bool)(resources.GetObject("label1.Visible"))); // // labelPushpinUrl // this.labelPushpinUrl.AccessibleDescription = resources.GetString("labelPushpinUrl.AccessibleDescription"); this.labelPushpinUrl.AccessibleName = resources.GetString("labelPushpinUrl.AccessibleName"); this.labelPushpinUrl.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("labelPushpinUrl.Anchor"))); this.labelPushpinUrl.AutoSize = ((bool)(resources.GetObject("labelPushpinUrl.AutoSize"))); this.labelPushpinUrl.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("labelPushpinUrl.Dock"))); this.labelPushpinUrl.Enabled = ((bool)(resources.GetObject("labelPushpinUrl.Enabled"))); this.labelPushpinUrl.FlatStyle = System.Windows.Forms.FlatStyle.System; this.labelPushpinUrl.Font = ((System.Drawing.Font)(resources.GetObject("labelPushpinUrl.Font"))); this.labelPushpinUrl.Image = ((System.Drawing.Image)(resources.GetObject("labelPushpinUrl.Image"))); this.labelPushpinUrl.ImageAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("labelPushpinUrl.ImageAlign"))); this.labelPushpinUrl.ImageIndex = ((int)(resources.GetObject("labelPushpinUrl.ImageIndex"))); this.labelPushpinUrl.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("labelPushpinUrl.ImeMode"))); this.labelPushpinUrl.Location = ((System.Drawing.Point)(resources.GetObject("labelPushpinUrl.Location"))); this.labelPushpinUrl.Name = "labelPushpinUrl"; this.labelPushpinUrl.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("labelPushpinUrl.RightToLeft"))); this.labelPushpinUrl.Size = ((System.Drawing.Size)(resources.GetObject("labelPushpinUrl.Size"))); this.labelPushpinUrl.TabIndex = ((int)(resources.GetObject("labelPushpinUrl.TabIndex"))); this.labelPushpinUrl.Text = resources.GetString("labelPushpinUrl.Text"); this.labelPushpinUrl.TextAlign = ((System.Drawing.ContentAlignment)(resources.GetObject("labelPushpinUrl.TextAlign"))); this.labelPushpinUrl.Visible = ((bool)(resources.GetObject("labelPushpinUrl.Visible"))); // // textBoxPushpinUrl // this.textBoxPushpinUrl.AccessibleDescription = resources.GetString("textBoxPushpinUrl.AccessibleDescription"); this.textBoxPushpinUrl.AccessibleName = resources.GetString("textBoxPushpinUrl.AccessibleName"); this.textBoxPushpinUrl.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("textBoxPushpinUrl.Anchor"))); this.textBoxPushpinUrl.AutoSize = ((bool)(resources.GetObject("textBoxPushpinUrl.AutoSize"))); this.textBoxPushpinUrl.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("textBoxPushpinUrl.BackgroundImage"))); this.textBoxPushpinUrl.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("textBoxPushpinUrl.Dock"))); this.textBoxPushpinUrl.Enabled = ((bool)(resources.GetObject("textBoxPushpinUrl.Enabled"))); this.textBoxPushpinUrl.Font = ((System.Drawing.Font)(resources.GetObject("textBoxPushpinUrl.Font"))); this.textBoxPushpinUrl.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("textBoxPushpinUrl.ImeMode"))); this.textBoxPushpinUrl.Location = ((System.Drawing.Point)(resources.GetObject("textBoxPushpinUrl.Location"))); this.textBoxPushpinUrl.MaxLength = ((int)(resources.GetObject("textBoxPushpinUrl.MaxLength"))); this.textBoxPushpinUrl.Multiline = ((bool)(resources.GetObject("textBoxPushpinUrl.Multiline"))); this.textBoxPushpinUrl.Name = "textBoxPushpinUrl"; this.textBoxPushpinUrl.PasswordChar = ((char)(resources.GetObject("textBoxPushpinUrl.PasswordChar"))); this.textBoxPushpinUrl.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("textBoxPushpinUrl.RightToLeft"))); this.textBoxPushpinUrl.ScrollBars = ((System.Windows.Forms.ScrollBars)(resources.GetObject("textBoxPushpinUrl.ScrollBars"))); this.textBoxPushpinUrl.Size = ((System.Drawing.Size)(resources.GetObject("textBoxPushpinUrl.Size"))); this.textBoxPushpinUrl.TabIndex = ((int)(resources.GetObject("textBoxPushpinUrl.TabIndex"))); this.textBoxPushpinUrl.Text = resources.GetString("textBoxPushpinUrl.Text"); this.textBoxPushpinUrl.TextAlign = ((System.Windows.Forms.HorizontalAlignment)(resources.GetObject("textBoxPushpinUrl.TextAlign"))); this.textBoxPushpinUrl.Visible = ((bool)(resources.GetObject("textBoxPushpinUrl.Visible"))); this.textBoxPushpinUrl.WordWrap = ((bool)(resources.GetObject("textBoxPushpinUrl.WordWrap"))); // // pictureBox1 // this.pictureBox1.AccessibleDescription = resources.GetString("pictureBox1.AccessibleDescription"); this.pictureBox1.AccessibleName = resources.GetString("pictureBox1.AccessibleName"); this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)(resources.GetObject("pictureBox1.Anchor"))); this.pictureBox1.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("pictureBox1.BackgroundImage"))); this.pictureBox1.Dock = ((System.Windows.Forms.DockStyle)(resources.GetObject("pictureBox1.Dock"))); this.pictureBox1.Enabled = ((bool)(resources.GetObject("pictureBox1.Enabled"))); this.pictureBox1.Font = ((System.Drawing.Font)(resources.GetObject("pictureBox1.Font"))); this.pictureBox1.Image = ((System.Drawing.Image)(resources.GetObject("pictureBox1.Image"))); this.pictureBox1.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("pictureBox1.ImeMode"))); this.pictureBox1.Location = ((System.Drawing.Point)(resources.GetObject("pictureBox1.Location"))); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("pictureBox1.RightToLeft"))); this.pictureBox1.Size = ((System.Drawing.Size)(resources.GetObject("pictureBox1.Size"))); this.pictureBox1.SizeMode = ((System.Windows.Forms.PictureBoxSizeMode)(resources.GetObject("pictureBox1.SizeMode"))); this.pictureBox1.TabIndex = ((int)(resources.GetObject("pictureBox1.TabIndex"))); this.pictureBox1.TabStop = false; this.pictureBox1.Text = resources.GetString("pictureBox1.Text"); this.pictureBox1.Visible = ((bool)(resources.GetObject("pictureBox1.Visible"))); // // MapOptionsDialog // this.AcceptButton = this.buttonOK; this.AccessibleDescription = resources.GetString("$this.AccessibleDescription"); this.AccessibleName = resources.GetString("$this.AccessibleName"); this.AutoScaleBaseSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScaleBaseSize"))); this.AutoScroll = ((bool)(resources.GetObject("$this.AutoScroll"))); this.AutoScrollMargin = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMargin"))); this.AutoScrollMinSize = ((System.Drawing.Size)(resources.GetObject("$this.AutoScrollMinSize"))); this.BackgroundImage = ((System.Drawing.Image)(resources.GetObject("$this.BackgroundImage"))); this.CancelButton = this.buttonCancel; this.ClientSize = ((System.Drawing.Size)(resources.GetObject("$this.ClientSize"))); this.Controls.Add(this.groupBoxPushpins); this.Controls.Add(this.buttonCancel); this.Controls.Add(this.buttonOK); this.Enabled = ((bool)(resources.GetObject("$this.Enabled"))); this.Font = ((System.Drawing.Font)(resources.GetObject("$this.Font"))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.ImeMode = ((System.Windows.Forms.ImeMode)(resources.GetObject("$this.ImeMode"))); this.Location = ((System.Drawing.Point)(resources.GetObject("$this.Location"))); this.MaximizeBox = false; this.MaximumSize = ((System.Drawing.Size)(resources.GetObject("$this.MaximumSize"))); this.MinimizeBox = false; this.MinimumSize = ((System.Drawing.Size)(resources.GetObject("$this.MinimumSize"))); this.Name = "MapOptionsDialog"; this.RightToLeft = ((System.Windows.Forms.RightToLeft)(resources.GetObject("$this.RightToLeft"))); this.StartPosition = ((System.Windows.Forms.FormStartPosition)(resources.GetObject("$this.StartPosition"))); this.Text = resources.GetString("$this.Text"); this.groupBoxPushpins.ResumeLayout(false); this.ResumeLayout(false); } #endregion private void buttonOK_Click(object sender, System.EventArgs e) { if (ValidatePushpinUrl()) { _mapOptions.PushpinUrl = PushpinUrl; DialogResult = DialogResult.OK; } } private void linkLabelViewPushpin_LinkClicked(object sender, System.Windows.Forms.LinkLabelLinkClickedEventArgs e) { try { Process.Start(_mapOptions.MoreAboutPushpinsUrl); } catch (Exception ex) { Trace.Fail("Unexpected error launching pushpin url " + _mapOptions.MoreAboutPushpinsUrl + ": " + ex.ToString()); } } private string PushpinUrl { get { return UrlHelper.FixUpUrl(textBoxPushpinUrl.Text.Trim()); } } private bool ValidatePushpinUrl() { using (new WaitCursor()) { // empty url is ok, means no custom pushpin if (PushpinUrl == String.Empty) return true; // try to validate (take no more than 5 seconds) try { PluginHttpRequest request = new PluginHttpRequest(PushpinUrl, HttpRequestCacheLevel.CacheIfAvailable); using (Stream response = request.GetResponse(5000)) { if (response == null) return ShowPushpinValidationError(); else return true; } } catch (Exception) { return ShowPushpinValidationError(); } } } private bool ShowPushpinValidationError() { DialogResult result = DisplayMessage.Show(MessageId.PushpinValidationError); return result == DialogResult.Yes; } } }
using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.Configuration; using System.IO; using System.Linq; using System.Reflection; using NUnit.Framework; using SqlCE4Umbraco; using Umbraco.Core; using Umbraco.Core.IO; using umbraco.DataLayer; using Umbraco.Core.Models.EntityBase; using GlobalSettings = umbraco.GlobalSettings; namespace Umbraco.Tests.TestHelpers { /// <summary> /// Common helper properties and methods useful to testing /// </summary> public static class TestHelper { /// <summary> /// Clears an initialized database /// </summary> public static void ClearDatabase() { var databaseSettings = ConfigurationManager.ConnectionStrings[Core.Configuration.GlobalSettings.UmbracoConnectionName]; var dataHelper = DataLayerHelper.CreateSqlHelper(databaseSettings.ConnectionString, false) as SqlCEHelper; if (dataHelper == null) throw new InvalidOperationException("The sql helper for unit tests must be of type SqlCEHelper, check the ensure the connection string used for this test is set to use SQLCE"); dataHelper.ClearDatabase(); } public static void DropForeignKeys(string table) { var databaseSettings = ConfigurationManager.ConnectionStrings[Core.Configuration.GlobalSettings.UmbracoConnectionName]; var dataHelper = DataLayerHelper.CreateSqlHelper(databaseSettings.ConnectionString, false) as SqlCEHelper; if (dataHelper == null) throw new InvalidOperationException("The sql helper for unit tests must be of type SqlCEHelper, check the ensure the connection string used for this test is set to use SQLCE"); dataHelper.DropForeignKeys(table); } /// <summary> /// Gets the current assembly directory. /// </summary> /// <value>The assembly directory.</value> static public string CurrentAssemblyDirectory { get { var codeBase = typeof(TestHelper).Assembly.CodeBase; var uri = new Uri(codeBase); var path = uri.LocalPath; return Path.GetDirectoryName(path); } } /// <summary> /// Maps the given <paramref name="relativePath"/> making it rooted on <see cref="CurrentAssemblyDirectory"/>. <paramref name="relativePath"/> must start with <code>~/</code> /// </summary> /// <param name="relativePath">The relative path.</param> /// <returns></returns> public static string MapPathForTest(string relativePath) { if (!relativePath.StartsWith("~/")) throw new ArgumentException("relativePath must start with '~/'", "relativePath"); return relativePath.Replace("~/", CurrentAssemblyDirectory + "/"); } public static void InitializeContentDirectories() { CreateDirectories(new[] { SystemDirectories.Masterpages, SystemDirectories.MvcViews, SystemDirectories.Media, SystemDirectories.AppPlugins }); } public static void CleanContentDirectories() { CleanDirectories(new[] { SystemDirectories.Masterpages, SystemDirectories.MvcViews, SystemDirectories.Media }); } public static void CreateDirectories(string[] directories) { foreach (var directory in directories) { var directoryInfo = new DirectoryInfo(IOHelper.MapPath(directory)); if (directoryInfo.Exists == false) Directory.CreateDirectory(IOHelper.MapPath(directory)); } } public static void CleanDirectories(string[] directories) { var preserves = new Dictionary<string, string[]> { { SystemDirectories.Masterpages, new[] {"dummy.txt"} }, { SystemDirectories.MvcViews, new[] {"dummy.txt"} } }; foreach (var directory in directories) { var directoryInfo = new DirectoryInfo(IOHelper.MapPath(directory)); var preserve = preserves.ContainsKey(directory) ? preserves[directory] : null; if (directoryInfo.Exists) directoryInfo.GetFiles().Where(x => preserve == null || preserve.Contains(x.Name) == false).ForEach(x => x.Delete()); } } public static void CleanUmbracoSettingsConfig() { var currDir = new DirectoryInfo(CurrentAssemblyDirectory); var umbracoSettingsFile = Path.Combine(currDir.Parent.Parent.FullName, "config", "umbracoSettings.config"); if (File.Exists(umbracoSettingsFile)) File.Delete(umbracoSettingsFile); } public static void AssertAllPropertyValuesAreEquals(object actual, object expected, string dateTimeFormat = null, Func<IEnumerable, IEnumerable> sorter = null, string[] ignoreProperties = null) { var properties = expected.GetType().GetProperties(); foreach (var property in properties) { //ignore properties that are attributed with this var att = property.GetCustomAttribute<EditorBrowsableAttribute>(false); if (att != null && att.State == EditorBrowsableState.Never) continue; if (ignoreProperties != null && ignoreProperties.Contains(property.Name)) continue; var expectedValue = property.GetValue(expected, null); var actualValue = property.GetValue(actual, null); if (((actualValue is string) == false) && actualValue is IEnumerable) { AssertListsAreEquals(property, (IEnumerable)actualValue, (IEnumerable)expectedValue, dateTimeFormat, sorter); } else if (dateTimeFormat.IsNullOrWhiteSpace() == false && actualValue is DateTime) { // round to second else in some cases tests can fail ;-( var expectedDateTime = (DateTime) expectedValue; expectedDateTime = expectedDateTime.AddTicks(-(expectedDateTime.Ticks%TimeSpan.TicksPerSecond)); var actualDateTime = (DateTime) actualValue; actualDateTime = actualDateTime.AddTicks(-(actualDateTime.Ticks % TimeSpan.TicksPerSecond)); Assert.AreEqual(expectedDateTime.ToString(dateTimeFormat), actualDateTime.ToString(dateTimeFormat), "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue); } else { Assert.AreEqual(expectedValue, actualValue, "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue); } } } private static void AssertListsAreEquals(PropertyInfo property, IEnumerable actualList, IEnumerable expectedList, string dateTimeFormat, Func<IEnumerable, IEnumerable> sorter) { if (sorter == null) { //this is pretty hackerific but saves us some code to write sorter = enumerable => { //semi-generic way of ensuring any collection of IEntity are sorted by Ids for comparison var entities = enumerable.OfType<IEntity>().ToList(); if (entities.Count > 0) { return entities.OrderBy(x => x.Id); } else { return enumerable; } }; } var actualListEx = sorter(actualList).Cast<object>().ToList(); var expectedListEx = sorter(expectedList).Cast<object>().ToList(); if (actualListEx.Count != expectedListEx.Count) Assert.Fail("Collection {0}.{1} does not match. Expected IEnumerable containing {2} elements but was IEnumerable containing {3} elements", property.PropertyType.Name, property.Name, expectedListEx.Count, actualListEx.Count); for (int i = 0; i < actualListEx.Count; i++) { var actualValue = actualListEx[i]; var expectedValue = expectedListEx[i]; if (((actualValue is string) == false) && actualValue is IEnumerable) { AssertListsAreEquals(property, (IEnumerable)actualValue, (IEnumerable)expectedValue, dateTimeFormat, sorter); } else if (dateTimeFormat.IsNullOrWhiteSpace() == false && actualValue is DateTime) { Assert.AreEqual(((DateTime)expectedValue).ToString(dateTimeFormat), ((DateTime)actualValue).ToString(dateTimeFormat), "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue); } else { Assert.AreEqual(expectedValue, actualValue, "Property {0}.{1} does not match. Expected: {2} but was: {3}", property.DeclaringType.Name, property.Name, expectedValue, actualValue); } } } } }
using System; using System.Collections.Generic; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace OrchardCore.Modules { public static class InvokeExtensions { /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them /// </summary> public static void Invoke<TEvents>(this IEnumerable<TEvents> events, Action<TEvents> dispatch, ILogger logger) { foreach (var sink in events) { try { dispatch(sink); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them /// </summary> public static void Invoke<TEvents, T1>(this IEnumerable<TEvents> events, Action<TEvents, T1> dispatch, T1 arg1, ILogger logger) { foreach (var sink in events) { try { dispatch(sink, arg1); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } } public static IEnumerable<TResult> Invoke<TEvents, TResult>(this IEnumerable<TEvents> events, Func<TEvents, TResult> dispatch, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = dispatch(sink); results.Add(result); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } return results; } public static IEnumerable<TResult> Invoke<TEvents, T1, TResult>(this IEnumerable<TEvents> events, Func<TEvents, T1, TResult> dispatch, T1 arg1, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = dispatch(sink, arg1); results.Add(result); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } return results; } public static IEnumerable<TResult> Invoke<TEvents, TResult>(this IEnumerable<TEvents> events, Func<TEvents, IEnumerable<TResult>> dispatch, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = dispatch(sink); results.AddRange(result); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } return results; } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them /// </summary> public static async Task InvokeAsync<TEvents>(this IEnumerable<TEvents> events, Func<TEvents, Task> dispatch, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them /// </summary> public static async Task InvokeAsync<TEvents, T1>(this IEnumerable<TEvents> events, Func<TEvents, T1, Task> dispatch, T1 arg1, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink, arg1); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them /// </summary> public static async Task InvokeAsync<TEvents, T1, T2>(this IEnumerable<TEvents> events, Func<TEvents, T1, T2, Task> dispatch, T1 arg1, T2 arg2, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink, arg1, arg2); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them /// </summary> public static async Task InvokeAsync<TEvents, T1, T2, T3>(this IEnumerable<TEvents> events, Func<TEvents, T1, T2, T3, Task> dispatch, T1 arg1, T2 arg2, T3 arg3, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink, arg1, arg2, arg3); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them /// </summary> public static async Task InvokeAsync<TEvents, T1, T2, T3, T4>(this IEnumerable<TEvents> events, Func<TEvents, T1, T2, T3, T4, Task> dispatch, T1 arg1, T2 arg2, T3 arg3, T4 arg4, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink, arg1, arg2, arg3, arg4); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } } /// <summary> /// Safely invoke methods by catching non fatal exceptions and logging them /// </summary> public static async Task InvokeAsync<TEvents, T1, T2, T3, T4, T5>(this IEnumerable<TEvents> events, Func<TEvents, T1, T2, T3, T4, T5, Task> dispatch, T1 arg1, T2 arg2, T3 arg3, T4 arg4, T5 arg5, ILogger logger) { foreach (var sink in events) { try { await dispatch(sink, arg1, arg2, arg3, arg4, arg5); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } } public static async Task<IEnumerable<TResult>> InvokeAsync<TEvents, TResult>(this IEnumerable<TEvents> events, Func<TEvents, Task<TResult>> dispatch, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = await dispatch(sink); results.Add(result); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } return results; } public static async Task<IEnumerable<TResult>> InvokeAsync<TEvents, T1, TResult>(this IEnumerable<TEvents> events, Func<TEvents, T1, Task<TResult>> dispatch, T1 arg1, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = await dispatch(sink, arg1); results.Add(result); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } return results; } public static async Task<IEnumerable<TResult>> InvokeAsync<TEvents, TResult>(this IEnumerable<TEvents> events, Func<TEvents, Task<IEnumerable<TResult>>> dispatch, ILogger logger) { var results = new List<TResult>(); foreach (var sink in events) { try { var result = await dispatch(sink); results.AddRange(result); } catch (Exception ex) { HandleException(ex, logger, typeof(TEvents).Name, sink.GetType().FullName); } } return results; } public static void HandleException(Exception ex, ILogger logger, string sourceType, string method) { if (IsLogged(ex)) { logger.LogError(ex, "{Type} thrown from {Method} by {Exception}", sourceType, method, ex.GetType().Name); } if (ex.IsFatal()) { throw ex; } } private static bool IsLogged(Exception ex) { return !ex.IsFatal(); } } }
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Collections.Generic; using System.Text; using NDesk.Options; using OpenSim.Framework; using OpenSim.Framework.Console; using OpenSim.Region.Framework.Scenes; namespace OpenSim.Region.ClientStack.LindenUDP { public class LLUDPServerCommands { private ICommandConsole m_console; private LLUDPServer m_udpServer; public LLUDPServerCommands(ICommandConsole console, LLUDPServer udpServer) { m_console = console; m_udpServer = udpServer; } public void Register() { m_console.Commands.AddCommand( "Comms", false, "show server throttles", "show server throttles", "Show information about server throttles", HandleShowServerThrottlesCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp packet", "debug lludp packet [--default | --all] <level> [<avatar-first-name> <avatar-last-name>]", "Turn on packet debugging. This logs information when the client stack hands a processed packet off to downstream code or when upstream code first requests that a certain packet be sent.", "If level > 255 then all incoming and outgoing packets are logged.\n" + "If level <= 255 then incoming AgentUpdate and outgoing SimStats and SimulatorViewerTimeMessage packets are not logged.\n" + "If level <= 200 then incoming RequestImage and outgoing ImagePacket, ImageData, LayerData and CoarseLocationUpdate packets are not logged.\n" + "If level <= 100 then incoming ViewerEffect and AgentAnimation and outgoing ViewerEffect and AvatarAnimation packets are not logged.\n" + "If level <= 50 then outgoing ImprovedTerseObjectUpdate packets are not logged.\n" + "If level <= 0 then no packets are logged.\n" + "If --default is specified then the level becomes the default logging level for all subsequent agents.\n" + "If --all is specified then the level becomes the default logging level for all current and subsequent agents.\n" + "In these cases, you cannot also specify an avatar name.\n" + "If an avatar name is given then only packets from that avatar are logged.", HandlePacketCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp data out", "debug lludp data out <level> <avatar-first-name> <avatar-last-name>\"", "Turn on debugging for final outgoing data to the given user's client.", "This operates at a much lower level than the packet command and prints out available details when the data is actually sent.\n" + "If level > 0 then information about all outgoing UDP data for this avatar is logged.\n" + "If level <= 0 then no information about outgoing UDP data for this avatar is logged.", HandleDataCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp drop", "debug lludp drop <in|out> <add|remove> <packet-name>", "Drop all in or outbound packets that match the given name", "For test purposes.", HandleDropCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp start", "debug lludp start <in|out|all>", "Control LLUDP packet processing.", "No effect if packet processing has already started.\n" + "in - start inbound processing.\n" + "out - start outbound processing.\n" + "all - start in and outbound processing.\n", HandleStartCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp stop", "debug lludp stop <in|out|all>", "Stop LLUDP packet processing.", "No effect if packet processing has already stopped.\n" + "in - stop inbound processing.\n" + "out - stop outbound processing.\n" + "all - stop in and outbound processing.\n", HandleStopCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp pool", "debug lludp pool <on|off>", "Turn object pooling within the lludp component on or off.", HandlePoolCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp status", "debug lludp status", "Return status of LLUDP packet processing.", HandleStatusCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp throttles log", "debug lludp throttles log <level> [<avatar-first-name> <avatar-last-name>]", "Change debug logging level for throttles.", "If level >= 0 then throttle debug logging is performed.\n" + "If level <= 0 then no throttle debug logging is performed.", HandleThrottleCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp throttles get", "debug lludp throttles get [<avatar-first-name> <avatar-last-name>]", "Return debug settings for throttles.", "adaptive - true/false, controls adaptive throttle setting.\n" + "request - request drip rate in kbps.\n" + "max - the max kbps throttle allowed for the specified existing clients. Use 'debug lludp get new-client-throttle-max' to see the setting for new clients.\n", HandleThrottleGetCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp throttles set", "debug lludp throttles set <param> <value> [<avatar-first-name> <avatar-last-name>]", "Set a throttle parameter for the given client.", "adaptive - true/false, controls adaptive throttle setting.\n" + "current - current drip rate in kbps.\n" + "request - requested drip rate in kbps.\n" + "max - the max kbps throttle allowed for the specified existing clients. Use 'debug lludp set new-client-throttle-max' to change the settings for new clients.\n", HandleThrottleSetCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp get", "debug lludp get", "Get debug parameters for the server.", "max-scene-throttle - the current max cumulative kbps provided for this scene to clients.\n" + "max-new-client-throttle - the max kbps throttle allowed to new clients. Use 'debug lludp throttles get max' to see the settings for existing clients.", HandleGetCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp set", "debug lludp set <param> <value>", "Set a parameter for the server.", "max-scene-throttle - the current max cumulative kbps provided for this scene to clients.\n" + "max-new-client-throttle - the max kbps throttle allowed to each new client. Use 'debug lludp throttles set max' to set for existing clients.", HandleSetCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp toggle agentupdate", "debug lludp toggle agentupdate", "Toggle whether agentupdate packets are processed or simply discarded.", HandleAgentUpdateCommand); MainConsole.Instance.Commands.AddCommand( "Debug", false, "debug lludp oqre", "debug lludp oqre <start|stop|status>", "Start, stop or get status of OutgoingQueueRefillEngine.", "If stopped then refill requests are processed directly via the threadpool.", HandleOqreCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp client get", "debug lludp client get [<avatar-first-name> <avatar-last-name>]", "Get debug parameters for the client. If no name is given then all client information is returned.", "process-unacked-sends - Do we take action if a sent reliable packet has not been acked.", HandleClientGetCommand); m_console.Commands.AddCommand( "Debug", false, "debug lludp client set", "debug lludp client set <param> <value> [<avatar-first-name> <avatar-last-name>]", "Set a debug parameter for a particular client. If no name is given then the value is set on all clients.", "process-unacked-sends - Do we take action if a sent reliable packet has not been acked.", HandleClientSetCommand); } private void HandleShowServerThrottlesCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; m_console.OutputFormat("Throttles for {0}", m_udpServer.Scene.Name); ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("Adaptive throttles", m_udpServer.ThrottleRates.AdaptiveThrottlesEnabled); long maxSceneDripRate = m_udpServer.Throttle.MaxDripRate; cdl.AddRow( "Max scene throttle", maxSceneDripRate != 0 ? string.Format("{0} kbps", maxSceneDripRate * 8 / 1000) : "unset"); int maxClientDripRate = m_udpServer.ThrottleRates.Total; cdl.AddRow( "Max new client throttle", maxClientDripRate != 0 ? string.Format("{0} kbps", maxClientDripRate * 8 / 1000) : "unset"); m_console.Output(cdl.ToString()); m_console.OutputFormat("{0}\n", GetServerThrottlesReport(m_udpServer)); } private string GetServerThrottlesReport(LLUDPServer udpServer) { StringBuilder report = new StringBuilder(); report.AppendFormat( "{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}\n", "Total", "Resend", "Land", "Wind", "Cloud", "Task", "Texture", "Asset"); report.AppendFormat( "{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}\n", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s", "kb/s"); ThrottleRates throttleRates = udpServer.ThrottleRates; report.AppendFormat( "{0,7} {1,8} {2,7} {3,7} {4,7} {5,7} {6,9} {7,7}", (throttleRates.Total * 8) / 1000, (throttleRates.Resend * 8) / 1000, (throttleRates.Land * 8) / 1000, (throttleRates.Wind * 8) / 1000, (throttleRates.Cloud * 8) / 1000, (throttleRates.Task * 8) / 1000, (throttleRates.Texture * 8) / 1000, (throttleRates.Asset * 8) / 1000); return report.ToString(); } protected string GetColumnEntry(string entry, int maxLength, int columnPadding) { return string.Format( "{0,-" + maxLength + "}{1,-" + columnPadding + "}", entry.Length > maxLength ? entry.Substring(0, maxLength) : entry, ""); } private void HandleDataCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 7) { MainConsole.Instance.OutputFormat("Usage: debug lludp data out <true|false> <avatar-first-name> <avatar-last-name>"); return; } int level; if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out level)) return; string firstName = args[5]; string lastName = args[6]; m_udpServer.Scene.ForEachScenePresence(sp => { if (sp.Firstname == firstName && sp.Lastname == lastName) { MainConsole.Instance.OutputFormat( "Data debug for {0} ({1}) set to {2} in {3}", sp.Name, sp.IsChildAgent ? "child" : "root", level, m_udpServer.Scene.Name); ((LLClientView)sp.ControllingClient).UDPClient.DebugDataOutLevel = level; } }); } private void HandleThrottleCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; bool all = args.Length == 5; bool one = args.Length == 7; if (!all && !one) { MainConsole.Instance.OutputFormat( "Usage: debug lludp throttles log <level> [<avatar-first-name> <avatar-last-name>]"); return; } int level; if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, args[4], out level)) return; string firstName = null; string lastName = null; if (one) { firstName = args[5]; lastName = args[6]; } m_udpServer.Scene.ForEachScenePresence(sp => { if (all || (sp.Firstname == firstName && sp.Lastname == lastName)) { MainConsole.Instance.OutputFormat( "Throttle log level for {0} ({1}) set to {2} in {3}", sp.Name, sp.IsChildAgent ? "child" : "root", level, m_udpServer.Scene.Name); ((LLClientView)sp.ControllingClient).UDPClient.ThrottleDebugLevel = level; } }); } private void HandleThrottleSetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; bool all = args.Length == 6; bool one = args.Length == 8; if (!all && !one) { MainConsole.Instance.OutputFormat( "Usage: debug lludp throttles set <param> <value> [<avatar-first-name> <avatar-last-name>]"); return; } string param = args[4]; string rawValue = args[5]; string firstName = null; string lastName = null; if (one) { firstName = args[6]; lastName = args[7]; } if (param == "adaptive") { bool newValue; if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newValue)) return; m_udpServer.Scene.ForEachScenePresence(sp => { if (all || (sp.Firstname == firstName && sp.Lastname == lastName)) { MainConsole.Instance.OutputFormat( "Setting param {0} to {1} for {2} ({3}) in {4}", param, newValue, sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name); LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; udpClient.FlowThrottle.AdaptiveEnabled = newValue; // udpClient.FlowThrottle.MaxDripRate = 0; // udpClient.FlowThrottle.AdjustedDripRate = 0; } }); } else if (param == "request") { int newValue; if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, rawValue, out newValue)) return; int newCurrentThrottleKbps = newValue * 1000 / 8; m_udpServer.Scene.ForEachScenePresence(sp => { if (all || (sp.Firstname == firstName && sp.Lastname == lastName)) { MainConsole.Instance.OutputFormat( "Setting param {0} to {1} for {2} ({3}) in {4}", param, newValue, sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name); LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; udpClient.FlowThrottle.RequestedDripRate = newCurrentThrottleKbps; } }); } else if (param == "max") { int newValue; if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, rawValue, out newValue)) return; int newThrottleMaxKbps = newValue * 1000 / 8; m_udpServer.Scene.ForEachScenePresence(sp => { if (all || (sp.Firstname == firstName && sp.Lastname == lastName)) { MainConsole.Instance.OutputFormat( "Setting param {0} to {1} for {2} ({3}) in {4}", param, newValue, sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name); LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; udpClient.FlowThrottle.MaxDripRate = newThrottleMaxKbps; } }); } } private void HandleThrottleGetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; bool all = args.Length == 4; bool one = args.Length == 6; if (!all && !one) { MainConsole.Instance.OutputFormat( "Usage: debug lludp throttles get [<avatar-first-name> <avatar-last-name>]"); return; } string firstName = null; string lastName = null; if (one) { firstName = args[4]; lastName = args[5]; } m_udpServer.Scene.ForEachScenePresence(sp => { if (all || (sp.Firstname == firstName && sp.Lastname == lastName)) { m_console.OutputFormat( "Status for {0} ({1}) in {2}", sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name); LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("adaptive", udpClient.FlowThrottle.AdaptiveEnabled); cdl.AddRow("current", string.Format("{0} kbps", udpClient.FlowThrottle.DripRate * 8 / 1000)); cdl.AddRow("request", string.Format("{0} kbps", udpClient.FlowThrottle.RequestedDripRate * 8 / 1000)); cdl.AddRow("max", string.Format("{0} kbps", udpClient.FlowThrottle.MaxDripRate * 8 / 1000)); m_console.Output(cdl.ToString()); } }); } private void HandleGetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; m_console.OutputFormat("Debug settings for {0}", m_udpServer.Scene.Name); ConsoleDisplayList cdl = new ConsoleDisplayList(); long maxSceneDripRate = m_udpServer.Throttle.MaxDripRate; cdl.AddRow( "max-scene-throttle", maxSceneDripRate != 0 ? string.Format("{0} kbps", maxSceneDripRate * 8 / 1000) : "unset"); int maxClientDripRate = m_udpServer.ThrottleRates.Total; cdl.AddRow( "max-new-client-throttle", maxClientDripRate != 0 ? string.Format("{0} kbps", maxClientDripRate * 8 / 1000) : "unset"); m_console.Output(cdl.ToString()); } private void HandleSetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 5) { MainConsole.Instance.OutputFormat("Usage: debug lludp set <param> <value>"); return; } string param = args[3]; string rawValue = args[4]; int newValue; if (param == "max-scene-throttle") { if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, rawValue, out newValue)) return; m_udpServer.Throttle.MaxDripRate = newValue * 1000 / 8; } else if (param == "max-new-client-throttle") { if (!ConsoleUtil.TryParseConsoleInt(MainConsole.Instance, rawValue, out newValue)) return; m_udpServer.ThrottleRates.Total = newValue * 1000 / 8; } else { return; } m_console.OutputFormat("{0} set to {1} in {2}", param, rawValue, m_udpServer.Scene.Name); } private void HandleClientGetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 4 && args.Length != 6) { MainConsole.Instance.OutputFormat("Usage: debug lludp client get [<avatar-first-name> <avatar-last-name>]"); return; } string name = null; if (args.Length == 6) name = string.Format("{0} {1}", args[4], args[5]); m_udpServer.Scene.ForEachScenePresence( sp => { if ((name == null || sp.Name == name) && sp.ControllingClient is LLClientView) { LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; m_console.OutputFormat( "Client debug parameters for {0} ({1}) in {2}", sp.Name, sp.IsChildAgent ? "child" : "root", m_udpServer.Scene.Name); ConsoleDisplayList cdl = new ConsoleDisplayList(); cdl.AddRow("process-unacked-sends", udpClient.ProcessUnackedSends); m_console.Output(cdl.ToString()); } }); } private void HandleClientSetCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 6 && args.Length != 8) { MainConsole.Instance.OutputFormat("Usage: debug lludp client set <param> <value> [<avatar-first-name> <avatar-last-name>]"); return; } string param = args[4]; string rawValue = args[5]; string name = null; if (args.Length == 8) name = string.Format("{0} {1}", args[6], args[7]); if (param == "process-unacked-sends") { bool newValue; if (!ConsoleUtil.TryParseConsoleBool(MainConsole.Instance, rawValue, out newValue)) return; m_udpServer.Scene.ForEachScenePresence( sp => { if ((name == null || sp.Name == name) && sp.ControllingClient is LLClientView) { LLUDPClient udpClient = ((LLClientView)sp.ControllingClient).UDPClient; udpClient.ProcessUnackedSends = newValue; m_console.OutputFormat("{0} set to {1} for {2} in {3}", param, newValue, sp.Name, m_udpServer.Scene.Name); } }); } } private void HandlePacketCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; bool setAsDefaultLevel = false; bool setAll = false; OptionSet optionSet = new OptionSet() .Add("default", o => setAsDefaultLevel = (o != null)) .Add("all", o => setAll = (o != null)); List<string> filteredArgs = optionSet.Parse(args); string name = null; if (filteredArgs.Count == 6) { if (!(setAsDefaultLevel || setAll)) { name = string.Format("{0} {1}", filteredArgs[4], filteredArgs[5]); } else { MainConsole.Instance.OutputFormat("ERROR: Cannot specify a user name when setting default/all logging level"); return; } } if (filteredArgs.Count > 3) { int newDebug; if (int.TryParse(filteredArgs[3], out newDebug)) { if (setAsDefaultLevel || setAll) { m_udpServer.DefaultClientPacketDebugLevel = newDebug; MainConsole.Instance.OutputFormat( "Packet debug for {0} clients set to {1} in {2}", (setAll ? "all" : "future"), m_udpServer.DefaultClientPacketDebugLevel, m_udpServer.Scene.Name); if (setAll) { m_udpServer.Scene.ForEachScenePresence(sp => { MainConsole.Instance.OutputFormat( "Packet debug for {0} ({1}) set to {2} in {3}", sp.Name, sp.IsChildAgent ? "child" : "root", newDebug, m_udpServer.Scene.Name); sp.ControllingClient.DebugPacketLevel = newDebug; }); } } else { m_udpServer.Scene.ForEachScenePresence(sp => { if (name == null || sp.Name == name) { MainConsole.Instance.OutputFormat( "Packet debug for {0} ({1}) set to {2} in {3}", sp.Name, sp.IsChildAgent ? "child" : "root", newDebug, m_udpServer.Scene.Name); sp.ControllingClient.DebugPacketLevel = newDebug; } }); } } else { MainConsole.Instance.Output("Usage: debug lludp packet [--default | --all] 0..255 [<first-name> <last-name>]"); } } } private void HandleDropCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 6) { MainConsole.Instance.Output("Usage: debug lludp drop <in|out> <add|remove> <packet-name>"); return; } string direction = args[3]; string subCommand = args[4]; string packetName = args[5]; if (subCommand == "add") { MainConsole.Instance.OutputFormat( "Adding packet {0} to {1} drop list for all connections in {2}", direction, packetName, m_udpServer.Scene.Name); m_udpServer.Scene.ForEachScenePresence( sp => { LLClientView llcv = (LLClientView)sp.ControllingClient; if (direction == "in") llcv.AddInPacketToDropSet(packetName); else if (direction == "out") llcv.AddOutPacketToDropSet(packetName); } ); } else if (subCommand == "remove") { MainConsole.Instance.OutputFormat( "Removing packet {0} from {1} drop list for all connections in {2}", direction, packetName, m_udpServer.Scene.Name); m_udpServer.Scene.ForEachScenePresence( sp => { LLClientView llcv = (LLClientView)sp.ControllingClient; if (direction == "in") llcv.RemoveInPacketFromDropSet(packetName); else if (direction == "out") llcv.RemoveOutPacketFromDropSet(packetName); } ); } } private void HandleStartCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 4) { MainConsole.Instance.Output("Usage: debug lludp start <in|out|all>"); return; } string subCommand = args[3]; if (subCommand == "in" || subCommand == "all") m_udpServer.StartInbound(); if (subCommand == "out" || subCommand == "all") m_udpServer.StartOutbound(); } private void HandleStopCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 4) { MainConsole.Instance.Output("Usage: debug lludp stop <in|out|all>"); return; } string subCommand = args[3]; if (subCommand == "in" || subCommand == "all") m_udpServer.StopInbound(); if (subCommand == "out" || subCommand == "all") m_udpServer.StopOutbound(); } private void HandlePoolCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 4) { MainConsole.Instance.Output("Usage: debug lludp pool <on|off>"); return; } string enabled = args[3]; if (enabled == "on") { if (m_udpServer.EnablePools()) { m_udpServer.EnablePoolStats(); MainConsole.Instance.OutputFormat("Packet pools enabled on {0}", m_udpServer.Scene.Name); } } else if (enabled == "off") { if (m_udpServer.DisablePools()) { m_udpServer.DisablePoolStats(); MainConsole.Instance.OutputFormat("Packet pools disabled on {0}", m_udpServer.Scene.Name); } } else { MainConsole.Instance.Output("Usage: debug lludp pool <on|off>"); } } private void HandleAgentUpdateCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; m_udpServer.DiscardInboundAgentUpdates = !m_udpServer.DiscardInboundAgentUpdates; MainConsole.Instance.OutputFormat( "Discard AgentUpdates now {0} for {1}", m_udpServer.DiscardInboundAgentUpdates, m_udpServer.Scene.Name); } private void HandleStatusCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; MainConsole.Instance.OutputFormat( "IN LLUDP packet processing for {0} is {1}", m_udpServer.Scene.Name, m_udpServer.IsRunningInbound ? "enabled" : "disabled"); MainConsole.Instance.OutputFormat( "OUT LLUDP packet processing for {0} is {1}", m_udpServer.Scene.Name, m_udpServer.IsRunningOutbound ? "enabled" : "disabled"); MainConsole.Instance.OutputFormat("LLUDP pools in {0} are {1}", m_udpServer.Scene.Name, m_udpServer.UsePools ? "on" : "off"); MainConsole.Instance.OutputFormat( "Packet debug level for new clients is {0}", m_udpServer.DefaultClientPacketDebugLevel); } private void HandleOqreCommand(string module, string[] args) { if (SceneManager.Instance.CurrentScene != null && SceneManager.Instance.CurrentScene != m_udpServer.Scene) return; if (args.Length != 4) { MainConsole.Instance.Output("Usage: debug lludp oqre <stop|start|status>"); return; } string subCommand = args[3]; if (subCommand == "stop") { m_udpServer.OqrEngine.Stop(); MainConsole.Instance.OutputFormat("Stopped OQRE for {0}", m_udpServer.Scene.Name); } else if (subCommand == "start") { m_udpServer.OqrEngine.Start(); MainConsole.Instance.OutputFormat("Started OQRE for {0}", m_udpServer.Scene.Name); } else if (subCommand == "status") { MainConsole.Instance.OutputFormat("OQRE in {0}", m_udpServer.Scene.Name); MainConsole.Instance.OutputFormat("Running: {0}", m_udpServer.OqrEngine.IsRunning); MainConsole.Instance.OutputFormat( "Requests waiting: {0}", m_udpServer.OqrEngine.IsRunning ? m_udpServer.OqrEngine.JobsWaiting.ToString() : "n/a"); } else { MainConsole.Instance.OutputFormat("Unrecognized OQRE subcommand {0}", subCommand); } } } }
using System; using NUnit.Framework; using ProtoCore.DSASM.Mirror; using ProtoTestFx.TD; namespace ProtoTest.TD.Associative { class Function { public TestFrameWork thisTest = new TestFrameWork(); string filePath = "..\\..\\..\\Scripts\\TD\\Associative\\Function\\"; [SetUp] public void Setup() { } [Test] [Category("SmokeTest")] public void T001_Associative_Function_Simple() { string code = @" a; b; sum; [Associative] { def Sum : int(a : int, b : int) { return = a + b; } a = 1; b = 10; sum = Sum (a, b); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); Assert.IsTrue((Int64)mirror.GetValue("a").Payload == 1); Assert.IsTrue((Int64)mirror.GetValue("b").Payload == 10); Assert.IsTrue((Int64)mirror.GetValue("sum").Payload == 11); } [Test] //Function does not accept single line function / Direct Assignment [Category("SmokeTest")] public void T002_Associative_Function_SinglelineFunction() { string code = @" d; [Associative] { def singleLine : int(a:int, b:int) = 10; d = singleLine(1,3); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); Assert.IsTrue((Int64)mirror.GetValue("d").Payload == 10); } [Test] [Category("SmokeTest")] public void T003_Associative_Function_MultilineFunction() { string code = @" [Associative] { def Divide : int(a:int, b:int) { return = a/b; } d = Divide (1,3); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); Assert.IsTrue(Convert.ToInt64(mirror.GetValue("d").Payload) == 0); } [Test] [Category("SmokeTest")] public void T004_Associative_Function_SpecifyReturnType() { string code = @" d; [Associative] { def Divide : double (a:int, b:int) { return = a/b; } d = Divide (1,3); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); thisTest.Verify("d", 0.33333333333333333); } [Test] [Category("Type System")] public void T005_Associative_Function_SpecifyArgumentType() { string code = @" result; [Associative] { def myFunction : int (a:int, b:int) { return = a + b; } d1 = 1.12; d2 = 0.5; result = myFunction (d1, d2); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); thisTest.Verify("result", 2); } [Test] //Function takes null as argument [Category("SmokeTest")] public void T006_Associative_Function_PassingNullAsArgument() { string code = @" [Associative] { def myFunction : double (a: double, b: double) { return = a + b; } d1 = null; d2 = 0.5; result = myFunction (d1, d2); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); //Assert.IsTrue((Double)mirror.GetValue("d").Payload == 0); } [Test] [Category("SmokeTest")] public void T007_Associative_Function_NestedFunction() { string code = @" result; [Associative] { def ChildFunction : double (r1 : double) { return = r1; } def ParentFunction : double (r1 : double) { return = ChildFunction (r1)*2; } d1 = 1.05; result = ParentFunction (d1); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); Assert.IsTrue((Double)mirror.GetValue("result").Payload == 2.1); } [Test] //Function does not work if the argument variable is declared before function declaration [Category("SmokeTest")] public void T008_Associative_Function_DeclareVariableBeforeFunctionDeclaration() { string code = @" sum; [Associative] { a = 1; b = 10; def Sum : int(a : int, b : int) { return = a + b; } sum = Sum (a, b); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); Assert.IsTrue((Int64)mirror.GetValue("sum").Payload == 11); } [Test] [Category("SmokeTest")] public void T009_Associative_Function_DeclareVariableInsideFunction() { string code = @" [Associative] { def Foo : int(input : int) { multiply = 5; divide = 10; return = {input*multiply, input/divide}; } input = 20; sum = Foo (input); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); //Verifiction should be done after collection is ready. } [Test] [Category("SmokeTest")] public void T010_Associative_Function_PassAndReturnBooleanValue() { string code = @" result1; result2; [Associative] { def Foo : bool (input : bool) { return = input; } input = false; result1 = Foo (input); result2 = Foo (true); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); Assert.IsTrue(System.Convert.ToBoolean(mirror.GetValue("result1").Payload) == false); Assert.IsTrue(System.Convert.ToBoolean(mirror.GetValue("result2").Payload)); } [Test] [Category("SmokeTest")] public void T011_Associative_Function_FunctionWithoutArgument() { string code = @" result1; [Associative] { def Foo1 : int () { return = 5; } result1 = Foo1 (); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); Assert.IsTrue((Int64)mirror.GetValue("result1").Payload == 5); } [Test] [Category("SmokeTest")] public void T012_Associative_Function_MultipleFunctions() { string code = @" result1; result2; [Associative] { def Foo1 : int () { return = 5; } def Foo2 : int () { return = 6; } result1 = Foo1 (); result2 = Foo2 (); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); Assert.IsTrue((Int64)mirror.GetValue("result1").Payload == 5); Assert.IsTrue((Int64)mirror.GetValue("result2").Payload == 6); } [Test] [Category("SmokeTest")] public void T013_Associative_Function_FunctionWithSameName_Negative() { string code = @" [Associative] { def Foo1 : int () { return = 5; } def Foo1 : int () { return = 6; } result2 = Foo2 (); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); } [Test] //Should return compilation error if a variable has the same name as a function? [Category("SmokeTest")] public void T014_Associative_Function_DuplicateVariableAndFunctionName_Negative() { Assert.Throws(typeof(ProtoCore.Exceptions.CompileErrorsOccured), () => { string code = @" [Associative] { def Foo : int () { return = 4; } Foo = 5; }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); }); } [Test] //Incorrect error message when the argument number is not matching with function declaration. [Category("SmokeTest")] public void T015_Associative_Function_UnmatchFunctionArgument_Negative() { string code = @" [Associative] { def Foo : int (a : int) { return = 5; } result = Foo(1,2); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); } [Test] [Category("SmokeTest")] public void T016_Associative_Function_ModifyArgumentInsideFunctionDoesNotAffectItsValue() { string code = @" input; result; originalInput; [Associative] { def Foo : int (a : int) { a = a + 1; return = a; } input = 3; result = Foo(input); originalInput = input; }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); Assert.IsTrue((Int64)mirror.GetValue("input").Payload == 3); Assert.IsTrue((Int64)mirror.GetValue("result").Payload == 4); Assert.IsTrue((Int64)mirror.GetValue("originalInput").Payload == 3); } [Test] //Calling a function before its declaration causes compilation failure [Category("SmokeTest")] public void T017_Associative_Function_CallingAFunctionBeforeItsDeclaration() { string code = @" input; result; [Associative] { def Level1 : int (a : int) { return = Level2(a+1); } def Level2 : int (a : int) { return = a + 1; } input = 3; result = Level1(input); }"; ExecutionMirror mirror = thisTest.RunScriptSource(code); Assert.IsTrue((Int64)mirror.GetValue("input").Payload == 3); Assert.IsTrue((Int64)mirror.GetValue("result").Payload == 5); } [Test] [Category("SmokeTest")] public void Z001_Associative_Function_Regress_1454696() { string src = @" def Twice : double(array : double[]) { return = array[0]; } arr = {1.0,2.0,3.0}; arr2 = Twice(arr);"; ExecutionMirror mirror = thisTest.RunScriptSource(src); thisTest.Verify("arr2", 1.0); } [Test] [Category("SmokeTest")] public void Z002_Defect_1461399() { string src = @"class Arc { constructor Arc() { } def get_StartPoint() { return = 1; } } def CurveProperties(curve : Arc) { return = { curve.get_StartPoint(), curve.get_StartPoint(), curve.get_StartPoint() }; } test=CurveProperties(null); "; ExecutionMirror mirror = thisTest.RunScriptSource(src); Object[] v1 = new Object[] { null, null, null }; thisTest.Verify("test", v1); } [Test] [Category("SmokeTest")] public void Z002_Defect_1461399_2() { string src = @"class Arc { constructor Arc() { } def get_StartPoint() { return = 1; } } def CurveProperties(curve : Arc) { return = { curve[0].get_StartPoint(), curve[0].get_StartPoint(), curve[0].get_StartPoint() }; } test=CurveProperties(null); "; ExecutionMirror mirror = thisTest.RunScriptSource(src); Object[] v1 = new Object[] { null, null, null }; thisTest.Verify("test", v1); } [Test] [Category("SmokeTest")] public void Z003_Defect_1456728() { string src = @"def function1 (arr : double[] ) { return = { arr[0], arr [1] }; } a = function1({null,null}); "; ExecutionMirror mirror = thisTest.RunScriptSource(src); Object[] v1 = { null, null }; thisTest.Verify("a", v1); } } }
// 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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.UseNullPropagation; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.UseNullPropagation { public partial class UseNullPropagationTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpUseNullPropagationDiagnosticAnalyzer(), new CSharpUseNullPropagationCodeFixProvider()); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestLeft_Equals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||]o == null ? null : o.ToString(); } }", @"using System; class C { void M(object o) { var v = o?.ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestMissingOnCSharp5() { await TestMissingAsync( @"using System; class C { void M(object o) { var v = [||]o == null ? null : o.ToString(); } }", new TestParameters(parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestRight_Equals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||]null == o ? null : o.ToString(); } }", @"using System; class C { void M(object o) { var v = o?.ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestLeft_NotEquals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||]o != null ? o.ToString() : null; } }", @"using System; class C { void M(object o) { var v = o?.ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestRight_NotEquals() { await TestInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||]null != o ? o.ToString() : null; } }", @"using System; class C { void M(object o) { var v = o?.ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestIndexer() { await TestInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||]o == null ? null : o[0]; } }", @"using System; class C { void M(object o) { var v = o?[0]; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestConditionalAccess() { await TestInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||]o == null ? null : o.B?.C; } }", @"using System; class C { void M(object o) { var v = o?.B?.C; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestMemberAccess() { await TestInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||]o == null ? null : o.B; } }", @"using System; class C { void M(object o) { var v = o?.B; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestMissingOnSimpleMatch() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||]o == null ? null : o; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestParenthesizedCondition() { await TestInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||](o == null) ? null : o.ToString(); } }", @"using System; class C { void M(object o) { var v = o?.ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestFixAll1() { await TestInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v1 = {|FixAllInDocument:o|} == null ? null : o.ToString(); var v2 = o != null ? o.ToString() : null; } }", @"using System; class C { void M(object o) { var v1 = o?.ToString(); var v2 = o?.ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestFixAll2() { await TestInRegularAndScriptAsync( @"using System; class C { void M(object o1, object o2) { var v1 = {|FixAllInDocument:o1|} == null ? null : o1.ToString(o2 == null ? null : o2.ToString()); } }", @"using System; class C { void M(object o1, object o2) { var v1 = o1?.ToString(o2?.ToString()); } }"); } [WorkItem(15505, "https://github.com/dotnet/roslyn/issues/15505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestOtherValueIsNotNull1() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||]o == null ? 0 : o.ToString(); } }"); } [WorkItem(15505, "https://github.com/dotnet/roslyn/issues/15505")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestOtherValueIsNotNull2() { await TestMissingInRegularAndScriptAsync( @"using System; class C { void M(object o) { var v = [||]o != null ? o.ToString() : 0; } }"); } [WorkItem(16287, "https://github.com/dotnet/roslyn/issues/16287")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestMethodGroup() { await TestMissingInRegularAndScriptAsync( @" using System; class D { void Foo() { var c = new C(); Action<string> a = [||]c != null ? c.M : (Action<string>)null; } } class C { public void M(string s) { } }"); } [WorkItem(17623, "https://github.com/dotnet/roslyn/issues/17623")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsUseNullPropagation)] public async Task TestInExpressionTree() { await TestMissingInRegularAndScriptAsync( @" using System; using System.Linq.Expressions; class Program { void Main(string s) { Method<string>(t => [||]s != null ? s.ToString() : null); // works } public void Method<T>(Expression<Func<T, string>> functor) { } }"); } } }
using UnityEngine; using Unity.Data; using Unity.GuiStyle; using Unity.Function.Graphic; using System; using System.Collections.Generic; using System.IO; using System.Threading; using Monoamp.Common.Component.Sound.Player; using Monoamp.Common.Data.Application.Music; using Monoamp.Common.Data.Application.Sound; using Monoamp.Common.Data.Standard.Riff.Wave; using Monoamp.Common.Utility; using Monoamp.Common.Struct; using Monoamp.Boundary; namespace Unity.View { public class ComponentPlayer : IView { private IPlayer player; private string title; private bool mouseButton; public delegate void ChangeMusicPrevious(); public delegate void ChangeMusicNext(); public ChangeMusicPrevious changeMusicPrevious; public ChangeMusicNext changeMusicNext; public Rect Rect{ get; set; } private int positionInBuffer; public ComponentPlayer( ChangeMusicPrevious aChangeMusicPrevious, ChangeMusicNext aChangeMusicNext ) { mouseButton = false; title = ""; player = new PlayerNull(); changeMusicPrevious = aChangeMusicPrevious; changeMusicNext = aChangeMusicNext; positionInBuffer = 0; } public void SetPlayer( string aFilePath ) { bool lIsMute = player.IsMute; bool lIsLoop = player.IsLoop; float lVolume = player.Volume; title = Path.GetFileNameWithoutExtension( aFilePath ); player = ConstructorCollection.ConstructPlayer( aFilePath ); player.IsMute = lIsMute; player.IsLoop = lIsLoop; player.Volume = lVolume; } public void Awake() { } public void Start() { } public void Update() { } public void OnGUI() { mouseButton = Input.GetMouseButton( 0 ); GUILayout.BeginVertical( GuiStyleSet.StylePlayer.box ); { GUILayout.TextArea( title, GuiStyleSet.StylePlayer.labelTitle ); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); GUILayout.Label( new GUIContent( player.GetTPosition().MMSS, "StylePlayer.LabelTime" ), GuiStyleSet.StylePlayer.labelTime ); float lPositionFloat = ( float )player.PositionRate; float lPositionAfter = GUILayout.HorizontalSlider( lPositionFloat, 0.0f, 1.0f, GuiStyleSet.StylePlayer.seekbar, GuiStyleSet.StylePlayer.seekbarThumb ); if( lPositionAfter != lPositionFloat ) { player.PositionRate = lPositionAfter; } GUILayout.Label( new GUIContent( player.GetLength().MMSS, "StylePlayer.LabelTime" ), GuiStyleSet.StylePlayer.labelTime ); GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); if( GUILayout.Button( new GUIContent( "", "StylePlayer.ButtonPrevious" ), GuiStyleSet.StylePlayer.buttonPrevious ) == true ) { changeMusicPrevious(); } bool lIsPlaying = GUILayout.Toggle( player.GetFlagPlaying(), new GUIContent( "", "StylePlayer.ToggleStartPause" ), GuiStyleSet.StylePlayer.toggleStartPause ); if( lIsPlaying != player.GetFlagPlaying() ) { if( lIsPlaying == true ) { player.Play(); } else { player.Pause(); } } if( GUILayout.Button( new GUIContent( "", "StylePlayer.ButtonNext" ), GuiStyleSet.StylePlayer.buttonNext ) == true ) { changeMusicNext(); } GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); GUILayout.BeginHorizontal(); { GUILayout.FlexibleSpace(); player.IsMute = GUILayout.Toggle( player.IsMute, new GUIContent( "", "StylePlayer.ToggleMute" ), GuiStyleSet.StylePlayer.toggleMute ); if( player.IsMute == false ) { player.Volume = GUILayout.HorizontalSlider( player.Volume, 0.0f, 1.0f, GuiStyleSet.StylePlayer.volumebar, GuiStyleSet.StyleSlider.horizontalbarThumb ); if( player.Volume == 0.0f ) { player.IsMute = true; } } else // isMute == true { float lVolume = GUILayout.HorizontalSlider( 0.0f, 0.0f, 1.0f, GuiStyleSet.StylePlayer.volumebar, GuiStyleSet.StyleSlider.horizontalbarThumb ); if( lVolume != 0.0f ) { player.IsMute = false; player.Volume = lVolume; } } GUILayout.FlexibleSpace(); } GUILayout.EndHorizontal(); } GUILayout.EndVertical(); float lHeightTitle = GuiStyleSet.StylePlayer.labelTitle.CalcSize( new GUIContent( title ) ).y; float lY = Rect.y + lHeightTitle + GuiStyleSet.StyleGeneral.box.margin.top + GuiStyleSet.StyleGeneral.box.padding.top + GuiStyleSet.StylePlayer.seekbar.fixedHeight; player.IsLoop = GUI.Toggle( new Rect( Screen.width / 2.0f - GuiStyleSet.StylePlayer.seekbar.fixedWidth / 2.0f, lY, 32.0f, 32.0f ), player.IsLoop, new GUIContent( "", "StylePlayer.ToggleLoop" ), GuiStyleSet.StylePlayer.toggleLoop ); } public void OnRenderObject() { float lHeightTitle = GuiStyleSet.StylePlayer.labelTitle.CalcSize( new GUIContent( title ) ).y + GuiStyleSet.StylePlayer.labelTitle.margin.top + GuiStyleSet.StylePlayer.labelTitle.margin.bottom; float lY = Rect.y + lHeightTitle; if( player != null && player.GetLength().Second != 0.0d ) { float lWidth = GuiStyleSet.StylePlayer.seekbar.fixedWidth; float lHeight = GuiStyleSet.StylePlayer.seekbar.fixedHeight; Gui.DrawSeekBar( new Rect( Screen.width / 2 - lWidth / 2, lY, lWidth, lHeight ), GuiStyleSet.StylePlayer.seekbarImage, ( float )( player.Loop.start / player.GetLength() ), ( float )( player.Loop.end / player.GetLength() ), ( float )player.PositionRate ); } else { float lWidth = GuiStyleSet.StylePlayer.seekbar.fixedWidth; float lHeight = GuiStyleSet.StylePlayer.seekbar.fixedHeight; Gui.DrawSeekBar( new Rect( Screen.width / 2 - lWidth / 2, lY, lWidth, lHeight ), GuiStyleSet.StylePlayer.seekbarImage, 0.0f, 0.0f, 0.0f ); } float lYVolume = Rect.y + lHeightTitle + GuiStyleSet.StylePlayer.toggleStartPause.fixedHeight + GuiStyleSet.StylePlayer.seekbar.fixedHeight + 18; float lWidthVolume = GuiStyleSet.StylePlayer.volumebarImage.fixedWidth; float lHeightVolume = GuiStyleSet.StylePlayer.volumebarImage.fixedHeight; Gui.DrawVolumeBar( new Rect( Screen.width / 2 - lWidthVolume / 2, lYVolume, lWidthVolume, lHeightVolume ), GuiStyleSet.StylePlayer.volumebarImage, player.Volume ); } public void OnAudioFilterRead( float[] aSoundBuffer, int aChannels, int aSampleRate ) { positionInBuffer = player.Update( aSoundBuffer, aChannels, aSampleRate, positionInBuffer ); int lLength = aSoundBuffer.Length / aChannels; if( positionInBuffer != lLength && mouseButton == false ) { changeMusicNext(); positionInBuffer = player.Update( aSoundBuffer, aChannels, aSampleRate, positionInBuffer ); } positionInBuffer %= lLength; } public void OnApplicationQuit() { } public string GetFilePath() { return player.GetFilePath(); } public bool GetIsLoop() { return player.IsLoop; } public void SetIsLoop( bool aIsLoop ) { player.IsLoop = aIsLoop; } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. using Microsoft.Azure.Management.Compute; using Microsoft.Azure.Management.Compute.Models; using Microsoft.Rest.ClientRuntime.Azure.TestFramework; using System; using System.Linq; using System.Net; using Xunit; namespace Compute.Tests { public class VMImagesTests { [Fact] public void TestVMImageGet() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); string[] availableWindowsServerImageVersions = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter").Select(t => t.Name).ToArray(); var vmimage = _pirClient.VirtualMachineImages.Get( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", availableWindowsServerImageVersions[0]); Assert.Equal(availableWindowsServerImageVersions[0], vmimage.Name); Assert.Equal(ComputeManagementTestUtilities.DefaultLocation, vmimage.Location, StringComparer.OrdinalIgnoreCase); // FIXME: This doesn't work with a real Windows Server images, which is what's in the query parameters. // Bug 4196378 /* Assert.True(vmimage.VirtualMachineImage.PurchasePlan.Name == "name"); Assert.True(vmimage.VirtualMachineImage.PurchasePlan.Publisher == "publisher"); Assert.True(vmimage.VirtualMachineImage.PurchasePlan.Product == "product"); */ Assert.Equal(OperatingSystemTypes.Windows, vmimage.OsDiskImage.OperatingSystem); //Assert.True(vmimage.VirtualMachineImage.DataDiskImages.Count(ddi => ddi.Lun == 123456789) != 0); } } [Fact] public void TestVMImageAutomaticOSUpgradeProperties() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // Validate if images supporting automatic OS upgrades return // AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported = true in GET VMImageVesion call string imagePublisher = "MicrosoftWindowsServer"; string imageOffer = "WindowsServer"; string imageSku = "2016-Datacenter"; string[] availableWindowsServerImageVersions =_pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku).Select(t => t.Name).ToArray(); string firstVersion = availableWindowsServerImageVersions.First(); string lastVersion = null; if (availableWindowsServerImageVersions.Length >= 2) { lastVersion = availableWindowsServerImageVersions.Last(); } var vmimage = _pirClient.VirtualMachineImages.Get( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, firstVersion); Assert.True(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported); if (!string.IsNullOrEmpty(lastVersion)) { vmimage = _pirClient.VirtualMachineImages.Get( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, lastVersion); Assert.True(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported); } // Validate if image not allowlisted to support automatic OS upgrades, return // AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported = false in GET VMImageVesion call imagePublisher = "Canonical"; imageOffer = "UbuntuServer"; imageSku = _pirClient.VirtualMachineImages.ListSkus(ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer).FirstOrDefault().Name; string[] availableUbuntuImageVersions = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku).Select(t => t.Name).ToArray(); firstVersion = availableUbuntuImageVersions.First(); lastVersion = null; if (availableUbuntuImageVersions.Length >= 2) { lastVersion = availableUbuntuImageVersions.Last(); } vmimage = _pirClient.VirtualMachineImages.Get( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, firstVersion); Assert.False(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported); if (!string.IsNullOrEmpty(lastVersion)) { vmimage = _pirClient.VirtualMachineImages.Get( ComputeManagementTestUtilities.DefaultLocation, imagePublisher, imageOffer, imageSku, lastVersion); Assert.False(vmimage.AutomaticOSUpgradeProperties.AutomaticOSUpgradeSupported); } } } [Fact] public void TestVMImageListNoFilter() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter"); Assert.True(vmimages.Count > 0); //Assert.True(vmimages.Count(vmi => vmi.Name == AvailableWindowsServerImageVersions[0]) != 0); //Assert.True(vmimages.Count(vmi => vmi.Name == AvailableWindowsServerImageVersions[1]) != 0); } } [Fact] public void TestVMImageListFilters() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); // Filter: top - Negative Test var vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 0); Assert.True(vmimages.Count == 0); // Filter: top - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 1); Assert.True(vmimages.Count == 1); // Filter: top - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 2); Assert.True(vmimages.Count == 2); // Filter: orderby - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", orderby: "name desc"); // Filter: orderby - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 2, orderby: "name asc"); Assert.True(vmimages.Count == 2); // Filter: top orderby - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 1, orderby: "name desc"); Assert.True(vmimages.Count == 1); // Filter: top orderby - Positive Test vmimages = _pirClient.VirtualMachineImages.List( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer", "2012-R2-Datacenter", top: 1, orderby: "name asc"); Assert.True(vmimages.Count == 1); } } [Fact] public void TestVMImageListPublishers() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var publishers = _pirClient.VirtualMachineImages.ListPublishers( ComputeManagementTestUtilities.DefaultLocation); Assert.True(publishers.Count > 0); Assert.True(publishers.Count(pub => pub.Name == "MicrosoftWindowsServer") != 0); } } [Fact] public void TestVMImageListOffers() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var offers = _pirClient.VirtualMachineImages.ListOffers( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer"); Assert.True(offers.Count > 0); Assert.True(offers.Count(offer => offer.Name == "WindowsServer") != 0); } } [Fact] public void TestVMImageListSkus() { using (MockContext context = MockContext.Start(this.GetType())) { ComputeManagementClient _pirClient = ComputeManagementTestUtilities.GetComputeManagementClient(context, new RecordedDelegatingHandler { StatusCodeToReturn = HttpStatusCode.OK }); var skus = _pirClient.VirtualMachineImages.ListSkus( ComputeManagementTestUtilities.DefaultLocation, "MicrosoftWindowsServer", "WindowsServer"); Assert.True(skus.Count > 0); Assert.True(skus.Count(sku => sku.Name == "2012-R2-Datacenter") != 0); } } } }
/* Lightweight C# Command line parser * * Author : Christian Bolterauer * Date : 8-Aug-2009 * Version : 1.0 * Changes : */ using System; using System.Collections.Generic; using System.Globalization; using System.Linq; namespace Hiale.NgenGui.Helper { /// <summary> /// Command Line Parser for creating and parsing command line options /// </summary> /// <remarks> Throws: MissingOptionException, DuplicateOptionException and if set InvalidOptionsException. /// </remarks> /// <seealso cref="Parse"/> /// <example> /// /// //using CmdLine OUTDATED! /// /// //create parser /// CmdLineParser parser = new CmdLineParser(); /// /// //add default help "-help",.. /// parser.AddHelpOption(); /// /// //add Option to parse /// CmdLineParser.Option DebugOption = parser.AddBoolSwitch("-Debug", "Print Debug information"); /// /// //add Alias option name /// DebugOption.AddAlias("/Debug"); /// /// CmdLineParser.NumberOption NegNumOpt = parser.AddDoubleParameter("-NegNum", "A required negativ Number", true); /// /// try /// { /// //parse /// parser.Parse(args); /// } /// catch (CmdLineParser.CMDLineParserException e) /// { /// Console.WriteLine("Error: " + e.Message); /// parser.HelpMessage(); /// } /// parser.Debug(); /// ///</example> internal class CmdLineParser { protected const string IS_NOT_A_SWITCH_MSG = "The Switch name does not start with an switch identifier '-' or '/' or contains space!"; private readonly List<Option> _switchesStore; private string[] _cmdlineArgs; private Option _help; private readonly List<String> _invalidArgs; private readonly List<Option> _matchedSwitches; //private readonly ArrayList _matchedSwitches; private readonly List<string> _unmatchedArgs; private static readonly string[] SwitchPrefixes = {"/", "-"}; public static bool AutoAddPrefix { get; set; } /// <summary> ///throw an exception if not matched (invalid) command line options were detected /// </summary> public bool ThrowInvalidOptionsException { get; set; } /// <summary> ///collect not matched (invalid) command line options as invalid args /// </summary> public bool CollectInvalidOptions { get; set; } public bool IsConsoleApplication { get; set; } public CmdLineParser() { _switchesStore = new List<Option>(); _invalidArgs = new List<string>(); //_matchedSwitches = new ArrayList(); _matchedSwitches = new List<Option>(); _unmatchedArgs = new List<string>(); CollectInvalidOptions = true; IsConsoleApplication = true; AutoAddPrefix = true; } /// <summary> /// Add a default help switch "-help","-h","-?","/help" /// </summary> public Option AddHelpOption() { _help = AddBoolSwitch("-help", "Command line help"); _help.AddAlias("-h"); _help.AddAlias("-?"); _help.AddAlias("/help"); return (_help); } /// <summary> /// Parses the command line and sets the values of each registered switch /// or parameter option. /// </summary> /// <param name="args">The arguments array sent to Main(string[] args)</param> /// <returns>'true' if all parsed options are valid otherwise 'false'</returns> /// <exception cref="DuplicateOptionException"></exception> /// <exception cref="InvalidOptionsException"></exception> public bool Parse(string[] args) { Clear(); for (var i = 0; i < args.Length; i++) args[i] = args[i].ToLower(); _cmdlineArgs = args; ParseOptions(); if (_invalidArgs.Count > 0) { if (ThrowInvalidOptionsException) { var iopts = string.Empty; foreach (string arg in _invalidArgs) { iopts += "'" + arg + "';"; } throw new InvalidOptionsException("Invalid command line argument(s): " + iopts); } return false; } return true; } /// <summary> /// Reset Parser and values of registed options. /// </summary> public void Clear() { _matchedSwitches.Clear(); _unmatchedArgs.Clear(); _invalidArgs.Clear(); foreach (var s in _switchesStore) s.Clear(); } /// <summary> /// Add (a custom) Option (Optional) /// </summary> /// <remarks> /// To add instances (or subclasses) of 'CmdLineParser.Option' /// that implement: /// <code>'public override object parseValue(string parameter)'</code> /// </remarks> /// <param name="opt">subclass from 'CmdLineParser.Option'</param> /// <seealso cref="AddBoolSwitch"/> /// <seealso cref="AddStringParameter"/> public void AddOption(Option opt) { //var switchName = string.Empty; //if (AutoAddPrefix) //{ // foreach (var switchPrefix in SwitchPrefixes.Where(switchPrefix => opt.Name.StartsWith(switchPrefix))) // opt.Name = opt.Name.Remove(0, 1); // switchName = opt.Name; // opt.Name = SwitchPrefixes[0] + opt.Name; //} CheckCmdLineOption(opt.Name); //if (AutoAddPrefix) //{ // for (var i = 1; i < SwitchPrefixes.Length; i++) // opt.AddAlias(SwitchPrefixes[i] + switchName); //} _switchesStore.Add(opt); } /// <summary> /// Add a basic command line switch. /// (exist = 'true' otherwise 'false'). /// </summary> public Option AddBoolSwitch(string name, string description) { var opt = new Option(name, description, typeof(bool), false, false); AddOption(opt); return opt; } /// <summary> /// Add a string parameter command line option. /// </summary> public Option AddStringParameter(string name, string description, bool required) { var opt = new Option(name, description, typeof (string), true, required); AddOption(opt); return opt; } /// <summary> /// Add a Integer parameter command line option. /// </summary> public NumberOption AddIntParameter(string name, string description, bool required) { var opt = new NumberOption(name, description, typeof (int), true, required) {NumberStyle = NumberStyles.Integer}; AddOption(opt); return opt; } /// <summary> /// Add a Double parameter command line option. /// </summary> public NumberOption AddDoubleParameter(string name, string description, bool required) { var opt = new NumberOption(name, description, typeof (double), true, required) {NumberStyle = NumberStyles.Float}; AddOption(opt); return (opt); } /// <summary> /// Add a Double parameter command line option. /// </summary> public NumberOption AddDoubleParameter(string name, string description, bool required, NumberFormatInfo numberformat) { var opt = new NumberOption(name, description, typeof (double), true, required) {NumberFormat = numberformat, ParseDecimalSeperator = false, NumberStyle = NumberStyles.Float | NumberStyles.AllowThousands}; AddOption(opt); return (opt); } /// <summary> /// Check if name is a valid Option name /// </summary> /// <param name="name"></param> /// <exception cref="CmdLineParserException"></exception> private static void CheckCmdLineOption(string name) { if (!IsASwitch(name)) throw new CmdLineParserException("Invalid Option: '" + name + "'"); } protected static bool IsASwitch(string arg) { //var isValid = SwitchPrefixes.Any(arg.StartsWith); //return isValid & !arg.Contains(" "); return !arg.Contains(" "); } private void ParseOptions() { for (var i = 0; i < _cmdlineArgs.Length; i++) { var arg = _cmdlineArgs[i]; var found = false; foreach (var s in _switchesStore) { if (Compare(s, arg)) { s.IsMatched = found = true; _matchedSwitches.Add(s); i = ProcessMatchedSwitch(s, _cmdlineArgs, i); } } if (found == false) ProcessUnmatchedArg(arg); } CheckReqired(); } private void CheckReqired() { foreach (var s in _switchesStore) { if (s.IsRequired && (!s.IsMatched)) throw new MissingRequiredOptionException("Missing Required Option:'" + s.Name + "'"); } } private static bool Compare(Option option, string arg) { if (!option.NeedsValue) { foreach (var optname in option.Names) { if (optname.Equals(arg)) { //option.Name = optname; //set name in case we match an alias name return true; } } return false; } foreach (var optname in option.Names) { if (arg.StartsWith(optname)) //if (arg.StartsWith(optname)) { CheckDuplicateAndSetName(option, optname); return true; } } return false; } private static void CheckDuplicateAndSetName(Option s, string optname) { if (s.IsMatched && s.NeedsValue) throw new DuplicateOptionException("Duplicate: The Option: '" + optname + "' already exists on the comand line as '" + s.Name + "'"); //s.Name = optname; //set name in case we match an alias name //NOT SURE IF IT HAS SIDEEFFECT IF IT'S COMMENTED OUT } private static int RetrieveParameter(ref string parameter, string optname, IList<string> cmdlineArgs, int pos) { if (cmdlineArgs[pos].Length == optname.Length) // arg must be in next cmdlineArg { if (cmdlineArgs.Count > pos + 1) { pos++; //change command line index to next cmdline Arg. parameter = cmdlineArgs[pos]; } } else { parameter = (cmdlineArgs[pos].Substring(optname.Length)); } return pos; } protected int ProcessMatchedSwitch(Option s, string[] cmdlineArgs, int pos) { //if help switch is matched give help .. only works for console apps if (s.Equals(_help)) { if (IsConsoleApplication) { Console.Write(HelpMessage()); } } //process bool switch if (s.Type == typeof (bool)) { ((IParsableOptionParameter)s).ParseValue(string.Empty); //string parameter = ""; //pos = RetrieveParameter(ref parameter, s.Name, cmdlineArgs, pos); //s.Value = true; //((IParsableOptionParameter)s).ParseValue(parameter); return pos; } if (s.NeedsValue) { //retrieve parameter value and adjust pos string parameter = ""; pos = RetrieveParameter(ref parameter, s.Name, cmdlineArgs, pos); //parse option using 'IParsableOptionParameter.parseValue(parameter)' //and set parameter value try { if (s.Type != null) { //((IParsableOptionParameter) s).Value = ((IParsableOptionParameter) s).ParseValue(parameter); ((IParsableOptionParameter) s).ParseValue(parameter); return pos; } } catch (Exception ex) { throw new ParameterConversionException(ex.Message); } } //unsupported type .. throw new CmdLineParserException("Unsupported Parameter Type:" + s.Type); } protected void ProcessUnmatchedArg(string arg) { if (CollectInvalidOptions && IsASwitch(arg)) //assuming an invalid comand line option { _invalidArgs.Add(arg); //collect first, throw Exception later if set.. } else { _unmatchedArgs.Add(arg); } } /// <summary> /// String array of remaining arguments not identified as command line options /// </summary> public String[] RemainingArgs() { if (_unmatchedArgs == null) return null; return _unmatchedArgs.ToArray(); } /// <summary> /// String array of matched command line options /// </summary> public String[] MatchedOptions() { var names = new List<string>(); for (int s = 0; s < _matchedSwitches.Count; s++) names.Add(_matchedSwitches[s].Name); return names.ToArray(); } /// <summary> /// String array of not identified command line options /// </summary> public String[] InvalidArgs() { if (_invalidArgs == null) return null; return _invalidArgs.ToArray(); } /// <summary> /// Create usage: A formated help message with a list of registered command line options. /// </summary> public string HelpMessage() { const string indent = " "; int ind = indent.Length; const int spc = 3; int len = 0; foreach (var s in _switchesStore) { foreach (var name in s.Names) { var nlen = name.Length; if (s.NeedsValue) nlen += (" [..]").Length; len = Math.Max(len, nlen); } } var help = "\nCommand line options are:\n\n"; var req = false; foreach (var s in _switchesStore) { var line = indent + s.Names[0]; if (s.NeedsValue) line += " [..]"; while (line.Length < len + spc + ind) line += " "; if (s.IsRequired) { line += "(*) "; req = true; } line += s.Description; help += line + "\n"; if (s.Aliases != null && s.Aliases.Length > 0) { foreach (string name in s.Aliases) { line = indent + name; if (s.NeedsValue) line += " [..]"; help += line + "\n"; } } help += "\n"; } if (req) help += "(*) Required.\n"; return help; } // ReSharper disable LocalizableElement /// <summary> /// Print debug information of this CMDLineParser to the system console. /// </summary> public void Debug() { Console.WriteLine(); Console.WriteLine("\n------------- DEBUG CMDLineParser -------------\n"); if (_switchesStore.Count > 0) { Console.WriteLine("There are {0} registered switches:", _switchesStore.Count); foreach (var s in _switchesStore) { Console.WriteLine("Command : {0} : [{1}]", s.Names[0], s.Description); Console.Write("Type : {0} ", s.Type); Console.WriteLine(); if (s.Aliases.Length > 0) { Console.Write("Aliases : [{0}] : ", s.Aliases.Length); foreach (string alias in s.Aliases) Console.Write(" {0}", alias); Console.WriteLine(); } Console.WriteLine("Required: {0}", s.IsRequired); Console.WriteLine("Value is: {0} \n", s.Value ?? "(Unknown)"); } } else { Console.WriteLine("There are no registered switches."); } if (_matchedSwitches.Count > 0) { Console.WriteLine("\nThe following switches were found:"); foreach (Option s in _matchedSwitches) Console.WriteLine(" {0} Value:{1}", s.Name ?? "(Unknown)", s.Value ?? "(Unknown)"); } else Console.WriteLine("\nNo Command Line Options detected."); Console.Write(InvalidArgsMessage()); Console.WriteLine("\n----------- DEBUG CMDLineParser END -----------\n"); } // ReSharper restore LocalizableElement private string InvalidArgsMessage() { const string indent = " "; string msg = ""; if (_invalidArgs != null) { msg += "\nThe following args contain invalid (unknown) options:"; if (_invalidArgs.Count > 0) { foreach (string s in _invalidArgs) msg += "\n" + indent + s; } else msg += "\n" + indent + "- Non -"; } return msg + "\n"; } /// <summary> /// Interface supporting parsing and setting of string parameter Values to objects /// </summary> private interface IParsableOptionParameter { /// <summary> /// Get or Set the value /// </summary> object Value { get; } /// <summary> /// parse string parameter to convert to an object /// </summary> /// <param name="parameter"></param> /// <returns>an object</returns> object ParseValue(string parameter); } /// <summary> /// A comand line Option: A switch or a string parameter option. /// </summary> /// <remarks> Use AddBoolSwitch(..) or AddStringParameter(..) (Factory) /// Methods to create and store a new parsable 'CMDLineParser.Option'. /// </remarks> public class Option : IParsableOptionParameter { private readonly bool _needsVal; private readonly Type _switchType; private readonly List<string> _names; private bool _matched; private string _name; private object _value; public Option(string name, string description, Type type, bool needsValue, bool required) { name = name.ToLower(); _names = AnalizeName(name); _switchType = type; _needsVal = needsValue; IsRequired = required; //_name = _names[0]; Description = description; } //getters and setters public string Name { get { return _name; } set { _name = value; } } public string Description { get; set; } /// <summary> /// Object Type of Option Value (e.g. typeof(int)) /// </summary> public Type Type { get { return _switchType; } } public bool NeedsValue { get { return _needsVal; } } public bool IsRequired { get; set; } /// <summary> /// set to 'true' if Option has been detected on the command line /// </summary> public bool IsMatched { get { return _matched; } set { _matched = value; } } public string[] Names { get { return _names.ToArray(); } } public string[] Aliases { get { var list = new List<string>(Names); list.RemoveAt(0); //remove 'name' (first element) from the list to leave aliases only return list.ToArray(); } } public object Value { get { return (_value); } private set { _value = value; } } private List<string> AnalizeName(string name) { var names = new List<string>(); if (AutoAddPrefix) { foreach (var switchPrefix in SwitchPrefixes) { if (name.StartsWith(switchPrefix)) name = name.Remove(0, switchPrefix.Length); } Name = name; names.AddRange(SwitchPrefixes.Select(switchPrefix => switchPrefix + name)); } else names.Add(name); return names; } /// <summary> /// Default implementation of parseValue: /// Subclasses should override this method to provide a method for converting /// the parsed string parameter to its Object type /// </summary> /// <param name="parameter"></param> /// <returns>converted value</returns> /// <see cref="ParseValue"/> public virtual object ParseValue(string parameter) { //set string parameter if (Type == typeof (string) && NeedsValue) { Value = parameter; return parameter; //string needs no parsing (conversion) to string... } if (Type == typeof(bool)) { Value = true; return true; } //throw Exception when parseValue has not been implemented by a subclass throw new Exception("Option is missing an method to convert the value."); } public void AddAlias(string alias) { if (!IsASwitch(alias)) throw new CmdLineParserException("Invalid Option: '" + alias + "'"); var aliasLow = alias.ToLower(); if (AutoAddPrefix) { foreach (var switchPrefix in SwitchPrefixes) { if (aliasLow.StartsWith(switchPrefix)) aliasLow = aliasLow.Remove(0, switchPrefix.Length); } foreach (var switchPrefix in SwitchPrefixes.Where(switchPrefix => !_names.Contains(switchPrefix + aliasLow))) { _names.Add(switchPrefix + aliasLow); } } else { if (!_names.Contains(aliasLow)) _names.Add(aliasLow); } } public void Clear() { _matched = false; _value = null; } public override string ToString() { return Name; } } /// <summary> /// An command line option with a Number parameter. /// </summary> ///<remarks> /// To avoid unpredictable results on plattforms that use different 'Culture' settings /// the default is set to 'invariant Culture' and parseDecimalSeperator=true; /// The number format can be changed for each CMDLineParser.NumberOption individually for /// more strict parsing. ///</remarks> public class NumberOption : Option { private NumberFormatInfo _numberformat; private NumberStyles _numberstyle; public NumberOption(string name, string description, Type type, bool hasval, bool required) : base(name, description, type, hasval, required) { NumberFormat = CultureInfo.InvariantCulture.NumberFormat; ParseDecimalSeperator = true; } /// <summary> /// Get or Set the NumberFormat Information for parsing the parameter /// </summary> public NumberFormatInfo NumberFormat { get { return _numberformat; } set { _numberformat = value; } } /// <summary> /// Get or Set the NumberStyle for parsing the parameter /// </summary> public NumberStyles NumberStyle { get { return _numberstyle; } set { _numberstyle = value; } } /// <summary> /// If set to true the parser tries to detect and set the Decimalseparetor ("." or ",") /// automaticly. (default=true) /// </summary> public bool ParseDecimalSeperator { get; set; } public override object ParseValue(string parameter) { // int parameter if (Type == typeof(int)) { return ParseIntValue(parameter); } // double parameter if (Type == typeof(double)) { return ParseDoubleValue(parameter); } throw new ParameterConversionException("Invalid Option Type: " + Type); } // private int ParseIntValue(string parameter) { try { return (Int32.Parse(parameter, _numberstyle, _numberformat)); } catch (Exception e) { throw new ParameterConversionException("Invalid Int Parameter:" + parameter + " - " + e.Message); } } // private double ParseDoubleValue(string parameter) { if (ParseDecimalSeperator) SetIdentifiedDecimalSeperator(parameter); try { return (Double.Parse(parameter, _numberstyle, _numberformat)); } catch (Exception e) { throw new ParameterConversionException("Invalid Double Parameter:" + parameter + " - " + e.Message); } } // private void SetIdentifiedDecimalSeperator(string parameter) { if (_numberformat.NumberDecimalSeparator == "." && parameter.Contains(",") && !(parameter.Contains("."))) { _numberformat.NumberDecimalSeparator = ","; if (_numberformat.NumberGroupSeparator == ",") _numberformat.NumberGroupSeparator = "."; } else { if (_numberformat.NumberDecimalSeparator == "," && parameter.Contains(".") && !(parameter.Contains(","))) { _numberformat.NumberDecimalSeparator = "."; if (_numberformat.NumberGroupSeparator == ".") _numberformat.NumberGroupSeparator = ","; } } } } #region Nested types: Exceptions /// <summary> /// Command line parsing Exception. /// </summary> public class CmdLineParserException : Exception { public CmdLineParserException(string message) : base(message) { } } /// <summary> /// Thrown when duplicate option was detected /// </summary> public class DuplicateOptionException : CmdLineParserException { public DuplicateOptionException(string message) : base(message) { } } /// <summary> /// Thrown when invalid (not registered) options have been detected /// </summary> public class InvalidOptionsException : CmdLineParserException { public InvalidOptionsException(string message) : base(message) { } } /// <summary> /// Thrown when parameter value conversion to specified type failed /// </summary> public class ParameterConversionException : CmdLineParserException { public ParameterConversionException(string message) : base(message) { } } /// <summary> /// Thrown when required option was not detected /// </summary> public class MissingRequiredOptionException : CmdLineParserException { public MissingRequiredOptionException(string message) : base(message) { } } #endregion } }
using System; using System.Collections.Generic; using System.Reactive.Linq; using System.Reactive.Threading.Tasks; using MS.Core; namespace System.Collections { public static class __SortedList { public static IObservable<System.Reactive.Unit> Add( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Object> key, IObservable<System.Object> value) { return ObservableExt.ZipExecute(SortedListValue, key, value, (SortedListValueLambda, keyLambda, valueLambda) => SortedListValueLambda.Add(keyLambda, valueLambda)); } public static IObservable<System.Reactive.Unit> Clear( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Do(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.Clear()).ToUnit(); } public static IObservable<System.Object> Clone(this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.Clone()); } public static IObservable<System.Boolean> Contains( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Object> key) { return Observable.Zip(SortedListValue, key, (SortedListValueLambda, keyLambda) => SortedListValueLambda.Contains(keyLambda)); } public static IObservable<System.Boolean> ContainsKey( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Object> key) { return Observable.Zip(SortedListValue, key, (SortedListValueLambda, keyLambda) => SortedListValueLambda.ContainsKey(keyLambda)); } public static IObservable<System.Boolean> ContainsValue( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Object> value) { return Observable.Zip(SortedListValue, value, (SortedListValueLambda, valueLambda) => SortedListValueLambda.ContainsValue(valueLambda)); } public static IObservable<System.Reactive.Unit> CopyTo( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Array> array, IObservable<System.Int32> arrayIndex) { return ObservableExt.ZipExecute(SortedListValue, array, arrayIndex, (SortedListValueLambda, arrayLambda, arrayIndexLambda) => SortedListValueLambda.CopyTo(arrayLambda, arrayIndexLambda)); } public static IObservable<System.Object> GetByIndex( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Int32> index) { return Observable.Zip(SortedListValue, index, (SortedListValueLambda, indexLambda) => SortedListValueLambda.GetByIndex(indexLambda)); } public static IObservable<System.Collections.IDictionaryEnumerator> GetEnumerator( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.GetEnumerator()); } public static IObservable<System.Object> GetKey(this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Int32> index) { return Observable.Zip(SortedListValue, index, (SortedListValueLambda, indexLambda) => SortedListValueLambda.GetKey(indexLambda)); } public static IObservable<System.Collections.IList> GetKeyList( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.GetKeyList()); } public static IObservable<System.Collections.IList> GetValueList( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.GetValueList()); } public static IObservable<System.Int32> IndexOfKey( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Object> key) { return Observable.Zip(SortedListValue, key, (SortedListValueLambda, keyLambda) => SortedListValueLambda.IndexOfKey(keyLambda)); } public static IObservable<System.Int32> IndexOfValue( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Object> value) { return Observable.Zip(SortedListValue, value, (SortedListValueLambda, valueLambda) => SortedListValueLambda.IndexOfValue(valueLambda)); } public static IObservable<System.Reactive.Unit> RemoveAt( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Int32> index) { return ObservableExt.ZipExecute(SortedListValue, index, (SortedListValueLambda, indexLambda) => SortedListValueLambda.RemoveAt(indexLambda)); } public static IObservable<System.Reactive.Unit> Remove( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Object> key) { return ObservableExt.ZipExecute(SortedListValue, key, (SortedListValueLambda, keyLambda) => SortedListValueLambda.Remove(keyLambda)); } public static IObservable<System.Reactive.Unit> SetByIndex( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Int32> index, IObservable<System.Object> value) { return ObservableExt.ZipExecute(SortedListValue, index, value, (SortedListValueLambda, indexLambda, valueLambda) => SortedListValueLambda.SetByIndex(indexLambda, valueLambda)); } public static IObservable<System.Collections.SortedList> Synchronized( IObservable<System.Collections.SortedList> list) { return Observable.Select(list, (listLambda) => System.Collections.SortedList.Synchronized(listLambda)); } public static IObservable<System.Reactive.Unit> TrimToSize( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Do(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.TrimToSize()).ToUnit(); } public static IObservable<System.Int32> get_Capacity( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.Capacity); } public static IObservable<System.Int32> get_Count( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.Count); } public static IObservable<System.Collections.ICollection> get_Keys( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.Keys); } public static IObservable<System.Collections.ICollection> get_Values( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.Values); } public static IObservable<System.Boolean> get_IsReadOnly( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.IsReadOnly); } public static IObservable<System.Boolean> get_IsFixedSize( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.IsFixedSize); } public static IObservable<System.Boolean> get_IsSynchronized( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.IsSynchronized); } public static IObservable<System.Object> get_SyncRoot( this IObservable<System.Collections.SortedList> SortedListValue) { return Observable.Select(SortedListValue, (SortedListValueLambda) => SortedListValueLambda.SyncRoot); } public static IObservable<System.Object> get_Item( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Object> key) { return Observable.Zip(SortedListValue, key, (SortedListValueLambda, keyLambda) => SortedListValueLambda[keyLambda]); } public static IObservable<System.Reactive.Unit> set_Capacity( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Int32> value) { return ObservableExt.ZipExecute(SortedListValue, value, (SortedListValueLambda, valueLambda) => SortedListValueLambda.Capacity = valueLambda); } public static IObservable<System.Reactive.Unit> set_Item( this IObservable<System.Collections.SortedList> SortedListValue, IObservable<System.Object> key, IObservable<System.Object> value) { return ObservableExt.ZipExecute(SortedListValue, key, value, (SortedListValueLambda, keyLambda, valueLambda) => SortedListValueLambda[keyLambda] = valueLambda); } } }
// *********************************************************************** // Copyright (c) 2011 Charlie Poole // // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // *********************************************************************** using System; using System.IO; using System.Threading; using System.Diagnostics; using System.Collections.Generic; using System.Reflection; using NUnit.Common; using NUnit.Engine.Internal; namespace NUnit.Engine.Services { /// <summary> /// Enumeration used to report AgentStatus /// </summary> public enum AgentStatus { Unknown, Starting, Ready, Busy, Stopping } /// <summary> /// The TestAgency class provides RemoteTestAgents /// on request and tracks their status. Agents /// are wrapped in an instance of the TestAgent /// class. Multiple agent types are supported /// but only one, ProcessAgent is implemented /// at this time. /// </summary> public class TestAgency : ServerBase, ITestAgency, IService { static Logger log = InternalTrace.GetLogger(typeof(TestAgency)); #region Private Fields private AgentDataBase _agentData = new AgentDataBase(); private IRuntimeFrameworkService _runtimeService; #endregion #region Constructors public TestAgency() : this( "TestAgency", 0 ) { } public TestAgency( string uri, int port ) : base( uri, port ) { } #endregion #region ServerBase Overrides //public override void Stop() //{ // foreach( KeyValuePair<Guid,AgentRecord> pair in agentData ) // { // AgentRecord r = pair.Value; // if ( !r.Process.HasExited ) // { // if ( r.Agent != null ) // { // r.Agent.Stop(); // r.Process.WaitForExit(10000); // } // if ( !r.Process.HasExited ) // r.Process.Kill(); // } // } // agentData.Clear(); // base.Stop (); //} #endregion #region Public Methods - Called by Agents public void Register( ITestAgent agent ) { AgentRecord r = _agentData[agent.Id]; if ( r == null ) throw new ArgumentException( string.Format("Agent {0} is not in the agency database", agent.Id), "agentId"); r.Agent = agent; } public void ReportStatus( Guid agentId, AgentStatus status ) { AgentRecord r = _agentData[agentId]; if ( r == null ) throw new ArgumentException( string.Format("Agent {0} is not in the agency database", agentId), "agentId" ); r.Status = status; } #endregion #region Public Methods - Called by Clients public ITestAgent GetAgent(TestPackage package, int waitTime) { // TODO: Decide if we should reuse agents //AgentRecord r = FindAvailableRemoteAgent(type); //if ( r == null ) // r = CreateRemoteAgent(type, framework, waitTime); return CreateRemoteAgent(package, waitTime); } public void ReleaseAgent( ITestAgent agent ) { AgentRecord r = _agentData[agent.Id]; if (r == null) log.Error(string.Format("Unable to release agent {0} - not in database", agent.Id)); else { r.Status = AgentStatus.Ready; log.Debug("Releasing agent " + agent.Id.ToString()); } } //public void DestroyAgent( ITestAgent agent ) //{ // AgentRecord r = agentData[agent.Id]; // if ( r != null ) // { // if( !r.Process.HasExited ) // r.Agent.Stop(); // agentData[r.Id] = null; // } //} #endregion #region Helper Methods private Guid LaunchAgentProcess(TestPackage package) { string runtimeSetting = package.GetSetting(PackageSettings.RuntimeFramework, ""); RuntimeFramework targetRuntime = RuntimeFramework.Parse( runtimeSetting != "" ? runtimeSetting : _runtimeService.SelectRuntimeFramework(package)); if (targetRuntime.Runtime == RuntimeType.Any) targetRuntime = new RuntimeFramework(RuntimeFramework.CurrentFramework.Runtime, targetRuntime.ClrVersion); bool useX86Agent = package.GetSetting(PackageSettings.RunAsX86, false); bool debugTests = package.GetSetting(PackageSettings.DebugTests, false); bool debugAgent = package.GetSetting(PackageSettings.DebugAgent, false); bool verbose = package.GetSetting("Verbose", false); string agentArgs = string.Empty; if (debugAgent) agentArgs += " --debug-agent"; if (verbose) agentArgs += " --verbose"; log.Info("Getting {0} agent for use under {1}", useX86Agent ? "x86" : "standard", targetRuntime); if (!targetRuntime.IsAvailable) throw new ArgumentException( string.Format("The {0} framework is not available", targetRuntime), "framework"); string agentExePath = GetTestAgentExePath(targetRuntime.ClrVersion, useX86Agent); if (agentExePath == null) throw new ArgumentException( string.Format("NUnit components for version {0} of the CLR are not installed", targetRuntime.ClrVersion.ToString()), "targetRuntime"); log.Debug("Using nunit-agent at " + agentExePath); Process p = new Process(); p.StartInfo.UseShellExecute = false; Guid agentId = Guid.NewGuid(); string arglist = agentId.ToString() + " " + ServerUrl + " " + agentArgs; switch( targetRuntime.Runtime ) { case RuntimeType.Mono: p.StartInfo.FileName = NUnitConfiguration.MonoExePath; string monoOptions = "--runtime=v" + targetRuntime.ClrVersion.ToString(3); if (debugTests || debugAgent) monoOptions += " --debug"; p.StartInfo.Arguments = string.Format("{0} \"{1}\" {2}", monoOptions, agentExePath, arglist); break; case RuntimeType.Net: p.StartInfo.FileName = agentExePath; if (targetRuntime.ClrVersion.Build < 0) targetRuntime = RuntimeFramework.GetBestAvailableFramework(targetRuntime); string envVar = "v" + targetRuntime.ClrVersion.ToString(3); p.StartInfo.EnvironmentVariables["COMPLUS_Version"] = envVar; p.StartInfo.Arguments = arglist; break; default: p.StartInfo.FileName = agentExePath; p.StartInfo.Arguments = arglist; break; } //p.Exited += new EventHandler(OnProcessExit); p.Start(); log.Info("Launched Agent process {0} - see nunit-agent_{0}.log", p.Id); log.Info("Command line: \"{0}\" {1}", p.StartInfo.FileName, p.StartInfo.Arguments); _agentData.Add( new AgentRecord( agentId, p, null, AgentStatus.Starting ) ); return agentId; } //private void OnProcessExit(object sender, EventArgs e) //{ // Process p = sender as Process; // if (p != null) // agentData.Remove(p.Id); //} //private AgentRecord FindAvailableAgent() //{ // foreach( AgentRecord r in agentData ) // if ( r.Status == AgentStatus.Ready) // { // log.Debug( "Reusing agent {0}", r.Id ); // r.Status = AgentStatus.Busy; // return r; // } // return null; //} private ITestAgent CreateRemoteAgent(TestPackage package, int waitTime) { Guid agentId = LaunchAgentProcess(package); log.Debug( "Waiting for agent {0} to register", agentId.ToString("B") ); int pollTime = 200; bool infinite = waitTime == Timeout.Infinite; while( infinite || waitTime > 0 ) { Thread.Sleep( pollTime ); if ( !infinite ) waitTime -= pollTime; ITestAgent agent = _agentData[agentId].Agent; if ( agent != null ) { log.Debug( "Returning new agent {0}", agentId.ToString("B") ); return agent; } } return null; } /// <summary> /// Return the NUnit Bin Directory for a particular /// runtime version, or null if it's not installed. /// For normal installations, there are only 1.1 and /// 2.0 directories. However, this method accommodates /// 3.5 and 4.0 directories for the benefit of NUnit /// developers using those runtimes. /// </summary> private static string GetNUnitBinDirectory(Version v) { // Get current bin directory string dir = NUnitConfiguration.NUnitBinDirectory; // Return current directory if current and requested // versions are both >= 2 or both 1 if ((Environment.Version.Major >= 2) == (v.Major >= 2)) return dir; // Check whether special support for version 1 is installed if (v.Major == 1) { string altDir = Path.Combine(dir, "net-1.1"); if (Directory.Exists(altDir)) return altDir; // The following is only applicable to the dev environment, // which uses parallel build directories. We try to substitute // one version number for another in the path. string[] search = new string[] { "2.0", "3.0", "3.5", "4.0" }; string[] replace = v.Minor == 0 ? new string[] { "1.0", "1.1" } : new string[] { "1.1", "1.0" }; // Look for current value in path so it can be replaced string current = null; foreach (string s in search) if (dir.IndexOf(s) >= 0) { current = s; break; } // Try the substitution if (current != null) { foreach (string target in replace) { altDir = dir.Replace(current, target); if (Directory.Exists(altDir)) return altDir; } } } return null; } private static string GetTestAgentExePath(Version v, bool requires32Bit) { string binDir = NUnitConfiguration.NUnitBinDirectory; if (binDir == null) return null; string agentName = v.Major > 1 && requires32Bit ? "nunit-agent-x86.exe" : "nunit-agent.exe"; string agentExePath = Path.Combine(binDir, agentName); return File.Exists(agentExePath) ? agentExePath : null; } #endregion #region IService Members public IServiceLocator ServiceContext { get; set; } public ServiceStatus Status { get; private set; } public void StopService() { try { Stop(); } finally { Status = ServiceStatus.Stopped; } } public void StartService() { try { // TestAgency requires on the RuntimeFrameworkService. _runtimeService = ServiceContext.GetService<IRuntimeFrameworkService>(); // Any object returned from ServiceContext is an IService if (_runtimeService != null && ((IService)_runtimeService).Status == ServiceStatus.Started) { try { Start(); Status = ServiceStatus.Started; } catch { Status = ServiceStatus.Error; throw; } } else { Status = ServiceStatus.Error; } } catch { Status = ServiceStatus.Error; throw; } } #endregion #region Nested Class - AgentRecord private class AgentRecord { public Guid Id; public Process Process; public ITestAgent Agent; public AgentStatus Status; public AgentRecord( Guid id, Process p, ITestAgent a, AgentStatus s ) { this.Id = id; this.Process = p; this.Agent = a; this.Status = s; } } #endregion #region Nested Class - AgentDataBase /// <summary> /// A simple class that tracks data about this /// agencies active and available agents /// </summary> private class AgentDataBase { private Dictionary<Guid, AgentRecord> agentData = new Dictionary<Guid, AgentRecord>(); public AgentRecord this[Guid id] { get { return agentData[id]; } set { if ( value == null ) agentData.Remove( id ); else agentData[id] = value; } } public AgentRecord this[ITestAgent agent] { get { foreach( KeyValuePair<Guid, AgentRecord> entry in agentData) { AgentRecord r = entry.Value; if ( r.Agent == agent ) return r; } return null; } } public void Add( AgentRecord r ) { agentData[r.Id] = r; } public void Remove(Guid agentId) { agentData.Remove(agentId); } public void Clear() { agentData.Clear(); } //#region IEnumerable Members //public IEnumerator<KeyValuePair<Guid,AgentRecord>> GetEnumerator() //{ // return agentData.GetEnumerator(); //} //#endregion } #endregion } }
// Copyright (c) DotSpatial Team. All rights reserved. // Licensed under the MIT license. See License.txt file in the project root for full license information. using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using DotSpatial.Data; using DotSpatial.Symbology; using GeoAPI.Geometries; namespace DotSpatial.Controls { /// <summary> /// Interface for the map frame. /// </summary> public interface IMapFrame : IFrame, IMapGroup, IProj { #region Events /// <summary> /// Occurs when the buffer content has been altered and any containing maps should quick-draw /// from the buffer, followed by the tool drawing. /// </summary> event EventHandler<ClipArgs> BufferChanged; /// <summary> /// Occurs after every one of the zones, chunks and stages has finished rendering to a stencil. /// </summary> event EventHandler FinishedRefresh; /// <summary> /// Occurs after changes have been made to the back buffer that affect the viewing area of the screen, /// thereby requiring an invalidation. /// </summary> event EventHandler ScreenUpdated; /// <summary> /// Occurs when View changed /// </summary> event EventHandler<ViewChangedEventArgs> ViewChanged; #endregion #region Properties /// <summary> /// Gets or sets the clockwise map frame angle used for rotation. /// </summary> double Angle { get; set; } /// <summary> /// Gets or sets the buffered image. Mess with this at your own risk. /// </summary> Image BufferImage { get; set; } /// <summary> /// Gets a rectangle indicating the size of the map frame image /// </summary> Rectangle ClientRectangle { get; } /// <summary> /// Gets or sets the integer that specifies the chunk that is actively being drawn /// </summary> int CurrentChunk { get; set; } /// <summary> /// Gets or sets a value indicating whether this map frame should define its buffer /// region to be the same size as the client, or three times larger. /// </summary> bool ExtendBuffer { get; set; } /// <summary> /// Gets the coefficient used for ExtendBuffer. This coefficient should not be modified. /// </summary> int ExtendBufferCoeff { get; } /// <summary> /// Gets or sets a value indicating whether this map frame is currently in the process of redrawing the /// stencils after a pan operation. Drawing should not take place if this is true. /// </summary> bool IsPanning { get; set; } /// <summary> /// Gets or sets the layers /// </summary> new IMapLayerCollection Layers { get; set; } /// <summary> /// Gets or sets the parent control for this map frame. /// </summary> Control Parent { get; set; } /// <summary> /// Gets or sets the PromptMode that determines how to warn users when attempting to add a layer without /// a projection to a map that has a projection. /// </summary> ActionMode ProjectionModeDefine { get; set; } /// <summary> /// Gets or sets the PromptMode that determines how to warn users when attempting to add a layer with /// a coordinate system that is different from the current projection. /// </summary> ActionMode ProjectionModeReproject { get; set; } /// <summary> /// gets or sets the rectangle in pixel coordinates that will be drawn to the entire screen. /// </summary> Rectangle View { get; set; } #endregion #region Methods /// <summary> /// Unlike PixelToProj, which works relative to the client control, /// BufferToProj takes a pixel coordinate on the buffer and /// converts it to geographic coordinates. /// </summary> /// <param name="position">A Point describing the pixel position on the back buffer</param> /// <returns>An ICoordinate describing the geographic position</returns> Coordinate BufferToProj(Point position); /// <summary> /// This projects a rectangle relative to the buffer into and Envelope in geographic coordinates. /// </summary> /// <param name="rect">A Rectangle</param> /// <returns>An Envelope interface</returns> Extent BufferToProj(Rectangle rect); /// <summary> /// Using the standard independent paint method would potentially cause for dis-synchrony between /// the parents state and the state of this control. This way, the drawing is all done at the same time. /// </summary> /// <param name="e">The event args.</param> void Draw(PaintEventArgs e); /// <summary> /// Uses the current buffer and envelope to force each of the contained layers /// to re-draw their content. This is useful after a zoom or size change. /// </summary> void Initialize(); /// <summary> /// Instructs the map frame to draw content from the specified regions to the buffer.. /// </summary> /// <param name="regions">The regions to initialize.</param> void Initialize(List<Extent> regions); /// <summary> /// This will cause an invalidation for each layer. The actual rectangle to re-draw is not specified /// here, but rather this simply indicates that some re-calculation is necessary. /// </summary> void InvalidateLayers(); /// <summary> /// Pans the image for this map frame. Instead of drawing entirely new content, from all 5 zones, /// just the slivers of newly revealed area need to be re-drawn. /// </summary> /// <param name="shift">A Point showing the amount to shift in pixels</param> void Pan(Point shift); /// <summary> /// When the control is being resized, the view needs to change in order to preserve the aspect ratio, /// even though we want to use the exact same extents. /// </summary> void ParentResize(); /// <summary> /// Obtains a rectangle relative to the background image by comparing /// the current View rectangle with the parent control's size. /// </summary> /// <param name="clip">Rectangle used for clipping.</param> /// <returns>The resulting rectangle.</returns> Rectangle ParentToView(Rectangle clip); // CGX /// <summary> /// /// </summary> void ZoomToLayerEnvelope(Envelope layerEnvelope); // CGX END /// <summary> /// Instead of using the usual buffers, this bypasses any buffering and instructs the layers /// to draw directly to the specified target rectangle on the graphics object. This is useful /// for doing vector drawing on much larger pages. The result will be centered in the /// specified target rectangle bounds. /// </summary> /// <param name="device">Graphics device to print to</param> /// <param name="targetRectangle">The target rectangle in the graphics units of the device</param> void Print(Graphics device, Rectangle targetRectangle); /// <summary> /// Instead of using the usual buffers, this bypasses any buffering and instructs the layers /// to draw directly to the specified target rectangle on the graphics object. This is useful /// for doing vector drawing on much larger pages. The result will be centered in the /// specified target rectangle bounds. /// </summary> /// <param name="device">Graphics object used for drawing.</param> /// <param name="targetRectangle">Rectangle to draw the content to.</param> /// <param name="targetEnvelope">the extents to draw to the target rectangle</param> void Print(Graphics device, Rectangle targetRectangle, Extent targetEnvelope, int iFactor = 1); /// <summary> /// Converts a single geographic location into the equivalent point on the /// screen relative to the top left corner of the map. /// </summary> /// <param name="location">The geographic position to transform</param> /// <returns>A Point with the new location.</returns> Point ProjToBuffer(Coordinate location); /// <summary> /// Converts a single geographic envelope into an equivalent Rectangle /// as it would be drawn on the screen. /// </summary> /// <param name="ext">The geographic Envelope</param> /// <returns>A Rectangle</returns> Rectangle ProjToBuffer(Extent ext); /// <summary> /// Re-creates the buffer based on the size of the control without changing /// the geographic extents. This is used after a resize operation. /// </summary> void ResetBuffer(); /// <summary> /// This is not called during a resize, but rather after panning or zooming where the /// view is used as a guide to update the extents. This will also call ResetBuffer. /// </summary> void ResetExtents(); /// <summary> /// Zooms in one notch, so that the scale becomes larger and the features become larger. /// </summary> void ZoomIn(); /// <summary> /// Zooms out one notch so that the scale becomes smaller and the features become smaller. /// </summary> void ZoomOut(); /// <summary> /// Zooms to the next extent of the map frame /// </summary> void ZoomToNext(); /// <summary> /// Zooms to the previous extent of the map frame /// </summary> void ZoomToPrevious(); //CGX double ComputeScaleFromExtent(); /// <summary> /// /// </summary> void ComputeExtentFromScale(double dScale); /// <summary> /// /// </summary> void ComputeExtentFromScale(double dScale, Point mousePosition); /// <summary> /// Gets or sets the map reference scale. /// </summary> double ReferenceScale { get; set; } /// <summary> /// Gets the map current scale. /// </summary> double CurrentScale { get; set; } /// <summary> /// gets or sets the map background color. /// </summary> Color BackgroundColor { get; set; } /// <summary> /// Gets or sets the map bookmarks. /// </summary> List<CBookmarks> Bookmarks { get; set; } //Fin CGX #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 Microsoft.Win32.SafeHandles; using System.Collections.Generic; using System.ComponentModel; using System.Globalization; using System.IO; using System.Security; using System.Text; using System.Threading; namespace System.Diagnostics { /// <devdoc> /// <para> /// Provides access to local and remote /// processes. Enables you to start and stop system processes. /// </para> /// </devdoc> public partial class Process : Component { private bool _haveProcessId; private int _processId; private bool _haveProcessHandle; private SafeProcessHandle _processHandle; private bool _isRemoteMachine; private string _machineName; private ProcessInfo _processInfo; private ProcessThreadCollection _threads; private ProcessModuleCollection _modules; private bool _haveWorkingSetLimits; private IntPtr _minWorkingSet; private IntPtr _maxWorkingSet; private bool _haveProcessorAffinity; private IntPtr _processorAffinity; private bool _havePriorityClass; private ProcessPriorityClass _priorityClass; private ProcessStartInfo _startInfo; private bool _watchForExit; private bool _watchingForExit; private EventHandler _onExited; private bool _exited; private int _exitCode; private DateTime? _startTime; private DateTime _exitTime; private bool _haveExitTime; private bool _priorityBoostEnabled; private bool _havePriorityBoostEnabled; private bool _raisedOnExited; private RegisteredWaitHandle _registeredWaitHandle; private WaitHandle _waitHandle; private StreamReader _standardOutput; private StreamWriter _standardInput; private StreamReader _standardError; private bool _disposed; private static object s_createProcessLock = new object(); private bool _standardInputAccessed; private StreamReadMode _outputStreamReadMode; private StreamReadMode _errorStreamReadMode; // Support for asynchronously reading streams public event DataReceivedEventHandler OutputDataReceived; public event DataReceivedEventHandler ErrorDataReceived; // Abstract the stream details internal AsyncStreamReader _output; internal AsyncStreamReader _error; internal bool _pendingOutputRead; internal bool _pendingErrorRead; #if FEATURE_TRACESWITCH internal static TraceSwitch _processTracing = #if DEBUG new TraceSwitch("processTracing", "Controls debug output from Process component"); #else null; #endif #endif /// <devdoc> /// <para> /// Initializes a new instance of the <see cref='System.Diagnostics.Process'/> class. /// </para> /// </devdoc> public Process() { // This class once inherited a finalizer. For backward compatibility it has one so that // any derived class that depends on it will see the behaviour expected. Since it is // not used by this class itself, suppress it immediately if this is not an instance // of a derived class it doesn't suffer the GC burden of finalization. if (GetType() == typeof(Process)) { GC.SuppressFinalize(this); } _machineName = "."; _outputStreamReadMode = StreamReadMode.Undefined; _errorStreamReadMode = StreamReadMode.Undefined; } private Process(string machineName, bool isRemoteMachine, int processId, ProcessInfo processInfo) { GC.SuppressFinalize(this); _processInfo = processInfo; _machineName = machineName; _isRemoteMachine = isRemoteMachine; _processId = processId; _haveProcessId = true; _outputStreamReadMode = StreamReadMode.Undefined; _errorStreamReadMode = StreamReadMode.Undefined; } public SafeProcessHandle SafeHandle { get { EnsureState(State.Associated); return OpenProcessHandle(); } } public IntPtr Handle => SafeHandle.DangerousGetHandle(); /// <devdoc> /// Returns whether this process component is associated with a real process. /// </devdoc> /// <internalonly/> bool Associated { get { return _haveProcessId || _haveProcessHandle; } } /// <devdoc> /// <para> /// Gets the base priority of /// the associated process. /// </para> /// </devdoc> public int BasePriority { get { EnsureState(State.HaveProcessInfo); return _processInfo.BasePriority; } } /// <devdoc> /// <para> /// Gets /// the /// value that was specified by the associated process when it was terminated. /// </para> /// </devdoc> public int ExitCode { get { EnsureState(State.Exited); return _exitCode; } } /// <devdoc> /// <para> /// Gets a /// value indicating whether the associated process has been terminated. /// </para> /// </devdoc> public bool HasExited { get { if (!_exited) { EnsureState(State.Associated); UpdateHasExited(); if (_exited) { RaiseOnExited(); } } return _exited; } } /// <summary>Gets the time the associated process was started.</summary> public DateTime StartTime { get { if (!_startTime.HasValue) { _startTime = StartTimeCore; } return _startTime.Value; } } /// <devdoc> /// <para> /// Gets the time that the associated process exited. /// </para> /// </devdoc> public DateTime ExitTime { get { if (!_haveExitTime) { EnsureState(State.Exited); _exitTime = ExitTimeCore; _haveExitTime = true; } return _exitTime; } } /// <devdoc> /// <para> /// Gets /// the unique identifier for the associated process. /// </para> /// </devdoc> public int Id { get { EnsureState(State.HaveId); return _processId; } } /// <devdoc> /// <para> /// Gets /// the name of the computer on which the associated process is running. /// </para> /// </devdoc> public string MachineName { get { EnsureState(State.Associated); return _machineName; } } /// <devdoc> /// <para> /// Gets or sets the maximum allowable working set for the associated /// process. /// </para> /// </devdoc> public IntPtr MaxWorkingSet { get { EnsureWorkingSetLimits(); return _maxWorkingSet; } set { SetWorkingSetLimits(null, value); } } /// <devdoc> /// <para> /// Gets or sets the minimum allowable working set for the associated /// process. /// </para> /// </devdoc> public IntPtr MinWorkingSet { get { EnsureWorkingSetLimits(); return _minWorkingSet; } set { SetWorkingSetLimits(value, null); } } public ProcessModuleCollection Modules { get { if (_modules == null) { EnsureState(State.HaveId | State.IsLocal); _modules = ProcessManager.GetModules(_processId); } return _modules; } } public long NonpagedSystemMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PoolNonPagedBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.NonpagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int NonpagedSystemMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PoolNonPagedBytes); } } public long PagedMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PageFileBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PagedMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PageFileBytes); } } public long PagedSystemMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PoolPagedBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PagedSystemMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PagedSystemMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PoolPagedBytes); } } public long PeakPagedMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PageFileBytesPeak; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakPagedMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakPagedMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PageFileBytesPeak); } } public long PeakWorkingSet64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.WorkingSetPeak; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakWorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakWorkingSet { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.WorkingSetPeak); } } public long PeakVirtualMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.VirtualBytesPeak; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PeakVirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PeakVirtualMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.VirtualBytesPeak); } } /// <devdoc> /// <para> /// Gets or sets a value indicating whether the associated process priority /// should be temporarily boosted by the operating system when the main window /// has focus. /// </para> /// </devdoc> public bool PriorityBoostEnabled { get { if (!_havePriorityBoostEnabled) { _priorityBoostEnabled = PriorityBoostEnabledCore; _havePriorityBoostEnabled = true; } return _priorityBoostEnabled; } set { PriorityBoostEnabledCore = value; _priorityBoostEnabled = value; _havePriorityBoostEnabled = true; } } /// <devdoc> /// <para> /// Gets or sets the overall priority category for the /// associated process. /// </para> /// </devdoc> public ProcessPriorityClass PriorityClass { get { if (!_havePriorityClass) { _priorityClass = PriorityClassCore; _havePriorityClass = true; } return _priorityClass; } set { if (!Enum.IsDefined(typeof(ProcessPriorityClass), value)) { throw new InvalidEnumArgumentException(nameof(value), (int)value, typeof(ProcessPriorityClass)); } PriorityClassCore = value; _priorityClass = value; _havePriorityClass = true; } } public long PrivateMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.PrivateBytes; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.PrivateMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int PrivateMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.PrivateBytes); } } /// <devdoc> /// <para> /// Gets /// the friendly name of the process. /// </para> /// </devdoc> public string ProcessName { get { EnsureState(State.HaveProcessInfo); return _processInfo.ProcessName; } } /// <devdoc> /// <para> /// Gets /// or sets which processors the threads in this process can be scheduled to run on. /// </para> /// </devdoc> public IntPtr ProcessorAffinity { get { if (!_haveProcessorAffinity) { _processorAffinity = ProcessorAffinityCore; _haveProcessorAffinity = true; } return _processorAffinity; } set { ProcessorAffinityCore = value; _processorAffinity = value; _haveProcessorAffinity = true; } } public int SessionId { get { EnsureState(State.HaveProcessInfo); return _processInfo.SessionId; } } /// <devdoc> /// <para> /// Gets or sets the properties to pass into the <see cref='System.Diagnostics.Process.Start'/> method for the <see cref='System.Diagnostics.Process'/> /// . /// </para> /// </devdoc> public ProcessStartInfo StartInfo { get { if (_startInfo == null) { if (Associated) { throw new InvalidOperationException(SR.CantGetProcessStartInfo); } _startInfo = new ProcessStartInfo(); } return _startInfo; } set { if (value == null) { throw new ArgumentNullException(nameof(value)); } if (Associated) { throw new InvalidOperationException(SR.CantSetProcessStartInfo); } _startInfo = value; } } /// <devdoc> /// <para> /// Gets the set of threads that are running in the associated /// process. /// </para> /// </devdoc> public ProcessThreadCollection Threads { get { if (_threads == null) { EnsureState(State.HaveProcessInfo); int count = _processInfo._threadInfoList.Count; ProcessThread[] newThreadsArray = new ProcessThread[count]; for (int i = 0; i < count; i++) { newThreadsArray[i] = new ProcessThread(_isRemoteMachine, _processId, (ThreadInfo)_processInfo._threadInfoList[i]); } ProcessThreadCollection newThreads = new ProcessThreadCollection(newThreadsArray); _threads = newThreads; } return _threads; } } public int HandleCount { get { EnsureState(State.HaveProcessInfo); EnsureHandleCountPopulated(); return _processInfo.HandleCount; } } partial void EnsureHandleCountPopulated(); [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.VirtualMemorySize64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public long VirtualMemorySize64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.VirtualBytes; } } public int VirtualMemorySize { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.VirtualBytes); } } /// <devdoc> /// <para> /// Gets or sets whether the <see cref='System.Diagnostics.Process.Exited'/> /// event is fired /// when the process terminates. /// </para> /// </devdoc> public bool EnableRaisingEvents { get { return _watchForExit; } set { if (value != _watchForExit) { if (Associated) { if (value) { OpenProcessHandle(); EnsureWatchingForExit(); } else { StopWatchingForExit(); } } _watchForExit = value; } } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamWriter StandardInput { get { if (_standardInput == null) { throw new InvalidOperationException(SR.CantGetStandardIn); } _standardInputAccessed = true; return _standardInput; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamReader StandardOutput { get { if (_standardOutput == null) { throw new InvalidOperationException(SR.CantGetStandardOut); } if (_outputStreamReadMode == StreamReadMode.Undefined) { _outputStreamReadMode = StreamReadMode.SyncMode; } else if (_outputStreamReadMode != StreamReadMode.SyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } return _standardOutput; } } /// <devdoc> /// <para>[To be supplied.]</para> /// </devdoc> public StreamReader StandardError { get { if (_standardError == null) { throw new InvalidOperationException(SR.CantGetStandardError); } if (_errorStreamReadMode == StreamReadMode.Undefined) { _errorStreamReadMode = StreamReadMode.SyncMode; } else if (_errorStreamReadMode != StreamReadMode.SyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } return _standardError; } } public long WorkingSet64 { get { EnsureState(State.HaveProcessInfo); return _processInfo.WorkingSet; } } [ObsoleteAttribute("This property has been deprecated. Please use System.Diagnostics.Process.WorkingSet64 instead. http://go.microsoft.com/fwlink/?linkid=14202")] public int WorkingSet { get { EnsureState(State.HaveProcessInfo); return unchecked((int)_processInfo.WorkingSet); } } public event EventHandler Exited { add { _onExited += value; } remove { _onExited -= value; } } /// <devdoc> /// This is called from the threadpool when a process exits. /// </devdoc> /// <internalonly/> private void CompletionCallback(object context, bool wasSignaled) { StopWatchingForExit(); RaiseOnExited(); } /// <internalonly/> /// <devdoc> /// <para> /// Free any resources associated with this component. /// </para> /// </devdoc> protected override void Dispose(bool disposing) { if (!_disposed) { if (disposing) { //Dispose managed and unmanaged resources Close(); } _disposed = true; } } public bool CloseMainWindow() { return CloseMainWindowCore(); } public bool WaitForInputIdle() { return WaitForInputIdle(int.MaxValue); } public bool WaitForInputIdle(int milliseconds) { return WaitForInputIdleCore(milliseconds); } public ISynchronizeInvoke SynchronizingObject { get; set; } /// <devdoc> /// <para> /// Frees any resources associated with this component. /// </para> /// </devdoc> public void Close() { if (Associated) { if (_haveProcessHandle) { StopWatchingForExit(); #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process - CloseHandle(process) in Close()"); #endif _processHandle.Dispose(); _processHandle = null; _haveProcessHandle = false; } _haveProcessId = false; _isRemoteMachine = false; _machineName = "."; _raisedOnExited = false; // Only call close on the streams if the user cannot have a reference on them. // If they are referenced it is the user's responsibility to dispose of them. try { if (_standardOutput != null && (_outputStreamReadMode == StreamReadMode.AsyncMode || _outputStreamReadMode == StreamReadMode.Undefined)) { if (_outputStreamReadMode == StreamReadMode.AsyncMode) { _output.CancelOperation(); } _standardOutput.Close(); } if (_standardError != null && (_errorStreamReadMode == StreamReadMode.AsyncMode || _errorStreamReadMode == StreamReadMode.Undefined)) { if (_errorStreamReadMode == StreamReadMode.AsyncMode) { _error.CancelOperation(); } _standardError.Close(); } if (_standardInput != null && !_standardInputAccessed) { _standardInput.Close(); } } finally { _standardOutput = null; _standardInput = null; _standardError = null; _output = null; _error = null; CloseCore(); Refresh(); } } } /// <devdoc> /// Helper method for checking preconditions when accessing properties. /// </devdoc> /// <internalonly/> private void EnsureState(State state) { if ((state & State.Associated) != (State)0) if (!Associated) throw new InvalidOperationException(SR.NoAssociatedProcess); if ((state & State.HaveId) != (State)0) { if (!_haveProcessId) { if (_haveProcessHandle) { SetProcessId(ProcessManager.GetProcessIdFromHandle(_processHandle)); } else { EnsureState(State.Associated); throw new InvalidOperationException(SR.ProcessIdRequired); } } } if ((state & State.IsLocal) != (State)0 && _isRemoteMachine) { throw new NotSupportedException(SR.NotSupportedRemote); } if ((state & State.HaveProcessInfo) != (State)0) { if (_processInfo == null) { if ((state & State.HaveId) == (State)0) EnsureState(State.HaveId); _processInfo = ProcessManager.GetProcessInfo(_processId, _machineName); if (_processInfo == null) { throw new InvalidOperationException(SR.NoProcessInfo); } } } if ((state & State.Exited) != (State)0) { if (!HasExited) { throw new InvalidOperationException(SR.WaitTillExit); } if (!_haveProcessHandle) { throw new InvalidOperationException(SR.NoProcessHandle); } } } /// <devdoc> /// Make sure we have obtained the min and max working set limits. /// </devdoc> /// <internalonly/> private void EnsureWorkingSetLimits() { if (!_haveWorkingSetLimits) { GetWorkingSetLimits(out _minWorkingSet, out _maxWorkingSet); _haveWorkingSetLimits = true; } } /// <devdoc> /// Helper to set minimum or maximum working set limits. /// </devdoc> /// <internalonly/> private void SetWorkingSetLimits(IntPtr? min, IntPtr? max) { SetWorkingSetLimitsCore(min, max, out _minWorkingSet, out _maxWorkingSet); _haveWorkingSetLimits = true; } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> component given a process identifier and /// the name of a computer in the network. /// </para> /// </devdoc> public static Process GetProcessById(int processId, string machineName) { if (!ProcessManager.IsProcessRunning(processId, machineName)) { throw new ArgumentException(SR.Format(SR.MissingProccess, processId.ToString(CultureInfo.CurrentCulture))); } return new Process(machineName, ProcessManager.IsRemoteMachine(machineName), processId, null); } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> component given the /// identifier of a process on the local computer. /// </para> /// </devdoc> public static Process GetProcessById(int processId) { return GetProcessById(processId, "."); } /// <devdoc> /// <para> /// Creates an array of <see cref='System.Diagnostics.Process'/> components that are /// associated /// with process resources on the /// local computer. These process resources share the specified process name. /// </para> /// </devdoc> public static Process[] GetProcessesByName(string processName) { return GetProcessesByName(processName, "."); } /// <devdoc> /// <para> /// Creates a new <see cref='System.Diagnostics.Process'/> /// component for each process resource on the local computer. /// </para> /// </devdoc> public static Process[] GetProcesses() { return GetProcesses("."); } /// <devdoc> /// <para> /// Creates a new <see cref='System.Diagnostics.Process'/> /// component for each /// process resource on the specified computer. /// </para> /// </devdoc> public static Process[] GetProcesses(string machineName) { bool isRemoteMachine = ProcessManager.IsRemoteMachine(machineName); ProcessInfo[] processInfos = ProcessManager.GetProcessInfos(machineName); Process[] processes = new Process[processInfos.Length]; for (int i = 0; i < processInfos.Length; i++) { ProcessInfo processInfo = processInfos[i]; processes[i] = new Process(machineName, isRemoteMachine, processInfo.ProcessId, processInfo); } #if FEATURE_TRACESWITCH Debug.WriteLineIf(_processTracing.TraceVerbose, "Process.GetProcesses(" + machineName + ")"); #if DEBUG if (_processTracing.TraceVerbose) { Debug.Indent(); for (int i = 0; i < processInfos.Length; i++) { Debug.WriteLine(processes[i].Id + ": " + processes[i].ProcessName); } Debug.Unindent(); } #endif #endif return processes; } /// <devdoc> /// <para> /// Returns a new <see cref='System.Diagnostics.Process'/> /// component and associates it with the current active process. /// </para> /// </devdoc> public static Process GetCurrentProcess() { return new Process(".", false, GetCurrentProcessId(), null); } /// <devdoc> /// <para> /// Raises the <see cref='System.Diagnostics.Process.Exited'/> event. /// </para> /// </devdoc> protected void OnExited() { EventHandler exited = _onExited; if (exited != null) { exited(this, EventArgs.Empty); } } /// <devdoc> /// Raise the Exited event, but make sure we don't do it more than once. /// </devdoc> /// <internalonly/> private void RaiseOnExited() { if (!_raisedOnExited) { lock (this) { if (!_raisedOnExited) { _raisedOnExited = true; OnExited(); } } } } /// <devdoc> /// <para> /// Discards any information about the associated process /// that has been cached inside the process component. After <see cref='System.Diagnostics.Process.Refresh'/> is called, the /// first request for information for each property causes the process component /// to obtain a new value from the associated process. /// </para> /// </devdoc> public void Refresh() { _processInfo = null; _threads = null; _modules = null; _exited = false; _haveWorkingSetLimits = false; _haveProcessorAffinity = false; _havePriorityClass = false; _haveExitTime = false; _havePriorityBoostEnabled = false; RefreshCore(); } /// <summary> /// Opens a long-term handle to the process, with all access. If a handle exists, /// then it is reused. If the process has exited, it throws an exception. /// </summary> private SafeProcessHandle OpenProcessHandle() { if (!_haveProcessHandle) { //Cannot open a new process handle if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } SetProcessHandle(GetProcessHandle()); } return _processHandle; } /// <devdoc> /// Helper to associate a process handle with this component. /// </devdoc> /// <internalonly/> private void SetProcessHandle(SafeProcessHandle processHandle) { _processHandle = processHandle; _haveProcessHandle = true; if (_watchForExit) { EnsureWatchingForExit(); } } /// <devdoc> /// Helper to associate a process id with this component. /// </devdoc> /// <internalonly/> private void SetProcessId(int processId) { _processId = processId; _haveProcessId = true; ConfigureAfterProcessIdSet(); } /// <summary>Additional optional configuration hook after a process ID is set.</summary> partial void ConfigureAfterProcessIdSet(); /// <devdoc> /// <para> /// Starts a process specified by the <see cref='System.Diagnostics.Process.StartInfo'/> property of this <see cref='System.Diagnostics.Process'/> /// component and associates it with the /// <see cref='System.Diagnostics.Process'/> . If a process resource is reused /// rather than started, the reused process is associated with this <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public bool Start() { Close(); ProcessStartInfo startInfo = StartInfo; if (startInfo.FileName.Length == 0) { throw new InvalidOperationException(SR.FileNameMissing); } if (startInfo.StandardInputEncoding != null && !startInfo.RedirectStandardInput) { throw new InvalidOperationException(SR.StandardInputEncodingNotAllowed); } if (startInfo.StandardOutputEncoding != null && !startInfo.RedirectStandardOutput) { throw new InvalidOperationException(SR.StandardOutputEncodingNotAllowed); } if (startInfo.StandardErrorEncoding != null && !startInfo.RedirectStandardError) { throw new InvalidOperationException(SR.StandardErrorEncodingNotAllowed); } //Cannot start a new process and store its handle if the object has been disposed, since finalization has been suppressed. if (_disposed) { throw new ObjectDisposedException(GetType().Name); } return StartCore(startInfo); } /// <devdoc> /// <para> /// Starts a process resource by specifying the name of a /// document or application file. Associates the process resource with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(string fileName) { return Start(new ProcessStartInfo(fileName)); } /// <devdoc> /// <para> /// Starts a process resource by specifying the name of an /// application and a set of command line arguments. Associates the process resource /// with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(string fileName, string arguments) { return Start(new ProcessStartInfo(fileName, arguments)); } /// <devdoc> /// <para> /// Starts a process resource specified by the process start /// information passed in, for example the file name of the process to start. /// Associates the process resource with a new <see cref='System.Diagnostics.Process'/> /// component. /// </para> /// </devdoc> public static Process Start(ProcessStartInfo startInfo) { Process process = new Process(); if (startInfo == null) throw new ArgumentNullException(nameof(startInfo)); process.StartInfo = startInfo; return process.Start() ? process : null; } /// <devdoc> /// Make sure we are not watching for process exit. /// </devdoc> /// <internalonly/> private void StopWatchingForExit() { if (_watchingForExit) { RegisteredWaitHandle rwh = null; WaitHandle wh = null; lock (this) { if (_watchingForExit) { _watchingForExit = false; wh = _waitHandle; _waitHandle = null; rwh = _registeredWaitHandle; _registeredWaitHandle = null; } } if (rwh != null) { rwh.Unregister(null); } if (wh != null) { wh.Dispose(); } } } public override string ToString() { if (Associated) { string processName = ProcessName; if (processName.Length != 0) { return String.Format(CultureInfo.CurrentCulture, "{0} ({1})", base.ToString(), processName); } } return base.ToString(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to wait /// indefinitely for the associated process to exit. /// </para> /// </devdoc> public void WaitForExit() { WaitForExit(Timeout.Infinite); } /// <summary> /// Instructs the Process component to wait the specified number of milliseconds for /// the associated process to exit. /// </summary> public bool WaitForExit(int milliseconds) { bool exited = WaitForExitCore(milliseconds); if (exited && _watchForExit) { RaiseOnExited(); } return exited; } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to start /// reading the StandardOutput stream asynchronously. The user can register a callback /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached /// then the remaining information is returned. The user can add an event handler to OutputDataReceived. /// </para> /// </devdoc> public void BeginOutputReadLine() { if (_outputStreamReadMode == StreamReadMode.Undefined) { _outputStreamReadMode = StreamReadMode.AsyncMode; } else if (_outputStreamReadMode != StreamReadMode.AsyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } if (_pendingOutputRead) throw new InvalidOperationException(SR.PendingAsyncOperation); _pendingOutputRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. if (_output == null) { if (_standardOutput == null) { throw new InvalidOperationException(SR.CantGetStandardOut); } Stream s = _standardOutput.BaseStream; _output = new AsyncStreamReader(s, OutputReadNotifyUser, _standardOutput.CurrentEncoding); } _output.BeginReadLine(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to start /// reading the StandardError stream asynchronously. The user can register a callback /// that will be called when a line of data terminated by \n,\r or \r\n is reached, or the end of stream is reached /// then the remaining information is returned. The user can add an event handler to ErrorDataReceived. /// </para> /// </devdoc> public void BeginErrorReadLine() { if (_errorStreamReadMode == StreamReadMode.Undefined) { _errorStreamReadMode = StreamReadMode.AsyncMode; } else if (_errorStreamReadMode != StreamReadMode.AsyncMode) { throw new InvalidOperationException(SR.CantMixSyncAsyncOperation); } if (_pendingErrorRead) { throw new InvalidOperationException(SR.PendingAsyncOperation); } _pendingErrorRead = true; // We can't detect if there's a pending synchronous read, stream also doesn't. if (_error == null) { if (_standardError == null) { throw new InvalidOperationException(SR.CantGetStandardError); } Stream s = _standardError.BaseStream; _error = new AsyncStreamReader(s, ErrorReadNotifyUser, _standardError.CurrentEncoding); } _error.BeginReadLine(); } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation /// specified by BeginOutputReadLine(). /// </para> /// </devdoc> public void CancelOutputRead() { if (_output != null) { _output.CancelOperation(); } else { throw new InvalidOperationException(SR.NoAsyncOperation); } _pendingOutputRead = false; } /// <devdoc> /// <para> /// Instructs the <see cref='System.Diagnostics.Process'/> component to cancel the asynchronous operation /// specified by BeginErrorReadLine(). /// </para> /// </devdoc> public void CancelErrorRead() { if (_error != null) { _error.CancelOperation(); } else { throw new InvalidOperationException(SR.NoAsyncOperation); } _pendingErrorRead = false; } internal void OutputReadNotifyUser(String data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler outputDataReceived = OutputDataReceived; if (outputDataReceived != null) { DataReceivedEventArgs e = new DataReceivedEventArgs(data); outputDataReceived(this, e); // Call back to user informing data is available } } internal void ErrorReadNotifyUser(String data) { // To avoid race between remove handler and raising the event DataReceivedEventHandler errorDataReceived = ErrorDataReceived; if (errorDataReceived != null) { DataReceivedEventArgs e = new DataReceivedEventArgs(data); errorDataReceived(this, e); // Call back to user informing data is available. } } /// <summary> /// This enum defines the operation mode for redirected process stream. /// We don't support switching between synchronous mode and asynchronous mode. /// </summary> private enum StreamReadMode { Undefined, SyncMode, AsyncMode } /// <summary>A desired internal state.</summary> private enum State { HaveId = 0x1, IsLocal = 0x2, HaveProcessInfo = 0x8, Exited = 0x10, Associated = 0x20, } } }
using System; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.DependencyInjection; using Dotnettency; using Microsoft.Extensions.Hosting; using Microsoft.AspNetCore.Http; using System.Threading.Tasks; using Microsoft.Extensions.Logging; namespace Sample.Pages { public class Startup { [Obsolete] public Startup(IConfiguration configuration, IWebHostEnvironment environment) { Configuration = configuration; Environment = environment; } public IConfiguration Configuration { get; } public IWebHostEnvironment Environment { get; } // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { // var defaultServices = services.Clone(); services.Configure<CookiePolicyOptions>(options => { // This lambda determines whether user consent for non-essential cookies is needed for a given request. options.CheckConsentNeeded = context => true; }); services.AddSingleton<IHttpContextAccessor, HttpContextAccessor>(); IConfigurationSection configSection = Configuration.GetSection("Tenants"); services.Configure<TenantMappingOptions<int>>(configSection); services.AddMultiTenancy<Tenant>((builder) => { builder //.IdentifyTenantsWithRequestAuthorityUri() //.InitialiseTenant<TenantShellFactory>() .AddAspNetCore() .IdentifyFromHttpContext<int>((m) => { m.MapValue(http => http.Request.GetUri().Port.ToString()) .UsingDotNetGlobPatternMatching() .Initialise(key => { Tenant result = null; switch (key) { case 1: result = new Tenant(Guid.Parse("049c8cc4-3660-41c7-92f0-85430452be22")) { Name = "Gicrosoft" }; break; case 2: result = new Tenant(Guid.Parse("b17fcd22-0db1-47c0-9fef-1aa1cb09605e")) { Name = "Moogle" }; break; case 3: result = null; break; } return Task.FromResult(result); }); }) .ConfigureNamedTenantFileSystems((namedItems) => { var contentFileProvider = Environment.ContentRootFileProvider; var webFileProvider = Environment.WebRootFileProvider; namedItems.AddWebFileSystem(Environment.WebRootPath, (ctx, fs) => { Guid tenantGuid = (ctx.Tenant?.TenantGuid).GetValueOrDefault(); fs.SetPartitionId(tenantGuid) .SetSubDirectory(".tenants\\") .AllowAccessTo(webFileProvider); }) .UseAsEnvironmentWebRootFileProvider(Environment) .AddContentFileSystem(Environment.ContentRootPath, (ctx, fs) => { Guid tenantGuid = (ctx.Tenant?.TenantGuid).GetValueOrDefault(); fs.SetPartitionId(tenantGuid) .SetSubDirectory(".tenants\\") .AllowAccessTo(contentFileProvider); }) .UseAsEnvironmentContentRootFileProvider(Environment); }) .ConfigureTenantConfiguration((a, tenantConfig) => { tenantConfig.AddJsonFile(Environment.ContentRootFileProvider, $"/appsettings.{a.Tenant?.Name}.json", true, true); }) .ConfigureTenantContainers((containerOptions) => { containerOptions // .SetDefaultServices(defaultServices) .UseTenantHostedServices((m) => { // If you have registered IHostedService's at application level // each tenant will also have access to them, to // avoid each tenant from also running them you can exclude them here. //m.Remove<MyGlobalHostedService>().Remove<MyOtherGlobalHostedService>(); }) // Can now regiser IHostedService in tenant level. .AutofacAsync(async (tenantContext, tenantServices) => { // Can now use tenant level configuration to decide how to bootstrap the tenants services here.. var currentTenantConfig = await tenantContext.GetConfigurationAsync(); var someTenantConfigSetting = currentTenantConfig.GetValue<bool>("SomeSetting"); if (someTenantConfigSetting) { // register services certain way for this tenant. } if (tenantContext.Tenant != null) { tenantServices.AddRazorPages((o) => { o.RootDirectory = $"/Pages/{tenantContext.Tenant.Name}"; }).AddNewtonsoftJson(); // demonstrates registering IHostedService at per tenant level tenantServices.AddHostedService<TimedTenantHostedService>(); // Example of overriding logging at root level for a tenant if (tenantContext.Tenant.Name == "Moogle") { tenantServices.AddLoggingFactory(b => b.ClearProviders().SetMinimumLevel(LogLevel.Debug) .AddDebug()); } else { tenantServices.AddLoggingFactory(b => b.ClearProviders().SetMinimumLevel(LogLevel.Information)); } } }); }) .ConfigureTenantMiddleware((tenantOptions) => { tenantOptions.AspNetCorePipelineTask(async (context, tenantAppBuilder) => { var tenantConfig = await context.GetConfigurationAsync(); var someTenantConfigSetting = tenantConfig.GetValue<bool>("SomeSetting"); if (someTenantConfigSetting) { // register services certain way for this tenant. } // Example of using your own custom tenant shell items. // Check out the ConfigureTenantShellItem<> below. // You can also inject Task<ExampleShellItem> into controllers etc. // ExampleShellItem will be lazily constructed only per tenant, or once after a tenant restart. var exampleShellItemTask = await context.GetShellItemAsync<Task<ExampleShellItem>>(); var exampleShellItem = await exampleShellItemTask; if (exampleShellItem.Colour != "indigo") { throw new Exception("wrong named item was retrieved.."); } var redShellItem = await context.GetShellItemAsync<ExampleShellItem>("red"); if (redShellItem.Colour != "red") { throw new Exception("wrong named item was retrieved.."); } var blueShellItem = await context.GetShellItemAsync<ExampleShellItem>("blue"); if (blueShellItem.Colour != "blue") { throw new Exception("wrong named item was retrieved.."); } tenantAppBuilder.Use(async (c, next) => { var logger = c.RequestServices.GetRequiredService<ILogger<Startup>>(); logger.LogDebug("Debug log in middleware."); // This is some middleware running in the tenant pipeline. Console.WriteLine("Running in tenant pipeline: " + context.Tenant?.Name); await next.Invoke(); }); tenantAppBuilder.UseRouting(); if (context.Tenant != null) { tenantAppBuilder.UseAuthorization(); tenantAppBuilder.Use(async (c, next) => { // Demonstrates per tenant files. // /foo.txt exists for one tenant but not another. var webHostEnvironment = c.RequestServices.GetRequiredService<IWebHostEnvironment>(); var contentFileProvider = webHostEnvironment.ContentRootFileProvider; var webFileProvider = webHostEnvironment.WebRootFileProvider; var fooTextFile = webFileProvider.GetFileInfo("/foo.txt"); Console.WriteLine($"/Foo.txt file exists? {fooTextFile.Exists}"); // Demonstrates per tenant config. // SomeSetting is true for Moogle tenant but not other tenants. Console.WriteLine($"Tenant config setting: {someTenantConfigSetting}"); await next.Invoke(); }); tenantAppBuilder.UseEndpoints(endpoints => { endpoints.MapRazorPages(); }); } }); }) .ConfigureTenantShellItem(async (b) => { // Example - you can configure your own arbitrary shell items // This item will be lazily constructed once per tenant, and stored in tenant shell, and // optionally disposed of if tenant is restarted (if implements IDisposable). var exampleItem1 = await b.GetConfigurationAsync(); return new ExampleShellItem(b.Tenant?.Name ?? "NULL TENANT") { Colour = "indigo" }; // To access this item, you can do either / all of: // 1. Inject Task<ExampleShellItem> into your controllers etc, then await that task where needed. // 2. Inject ITenantShellItemAccessor<ExampleShellItem> then await it's lazy factory task. // 3. Use IServiceProvider extension method e.g: await ApplicationServices.GetShellItemAsync<Tenant, ExampleShellItem>(); // 4. In startup methods above, use "await context.GetShellItemAsync<ExampleShellItem>()" as shown in the middleware example. // Note: Tenant shell items are removed from the Tenant Shell if the tenant is restarted. // and then lazily re-initialised again when first consumed after the tenant restart // Another Note: If your service implements IDisposable, it will also be disposed of, when the tenant is restarted. // (That's the convention for any item stored in Tenant Shell) }) .ConfigureNamedTenantShellItems<Tenant, ExampleShellItem>((b) => { b.Add("red", (c) => new ExampleShellItem(c.Tenant?.Name ?? "NULL TENANT") { Colour = "red" }); b.Add("blue", (c) => new ExampleShellItem(c.Tenant?.Name ?? "NULL TENANT") { Colour = "blue" }); }); }); } public class ExampleShellItem { public ExampleShellItem(string tenantName) { TenantName = tenantName; Console.WriteLine($"ExampleShellItem constructed for tenant: {tenantName}"); } public string TenantName { get; set; } public string Colour { get; set; } } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IWebHostEnvironment env) { if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseExceptionHandler("/Error"); // The default HSTS value is 30 days. You may want to change this for production scenarios, see https://aka.ms/aspnetcore-hsts. app.UseHsts(); } app.UseHttpsRedirection(); app.UseStaticFiles(); app.UseCookiePolicy(); app.UseMultitenancy<Tenant>((builder) => { builder.UseTenantContainers() .UsePerTenantMiddlewarePipeline(app); }); } } public class ExampleShellItem2 { } public class ExampleShellItem3 { } }
//----------------------------------------------------------------------- // <copyright file="BasicChat.cs" company="AllSeen Alliance."> // Copyright (c) 2012, AllSeen Alliance. All rights reserved. // // Permission to use, copy, modify, and/or distribute this software for any // purpose with or without fee is hereby granted, provided that the above // copyright notice and this permission notice appear in all copies. // // THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES // WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF // MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR // ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES // WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN // ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF // OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE. // </copyright> //----------------------------------------------------------------------- using UnityEngine; using AllJoynUnity; using System.Runtime.InteropServices; using System.Collections; namespace basic_clientserver { class BasicChat { private const string INTERFACE_NAME = "org.alljoyn.bus.chat"; private const string SERVICE_NAME = "org.alljoyn.bus.chat"; private const string SERVICE_PATH = "/chat"; private const ushort SERVICE_PORT = 25; private static readonly string[] connectArgs = {"unix:abstract=alljoyn", "tcp:addr=127.0.0.1,port=9955", "launchd:"}; private string connectedVal; private static AllJoyn.BusAttachment msgBus; private MyBusListener busListener; private MySessionPortListener sessionPortListener; private static MySessionListener sessionListener; private static TestBusObject testObj; private AllJoyn.InterfaceDescription testIntf; public static string chatText = ""; public AllJoyn.SessionOpts opts; public static ArrayList sFoundName = new ArrayList(); public static string currentJoinedSession = null; private static uint currentSessionId = 0; private static string myAdvertisedName = null; public static bool AllJoynStarted = false; class TestBusObject : AllJoyn.BusObject { private AllJoyn.InterfaceDescription.Member chatMember; public TestBusObject(AllJoyn.BusAttachment bus, string path) : base(bus, path, false) { AllJoyn.InterfaceDescription exampleIntf = bus.GetInterface(INTERFACE_NAME); AllJoyn.QStatus status = AddInterface(exampleIntf); if(!status) { chatText = "Chat Failed to add interface " + status.ToString() + "\n" + chatText; Debug.Log("Chat Failed to add interface " + status.ToString()); } chatMember = exampleIntf.GetMember("chat"); } protected override void OnObjectRegistered () { chatText = "Chat ObjectRegistered has been called\n" + chatText; Debug.Log("Chat ObjectRegistered has been called"); } public void SendChatSignal(string msg) { AllJoyn.MsgArgs payload = new AllJoyn.MsgArgs(1); payload[0].Set(msg); AllJoyn.QStatus status = Signal(null, currentSessionId, chatMember, payload, 0, 64); if(!status) { Debug.Log("Chat failed to send signal: "+status.ToString()); } } } class MyBusListener : AllJoyn.BusListener { protected override void FoundAdvertisedName(string name, AllJoyn.TransportMask transport, string namePrefix) { chatText = "Chat FoundAdvertisedName(name=" + name + ", prefix=" + namePrefix + ")\n" + chatText; Debug.Log("Chat FoundAdvertisedName(name=" + name + ", prefix=" + namePrefix + ")"); if(string.Compare(myAdvertisedName, name) == 0) { chatText = "Ignoring my advertisement\n" + chatText; Debug.Log("Ignoring my advertisement"); } else if(string.Compare(SERVICE_NAME, namePrefix) == 0) { sFoundName.Add(name); } } protected override void ListenerRegistered(AllJoyn.BusAttachment busAttachment) { chatText = "Chat ListenerRegistered: busAttachment=" + busAttachment + "\n" + chatText; Debug.Log("Chat ListenerRegistered: busAttachment=" + busAttachment); } protected override void NameOwnerChanged(string busName, string previousOwner, string newOwner) { //if(string.Compare(SERVICE_NAME, busName) == 0) { chatText = "Chat NameOwnerChanged: name=" + busName + ", oldOwner=" + previousOwner + ", newOwner=" + newOwner + "\n" + chatText; Debug.Log("Chat NameOwnerChanged: name=" + busName + ", oldOwner=" + previousOwner + ", newOwner=" + newOwner); } } protected override void LostAdvertisedName(string name, AllJoyn.TransportMask transport, string namePrefix) { chatText = "Chat LostAdvertisedName(name=" + name + ", prefix=" + namePrefix + ")\n" + chatText; Debug.Log("Chat LostAdvertisedName(name=" + name + ", prefix=" + namePrefix + ")"); sFoundName.Remove(name); } } class MySessionPortListener : AllJoyn.SessionPortListener { protected override bool AcceptSessionJoiner(ushort sessionPort, string joiner, AllJoyn.SessionOpts opts) { if (sessionPort != SERVICE_PORT) { chatText = "Chat Rejecting join attempt on unexpected session port " + sessionPort + "\n" + chatText; Debug.Log("Chat Rejecting join attempt on unexpected session port " + sessionPort); return false; } chatText = "Chat Accepting join session request from " + joiner + " (opts.proximity=" + opts.Proximity + ", opts.traffic=" + opts.Traffic + ", opts.transports=" + opts.Transports + ")\n" + chatText; Debug.Log("Chat Accepting join session request from " + joiner + " (opts.proximity=" + opts.Proximity + ", opts.traffic=" + opts.Traffic + ", opts.transports=" + opts.Transports + ")"); return true; } protected override void SessionJoined(ushort sessionPort, uint sessionId, string joiner) { Debug.Log("Session Joined!!!!!!"); chatText = "Session Joined!!!!!! \n" + chatText; currentSessionId = sessionId; currentJoinedSession = myAdvertisedName; if(sessionListener == null) { sessionListener = new MySessionListener(); msgBus.SetSessionListener(sessionListener, sessionId); } } } class MySessionListener : AllJoyn.SessionListener { protected override void SessionLost(uint sessionId) { chatText = "SessionLost ("+sessionId+") \n" + chatText; Debug.Log("SessionLost ("+sessionId+")"); } protected override void SessionMemberAdded(uint sessionId, string uniqueName) { chatText = "SessionMemberAdded ("+sessionId+","+uniqueName+") \n" + chatText; Debug.Log("SessionMemberAdded ("+sessionId+","+uniqueName+")"); } protected override void SessionMemberRemoved(uint sessionId, string uniqueName) { chatText = "SessionMemberRemoved ("+sessionId+","+uniqueName+") \n" + chatText; Debug.Log("SessionMemberRemoved ("+sessionId+","+uniqueName+")"); } } public BasicChat() { StartUp(); } public void StartUp() { chatText = "Starting AllJoyn\n\n\n" + chatText; AllJoynStarted = true; AllJoyn.QStatus status = AllJoyn.QStatus.OK; { chatText = "Creating BusAttachment\n" + chatText; // Create message bus msgBus = new AllJoyn.BusAttachment("myApp", true); // Add org.alljoyn.Bus.method_sample interface status = msgBus.CreateInterface(INTERFACE_NAME, false, out testIntf); if(status) { chatText = "Chat Interface Created.\n" + chatText; Debug.Log("Chat Interface Created."); testIntf.AddSignal("chat", "s", "msg", 0); testIntf.Activate(); } else { chatText = "Failed to create interface 'org.alljoyn.Bus.chat'\n" + chatText; Debug.Log("Failed to create interface 'org.alljoyn.Bus.chat'"); } // Create a bus listener busListener = new MyBusListener(); if(status) { msgBus.RegisterBusListener(busListener); chatText = "Chat BusListener Registered.\n" + chatText; Debug.Log("Chat BusListener Registered."); } if(testObj == null) testObj = new TestBusObject(msgBus, SERVICE_PATH); // Start the msg bus if(status) { status = msgBus.Start(); if(status) { chatText = "Chat BusAttachment started.\n" + chatText; Debug.Log("Chat BusAttachment started."); msgBus.RegisterBusObject(testObj); for (int i = 0; i < connectArgs.Length; ++i) { chatText = "Chat Connect trying: "+connectArgs[i]+"\n" + chatText; Debug.Log("Chat Connect trying: "+connectArgs[i]); status = msgBus.Connect(connectArgs[i]); if (status) { chatText = "BusAttchement.Connect(" + connectArgs[i] + ") SUCCEDED.\n" + chatText; Debug.Log("BusAttchement.Connect(" + connectArgs[i] + ") SUCCEDED."); connectedVal = connectArgs[i]; break; } else { chatText = "BusAttachment.Connect(" + connectArgs[i] + ") failed.\n" + chatText; Debug.Log("BusAttachment.Connect(" + connectArgs[i] + ") failed."); } } if(!status) { chatText = "BusAttachment.Connect failed.\n" + chatText; Debug.Log("BusAttachment.Connect failed."); } } else { chatText = "Chat BusAttachment.Start failed.\n" + chatText; Debug.Log("Chat BusAttachment.Start failed."); } } myAdvertisedName = SERVICE_NAME+"._"+msgBus.GlobalGUIDString; AllJoyn.InterfaceDescription.Member chatMember = testIntf.GetMember("chat"); status = msgBus.RegisterSignalHandler(this.ChatSignalHandler, chatMember, null); if(!status) { chatText ="Chat Failed to add signal handler " + status + "\n" + chatText; Debug.Log("Chat Failed to add signal handler " + status); } else { chatText ="Chat add signal handler " + status + "\n" + chatText; Debug.Log("Chat add signal handler " + status); } status = msgBus.AddMatch("type='signal',member='chat'"); if(!status) { chatText ="Chat Failed to add Match " + status.ToString() + "\n" + chatText; Debug.Log("Chat Failed to add Match " + status.ToString()); } else { chatText ="Chat add Match " + status.ToString() + "\n" + chatText; Debug.Log("Chat add Match " + status.ToString()); } } // Request name if(status) { status = msgBus.RequestName(myAdvertisedName, AllJoyn.DBus.NameFlags.ReplaceExisting | AllJoyn.DBus.NameFlags.DoNotQueue); if(!status) { chatText ="Chat RequestName(" + SERVICE_NAME + ") failed (status=" + status + ")\n" + chatText; Debug.Log("Chat RequestName(" + SERVICE_NAME + ") failed (status=" + status + ")"); } } // Create session opts = new AllJoyn.SessionOpts(AllJoyn.SessionOpts.TrafficType.Messages, false, AllJoyn.SessionOpts.ProximityType.Any, AllJoyn.TransportMask.Any); if(status) { ushort sessionPort = SERVICE_PORT; sessionPortListener = new MySessionPortListener(); status = msgBus.BindSessionPort(ref sessionPort, opts, sessionPortListener); if(!status || sessionPort != SERVICE_PORT) { chatText = "Chat BindSessionPort failed (" + status + ")\n" + chatText; Debug.Log("Chat BindSessionPort failed (" + status + ")"); } chatText = "Chat BindSessionPort on port (" + sessionPort + ")\n" + chatText; Debug.Log("Chat BBindSessionPort on port (" + sessionPort + ")");; } // Advertise name if(status) { status = msgBus.AdvertiseName(myAdvertisedName, opts.Transports); if(!status) { chatText = "Chat Failed to advertise name " + myAdvertisedName + " (" + status + ")\n" + chatText; Debug.Log("Chat Failed to advertise name " + myAdvertisedName + " (" + status + ")"); } } status = msgBus.FindAdvertisedName(SERVICE_NAME); if(!status) { chatText = "Chat org.alljoyn.Bus.FindAdvertisedName failed.\n" + chatText; Debug.Log("Chat org.alljoyn.Bus.FindAdvertisedName failed."); } Debug.Log("Completed ChatService Constructor"); } public void ChatSignalHandler(AllJoyn.InterfaceDescription.Member member, string srcPath, AllJoyn.Message message) { Debug.Log("Client Chat msg - : "+message[0]); chatText = "Client Chat msg: ("+message[0]+ ")\n" + chatText; } public void SendTheMsg(string msg) { if(currentSessionId != 0) { testObj.SendChatSignal(msg); } } public void JoinSession(string session) { if(currentJoinedSession != null) LeaveSession(); AllJoyn.QStatus status = AllJoyn.QStatus.NONE; if(sessionListener != null) { status = msgBus.SetSessionListener(null, currentSessionId); sessionListener = null; if(!status) { chatText = "SetSessionListener failed status(" + status.ToString() + ")\n" + chatText; Debug.Log("SetSessionListener status(" + status.ToString() + ")"); } } sessionListener = new MySessionListener(); chatText = "About to call JoinSession (Session=" + session + ")\n" + chatText; Debug.Log("About to call JoinSession (Session=" + session + ")"); status = msgBus.JoinSession(session, SERVICE_PORT, sessionListener, out currentSessionId, opts); if(status) { chatText = "Client JoinSession SUCCESS (Session id=" + currentSessionId + ")\n" + chatText; Debug.Log("Client JoinSession SUCCESS (Session id=" + currentSessionId + ")"); currentJoinedSession = session; } else { chatText = "Chat JoinSession failed (status=" + status.ToString() + ")\n" + chatText; Debug.Log("Chat JoinSession failed (status=" + status.ToString() + ")"); } } public void LeaveSession() { Debug.Log("in LeaveSession."); if(currentSessionId != 0) { AllJoyn.QStatus status = AllJoyn.QStatus.NONE; if(sessionListener != null) { Debug.Log("clear session listener"); status = msgBus.SetSessionListener(null, currentSessionId); sessionListener = null; if(!status) { chatText = "SetSessionListener failed status(" + status.ToString() + ")\n" + chatText; Debug.Log("SetSessionListener status(" + status.ToString() + ")"); } } Debug.Log("about to leave session"); status = msgBus.LeaveSession(currentSessionId); if(status) { chatText = "Chat LeaveSession SUCCESS (Session id=" + currentSessionId + ")\n" + chatText; Debug.Log("Chat LeaveSession SUCCESS (Session id=" + currentSessionId + ")"); currentSessionId = 0; currentJoinedSession = null; } else { chatText = "Chat LeaveSession failed (status=" + status.ToString() + ")\n" + chatText; Debug.Log("Chat LeaveSession failed (status=" + status.ToString() + ")"); } } else { currentJoinedSession = null; } Debug.Log("done LeaveSession."); } public void CloseDown() { if(msgBus == null) return; //no need to clean anything up AllJoynStarted = false; LeaveSession(); AllJoyn.QStatus status = msgBus.CancelFindAdvertisedName(SERVICE_NAME); if(!status) { chatText = "CancelAdvertisedName failed status(" + status.ToString() + ")\n" + chatText; Debug.Log("CancelAdvertisedName failed status(" + status.ToString() + ")"); } status = msgBus.CancelAdvertisedName(myAdvertisedName, opts.Transports); if(!status) { chatText = "CancelAdvertisedName failed status(" + status.ToString() + ")\n" + chatText; Debug.Log("CancelAdvertisedName failed status(" + status.ToString() + ")"); } status = msgBus.ReleaseName(myAdvertisedName); if(!status) { chatText = "ReleaseName failed status(" + status.ToString() + ")\n" + chatText; Debug.Log("ReleaseName status(" + status.ToString() + ")"); } status = msgBus.UnbindSessionPort(SERVICE_PORT); if(!status) { chatText = "UnbindSessionPort failed status(" + status.ToString() + ")\n" + chatText; Debug.Log("UnbindSessionPort status(" + status.ToString() + ")"); } status = msgBus.Disconnect(connectedVal); if(!status) { chatText = "Disconnect failed status(" + status.ToString() + ")\n" + chatText; Debug.Log("Disconnect status(" + status.ToString() + ")"); } AllJoyn.InterfaceDescription.Member chatMember = testIntf.GetMember("chat"); status = msgBus.UnregisterSignalHandler(this.ChatSignalHandler, chatMember, null); chatMember = null; if(!status) { chatText = "UnregisterSignalHandler failed status(" + status.ToString() + ")\n" + chatText; Debug.Log("UnregisterSignalHandler status(" + status.ToString() + ")"); } if(sessionListener != null) { status = msgBus.SetSessionListener(null, currentSessionId); sessionListener = null; if(!status) { chatText = "SetSessionListener failed status(" + status.ToString() + ")\n" + chatText; Debug.Log("SetSessionListener status(" + status.ToString() + ")"); } } chatText = "No Exceptions(" + status.ToString() + ")\n" + chatText; Debug.Log("No Exceptions(" + status.ToString() + ")"); currentSessionId = 0; currentJoinedSession = null; sFoundName.Clear(); connectedVal = null; msgBus = null; busListener = null; sessionPortListener = null; testObj = null; testIntf = null; opts = null; myAdvertisedName = null; AllJoynStarted = false; AllJoyn.StopAllJoynProcessing(); //Stop processing alljoyn callbacks } } }
// **************************************************************** // Copyright 2009, Charlie Poole // This is free software licensed under the NUnit license. You may // obtain a copy of the license at http://nunit.org // **************************************************************** using System; using System.Collections; using PclUnit.Constraints.Pieces; namespace PclUnit.Constraints { /// <summary> /// Helper class with properties and methods that supply /// a number of constraints used in Asserts. /// </summary> public class Is { #region Not /// <summary> /// Returns a ConstraintExpression that negates any /// following constraint. /// </summary> public static ConstraintExpression Not { get { return new ConstraintExpression().Not; } } #endregion #region All /// <summary> /// Returns a ConstraintExpression, which will apply /// the following constraint to all members of a collection, /// succeeding if all of them succeed. /// </summary> public static ConstraintExpression All { get { return new ConstraintExpression().All; } } #endregion #region Null /// <summary> /// Returns a constraint that tests for null /// </summary> public static NullConstraint Null { get { return new NullConstraint(); } } #endregion #region True /// <summary> /// Returns a constraint that tests for True /// </summary> public static TrueConstraint True { get { return new TrueConstraint(); } } #endregion #region False /// <summary> /// Returns a constraint that tests for False /// </summary> public static FalseConstraint False { get { return new FalseConstraint(); } } #endregion #region Positive /// <summary> /// Returns a constraint that tests for a positive value /// </summary> public static GreaterThanConstraint Positive { get { return new GreaterThanConstraint(0); } } #endregion #region Negative /// <summary> /// Returns a constraint that tests for a negative value /// </summary> public static LessThanConstraint Negative { get { return new LessThanConstraint(0); } } #endregion #region NaN /// <summary> /// Returns a constraint that tests for NaN /// </summary> public static NaNConstraint NaN { get { return new NaNConstraint(); } } #endregion #region Empty /// <summary> /// Returns a constraint that tests for empty /// </summary> public static EmptyConstraint Empty { get { return new EmptyConstraint(); } } #endregion #region Unique /// <summary> /// Returns a constraint that tests whether a collection /// contains all unique items. /// </summary> public static UniqueItemsConstraint Unique { get { return new UniqueItemsConstraint(); } } #endregion #region EqualTo /// <summary> /// Returns a constraint that tests two items for equality /// </summary> public static EqualConstraint EqualTo(object expected) { return new EqualConstraint(expected); } #endregion #region SameAs /// <summary> /// Returns a constraint that tests that two references are the same object /// </summary> public static SameAsConstraint SameAs(object expected) { return new SameAsConstraint(expected); } #endregion #region GreaterThan /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than the suppled argument /// </summary> public static GreaterThanConstraint GreaterThan(object expected) { return new GreaterThanConstraint(expected); } #endregion #region GreaterThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the suppled argument /// </summary> public static GreaterThanOrEqualConstraint GreaterThanOrEqualTo(object expected) { return new GreaterThanOrEqualConstraint(expected); } /// <summary> /// Returns a constraint that tests whether the /// actual value is greater than or equal to the suppled argument /// </summary> public static GreaterThanOrEqualConstraint AtLeast(object expected) { return new GreaterThanOrEqualConstraint(expected); } #endregion #region LessThan /// <summary> /// Returns a constraint that tests whether the /// actual value is less than the suppled argument /// </summary> public static LessThanConstraint LessThan(object expected) { return new LessThanConstraint(expected); } #endregion #region LessThanOrEqualTo /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the suppled argument /// </summary> public static LessThanOrEqualConstraint LessThanOrEqualTo(object expected) { return new LessThanOrEqualConstraint(expected); } /// <summary> /// Returns a constraint that tests whether the /// actual value is less than or equal to the suppled argument /// </summary> public static LessThanOrEqualConstraint AtMost(object expected) { return new LessThanOrEqualConstraint(expected); } #endregion #region TypeOf /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public static ExactTypeConstraint TypeOf(Type expectedType) { return new ExactTypeConstraint(expectedType); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual /// value is of the exact type supplied as an argument. /// </summary> public static ExactTypeConstraint TypeOf<T>() { return new ExactTypeConstraint(typeof(T)); } #endif #endregion #region InstanceOf /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public static InstanceOfTypeConstraint InstanceOf(Type expectedType) { return new InstanceOfTypeConstraint(expectedType); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> public static InstanceOfTypeConstraint InstanceOf<T>() { return new InstanceOfTypeConstraint(typeof(T)); } #endif /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> [Obsolete("Use InstanceOf(expectedType)")] public static InstanceOfTypeConstraint InstanceOfType(Type expectedType) { return new InstanceOfTypeConstraint(expectedType); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is of the type supplied as an argument or a derived type. /// </summary> [Obsolete("Use InstanceOf<T>()")] public static InstanceOfTypeConstraint InstanceOfType<T>() { return new InstanceOfTypeConstraint(typeof(T)); } #endif #endregion #region AssignableFrom /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public static AssignableFromConstraint AssignableFrom(Type expectedType) { return new AssignableFromConstraint(expectedType); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public static AssignableFromConstraint AssignableFrom<T>() { return new AssignableFromConstraint(typeof(T)); } #endif #endregion #region AssignableTo /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public static AssignableToConstraint AssignableTo(Type expectedType) { return new AssignableToConstraint(expectedType); } #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value /// is assignable from the type supplied as an argument. /// </summary> public static AssignableToConstraint AssignableTo<T>() { return new AssignableToConstraint(typeof(T)); } #endif #endregion #region EquivalentTo /// <summary> /// Returns a constraint that tests whether the actual value /// is a collection containing the same elements as the /// collection supplied as an argument. /// </summary> public static CollectionEquivalentConstraint EquivalentTo(IEnumerable expected) { return new CollectionEquivalentConstraint(expected); } #endregion #region SubsetOf /// <summary> /// Returns a constraint that tests whether the actual value /// is a subset of the collection supplied as an argument. /// </summary> public static CollectionSubsetConstraint SubsetOf(IEnumerable expected) { return new CollectionSubsetConstraint(expected); } #endregion #region Ordered /// <summary> /// Returns a constraint that tests whether a collection is ordered /// </summary> public static CollectionOrderedConstraint Ordered { get { return new CollectionOrderedConstraint(); } } #endregion #region StringContaining /// <summary> /// Returns a constraint that succeeds if the actual /// value contains the substring supplied as an argument. /// </summary> public static SubstringConstraint StringContaining(string expected) { return new SubstringConstraint(expected); } #endregion #region StringStarting /// <summary> /// Returns a constraint that succeeds if the actual /// value starts with the substring supplied as an argument. /// </summary> public static StartsWithConstraint StringStarting(string expected) { return new StartsWithConstraint(expected); } #endregion #region StringEnding /// <summary> /// Returns a constraint that succeeds if the actual /// value ends with the substring supplied as an argument. /// </summary> public static EndsWithConstraint StringEnding(string expected) { return new EndsWithConstraint(expected); } #endregion #region StringMatching // // /// <summary> // /// Returns a constraint that succeeds if the actual // /// value matches the Regex pattern supplied as an argument. // /// </summary> // public static RegexConstraint StringMatching(string pattern) // { // return new RegexConstraint(pattern); // } #endregion #region InRange<T> #if CLR_2_0 || CLR_4_0 /// <summary> /// Returns a constraint that tests whether the actual value falls /// within a specified range. /// </summary> public static RangeConstraint<T> InRange<T>(T from, T to) where T : IComparable<T> { return new RangeConstraint<T>(from, to); } #endif #endregion } }
using EpisodeInformer.Core.Net; using EpisodeInformer.Core.Rss; using EpisodeInformer.Core.Threading; using EpisodeInformer.Properties; using System; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.IO; using System.Net; using System.Windows.Forms; namespace EpisodeInformer { public partial class frmFileDownload : Form { private IContainer components = (IContainer)null; private TextBox txtURL; private TextBox txtTitle; private Label label2; private Label label1; private LinkLabel lnkLChange; private TextBox txtDestination; private Label label3; private StatusStrip statusStrip1; private Label label4; private CheckBox chkAutoOpen; private Button btnDownload; private Button btnClose; private Panel panel1; private Panel pnlDownloadOptions; private Panel panel3; private ToolStripProgressBar prgProgress; private ToolStripStatusLabel lblPercent; private ToolStripStatusLabel toolStripStatusLabel1; protected override void Dispose(bool disposing) { if (disposing && this.components != null) this.components.Dispose(); base.Dispose(disposing); } private void InitializeComponent() { ComponentResourceManager resources = new ComponentResourceManager(typeof(frmFileDownload)); this.txtURL = new TextBox(); this.txtTitle = new TextBox(); this.label2 = new Label(); this.label1 = new Label(); this.label4 = new Label(); this.chkAutoOpen = new CheckBox(); this.lnkLChange = new LinkLabel(); this.txtDestination = new TextBox(); this.label3 = new Label(); this.statusStrip1 = new StatusStrip(); this.prgProgress = new ToolStripProgressBar(); this.lblPercent = new ToolStripStatusLabel(); this.btnDownload = new Button(); this.btnClose = new Button(); this.panel1 = new Panel(); this.pnlDownloadOptions = new Panel(); this.panel3 = new Panel(); this.toolStripStatusLabel1 = new ToolStripStatusLabel(); this.statusStrip1.SuspendLayout(); this.panel1.SuspendLayout(); this.pnlDownloadOptions.SuspendLayout(); this.panel3.SuspendLayout(); this.SuspendLayout(); this.txtURL.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.txtURL.Location = new Point(63, 44); this.txtURL.Multiline = true; this.txtURL.Name = "txtURL"; this.txtURL.ReadOnly = true; this.txtURL.Size = new Size(249, 62); this.txtURL.TabIndex = 3; this.txtTitle.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.txtTitle.Location = new Point(63, 14); this.txtTitle.Multiline = true; this.txtTitle.Name = "txtTitle"; this.txtTitle.ReadOnly = true; this.txtTitle.Size = new Size(249, 24); this.txtTitle.TabIndex = 2; this.label2.AutoSize = true; this.label2.BackColor = Color.Transparent; this.label2.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.label2.Location = new Point(11, 48); this.label2.Name = "label2"; this.label2.Size = new Size(28, 15); this.label2.TabIndex = 1; this.label2.Text = "URL"; this.label1.AutoSize = true; this.label1.BackColor = Color.Transparent; this.label1.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.label1.Location = new Point(11, 18); this.label1.Name = "label1"; this.label1.Size = new Size(30, 15); this.label1.TabIndex = 0; this.label1.Text = "Title"; this.label4.AutoSize = true; this.label4.BackColor = Color.Transparent; this.label4.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.label4.Location = new Point(10, 64); this.label4.Name = "label4"; this.label4.Size = new Size(49, 15); this.label4.TabIndex = 4; this.label4.Text = "Options"; this.chkAutoOpen.AutoSize = true; this.chkAutoOpen.BackColor = Color.Transparent; this.chkAutoOpen.Checked = Settings.Default.AutoOpenDLFile; this.chkAutoOpen.CheckState = CheckState.Checked; this.chkAutoOpen.DataBindings.Add(new Binding("Checked", (object)Settings.Default, "AutoOpenDLFile", true, DataSourceUpdateMode.OnPropertyChanged)); this.chkAutoOpen.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.chkAutoOpen.Location = new Point(76, 63); this.chkAutoOpen.Name = "chkAutoOpen"; this.chkAutoOpen.Size = new Size(94, 19); this.chkAutoOpen.TabIndex = 3; this.chkAutoOpen.Text = "Auto Launch"; this.chkAutoOpen.UseVisualStyleBackColor = false; this.lnkLChange.AutoSize = true; this.lnkLChange.BackColor = Color.Transparent; this.lnkLChange.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.lnkLChange.Location = new Point(267, 53); this.lnkLChange.Name = "lnkLChange"; this.lnkLChange.Size = new Size(48, 15); this.lnkLChange.TabIndex = 2; this.lnkLChange.TabStop = true; this.lnkLChange.Text = "Change"; this.lnkLChange.LinkClicked += new LinkLabelLinkClickedEventHandler(this.lnkLChange_LinkClicked); this.txtDestination.DataBindings.Add(new Binding("Text", (object)Settings.Default, "LastDLFileLocation", true, DataSourceUpdateMode.OnPropertyChanged)); this.txtDestination.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.txtDestination.Location = new Point(76, 12); this.txtDestination.Multiline = true; this.txtDestination.Name = "txtDestination"; this.txtDestination.ReadOnly = true; this.txtDestination.Size = new Size(235, 38); this.txtDestination.TabIndex = 1; this.txtDestination.Text = Settings.Default.LastDLFileLocation; this.label3.AutoSize = true; this.label3.BackColor = Color.Transparent; this.label3.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.label3.Location = new Point(10, 16); this.label3.Name = "label3"; this.label3.Size = new Size(67, 15); this.label3.TabIndex = 0; this.label3.Text = "Destination"; this.statusStrip1.Items.AddRange(new ToolStripItem[3] { (ToolStripItem) this.toolStripStatusLabel1, (ToolStripItem) this.prgProgress, (ToolStripItem) this.lblPercent }); this.statusStrip1.Location = new Point(0, 314); this.statusStrip1.Name = "statusStrip1"; this.statusStrip1.Size = new Size(352, 22); this.statusStrip1.SizingGrip = false; this.statusStrip1.TabIndex = 2; this.statusStrip1.Text = "statusStrip1"; this.prgProgress.Name = "prgProgress"; this.prgProgress.Size = new Size(100, 16); this.lblPercent.Name = "lblPercent"; this.lblPercent.Size = new Size(0, 17); this.btnDownload.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.btnDownload.Location = new Point(157, 14); this.btnDownload.Name = "btnDownload"; this.btnDownload.Size = new Size(75, 23); this.btnDownload.TabIndex = 1; this.btnDownload.Text = "&Download"; this.btnDownload.UseVisualStyleBackColor = true; this.btnDownload.Click += new EventHandler(this.btnDownload_Click); this.btnClose.Font = new Font("Segoe UI Symbol", 9f, FontStyle.Regular, GraphicsUnit.Point, (byte)0); this.btnClose.Location = new Point(238, 14); this.btnClose.Name = "btnClose"; this.btnClose.Size = new Size(75, 23); this.btnClose.TabIndex = 0; this.btnClose.Text = "&Close"; this.btnClose.UseVisualStyleBackColor = true; this.btnClose.Click += new EventHandler(this.btnClose_Click); this.panel1.BackgroundImage = (Image)Resources.dfup; this.panel1.Controls.Add((Control)this.txtURL); this.panel1.Controls.Add((Control)this.txtTitle); this.panel1.Controls.Add((Control)this.label1); this.panel1.Controls.Add((Control)this.label2); this.panel1.Location = new Point(12, 12); this.panel1.Name = "panel1"; this.panel1.Size = new Size(328, 123); this.panel1.TabIndex = 4; this.pnlDownloadOptions.BackgroundImage = (Image)Resources.dfdw1; this.pnlDownloadOptions.Controls.Add((Control)this.label4); this.pnlDownloadOptions.Controls.Add((Control)this.txtDestination); this.pnlDownloadOptions.Controls.Add((Control)this.chkAutoOpen); this.pnlDownloadOptions.Controls.Add((Control)this.label3); this.pnlDownloadOptions.Controls.Add((Control)this.lnkLChange); this.pnlDownloadOptions.Location = new Point(12, 141); this.pnlDownloadOptions.Name = "pnlDownloadOptions"; this.pnlDownloadOptions.Size = new Size(328, 104); this.pnlDownloadOptions.TabIndex = 5; this.panel3.BackgroundImage = (Image)Resources.dfdw; this.panel3.Controls.Add((Control)this.btnDownload); this.panel3.Controls.Add((Control)this.btnClose); this.panel3.Location = new Point(12, 251); this.panel3.Name = "panel3"; this.panel3.Size = new Size(328, 50); this.panel3.TabIndex = 6; this.toolStripStatusLabel1.Name = "toolStripStatusLabel1"; this.toolStripStatusLabel1.Size = new Size(52, 17); this.toolStripStatusLabel1.Text = "Progress"; this.AutoScaleDimensions = new SizeF(6f, 13f); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackgroundImage = (Image)Resources.back; this.ClientSize = new Size(352, 336); this.Controls.Add((Control)this.panel3); this.Controls.Add((Control)this.pnlDownloadOptions); this.Controls.Add((Control)this.panel1); this.Controls.Add((Control)this.statusStrip1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = (Icon)resources.GetObject("$this.Icon"); this.MaximizeBox = false; this.Name = "frmFileDownload"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "Download File"; this.FormClosing += new FormClosingEventHandler(this.frmFileDownload_FormClosing); this.Load += new EventHandler(this.frmFileDownload_Load); this.statusStrip1.ResumeLayout(false); this.statusStrip1.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.pnlDownloadOptions.ResumeLayout(false); this.pnlDownloadOptions.PerformLayout(); this.panel3.ResumeLayout(false); this.ResumeLayout(false); this.PerformLayout(); } } }
// ReSharper disable All using System.Collections.Generic; using System.Data; using System.Dynamic; using System.Linq; using Frapid.DataAccess; using Frapid.DataAccess.Models; using Frapid.DbPolicy; using Frapid.Framework.Extensions; using Npgsql; using Serilog; using Frapid.NPoco; namespace Frapid.WebsiteBuilder.DataAccess { /// <summary> /// Provides simplified data access features to perform SCRUD operation on the database view "website.published_content_view". /// </summary> public class PublishedContentView : DbAccess, IPublishedContentViewRepository { /// <summary> /// The schema of this view. Returns literal "website". /// </summary> public override string _ObjectNamespace => "website"; /// <summary> /// The schema unqualified name of this view. Returns literal "published_content_view". /// </summary> public override string _ObjectName => "published_content_view"; /// <summary> /// Login id of application user accessing this view. /// </summary> public long _LoginId { get; set; } /// <summary> /// User id of application user accessing this table. /// </summary> public int _UserId { get; set; } /// <summary> /// The name of the database on which queries are being executed to. /// </summary> public string _Catalog { get; set; } /// <summary> /// Performs SQL count on the view "website.published_content_view". /// </summary> /// <returns>Returns the number of rows of the view "website.published_content_view".</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long Count() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"PublishedContentView\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT COUNT(*) FROM website.published_content_view;"; return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Executes a select query on the view "website.published_content_view" to return all instances of the "PublishedContentView" class. /// </summary> /// <returns>Returns a non-live, non-mapped instances of "PublishedContentView" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.WebsiteBuilder.Entities.PublishedContentView> Get() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.ExportData, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the export entity \"PublishedContentView\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM website.published_content_view ORDER BY 1;"; return Factory.Get<Frapid.WebsiteBuilder.Entities.PublishedContentView>(this._Catalog, sql); } /// <summary> /// Displayfields provide a minimal name/value context for data binding the row collection of website.published_content_view. /// </summary> /// <returns>Returns an enumerable name and value collection for the view website.published_content_view</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<DisplayField> GetDisplayFields() { List<DisplayField> displayFields = new List<DisplayField>(); if (string.IsNullOrWhiteSpace(this._Catalog)) { return displayFields; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to get display field for entity \"PublishedContentView\" was denied to the user with Login ID {LoginId}", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT content_id AS key, title || ' (' || category_name || ')' as value FROM website.published_content_view;"; using (NpgsqlCommand command = new NpgsqlCommand(sql)) { using (DataTable table = DbOperation.GetDataTable(this._Catalog, command)) { if (table?.Rows == null || table.Rows.Count == 0) { return displayFields; } foreach (DataRow row in table.Rows) { if (row != null) { DisplayField displayField = new DisplayField { Key = row["key"].ToString(), Value = row["value"].ToString() }; displayFields.Add(displayField); } } } } return displayFields; } /// <summary> /// Performs a select statement on the view "website.published_content_view" producing a paginated result of 10. /// </summary> /// <returns>Returns the first page of collection of "PublishedContentView" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.WebsiteBuilder.Entities.PublishedContentView> GetPaginatedResult() { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to the first page of the entity \"PublishedContentView\" was denied to the user with Login ID {LoginId}.", this._LoginId); throw new UnauthorizedException("Access is denied."); } } const string sql = "SELECT * FROM website.published_content_view ORDER BY 1 LIMIT 10 OFFSET 0;"; return Factory.Get<Frapid.WebsiteBuilder.Entities.PublishedContentView>(this._Catalog, sql); } /// <summary> /// Performs a select statement on the view "website.published_content_view" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result.</param> /// <returns>Returns collection of "PublishedContentView" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.WebsiteBuilder.Entities.PublishedContentView> GetPaginatedResult(long pageNumber) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the entity \"PublishedContentView\" was denied to the user with Login ID {LoginId}.", pageNumber, this._LoginId); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; const string sql = "SELECT * FROM website.published_content_view ORDER BY 1 LIMIT 10 OFFSET @0;"; return Factory.Get<Frapid.WebsiteBuilder.Entities.PublishedContentView>(this._Catalog, sql, offset); } public List<Frapid.DataAccess.Models.Filter> GetFilters(string catalog, string filterName) { const string sql = "SELECT * FROM config.filters WHERE object_name='website.published_content_view' AND lower(filter_name)=lower(@0);"; return Factory.Get<Frapid.DataAccess.Models.Filter>(catalog, sql, filterName).ToList(); } /// <summary> /// Performs a filtered count on view "website.published_content_view". /// </summary> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns number of rows of "PublishedContentView" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountWhere(List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"PublishedContentView\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM website.published_content_view WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.PublishedContentView(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on view "website.published_content_view" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filters">The list of filter conditions.</param> /// <returns>Returns collection of "PublishedContentView" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.WebsiteBuilder.Entities.PublishedContentView> GetWhere(long pageNumber, List<Frapid.DataAccess.Models.Filter> filters) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"PublishedContentView\" was denied to the user with Login ID {LoginId}. Filters: {Filters}.", pageNumber, this._LoginId, filters); throw new UnauthorizedException("Access is denied."); } } long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM website.published_content_view WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.PublishedContentView(), filters); sql.OrderBy("1"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.WebsiteBuilder.Entities.PublishedContentView>(this._Catalog, sql); } /// <summary> /// Performs a filtered count on view "website.published_content_view". /// </summary> /// <param name="filterName">The named filter.</param> /// <returns>Returns number of rows of "PublishedContentView" class using the filter.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public long CountFiltered(string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return 0; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to count entity \"PublishedContentView\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); Sql sql = Sql.Builder.Append("SELECT COUNT(*) FROM website.published_content_view WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.PublishedContentView(), filters); return Factory.Scalar<long>(this._Catalog, sql); } /// <summary> /// Performs a filtered select statement on view "website.published_content_view" producing a paginated result of 10. /// </summary> /// <param name="pageNumber">Enter the page number to produce the paginated result. If you provide a negative number, the result will not be paginated.</param> /// <param name="filterName">The named filter.</param> /// <returns>Returns collection of "PublishedContentView" class.</returns> /// <exception cref="UnauthorizedException">Thown when the application user does not have sufficient privilege to perform this action.</exception> public IEnumerable<Frapid.WebsiteBuilder.Entities.PublishedContentView> GetFiltered(long pageNumber, string filterName) { if (string.IsNullOrWhiteSpace(this._Catalog)) { return null; } if (!this.SkipValidation) { if (!this.Validated) { this.Validate(AccessTypeEnum.Read, this._LoginId, this._Catalog, false); } if (!this.HasAccess) { Log.Information("Access to Page #{Page} of the filtered entity \"PublishedContentView\" was denied to the user with Login ID {LoginId}. Filter: {Filter}.", pageNumber, this._LoginId, filterName); throw new UnauthorizedException("Access is denied."); } } List<Frapid.DataAccess.Models.Filter> filters = this.GetFilters(this._Catalog, filterName); long offset = (pageNumber - 1) * 10; Sql sql = Sql.Builder.Append("SELECT * FROM website.published_content_view WHERE 1 = 1"); Frapid.DataAccess.FilterManager.AddFilters(ref sql, new Frapid.WebsiteBuilder.Entities.PublishedContentView(), filters); sql.OrderBy("1"); if (pageNumber > 0) { sql.Append("LIMIT @0", 10); sql.Append("OFFSET @0", offset); } return Factory.Get<Frapid.WebsiteBuilder.Entities.PublishedContentView>(this._Catalog, sql); } } }
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for // license information. // // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.Compute { using Microsoft.Azure; using Microsoft.Azure.Management; using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// ImagesOperations operations. /// </summary> public partial interface IImagesOperations { /// <summary> /// Create or update an image. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='imageName'> /// The name of the image. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Image operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Image>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string imageName, Image parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an Image. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='imageName'> /// The name of the image. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<OperationStatusResponse>> DeleteWithHttpMessagesAsync(string resourceGroupName, string imageName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets an image. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='imageName'> /// The name of the image. /// </param> /// <param name='expand'> /// The expand expression to apply on the operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Image>> GetWithHttpMessagesAsync(string resourceGroupName, string imageName, string expand = default(string), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of images under a resource group. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Image>>> ListByResourceGroupWithHttpMessagesAsync(string resourceGroupName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of Images in the subscription. Use nextLink property /// in the response to get the next page of Images. Do this till /// nextLink is not null to fetch all the Images. /// </summary> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<IPage<Image>>> ListWithHttpMessagesAsync(Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Create or update an image. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='imageName'> /// The name of the image. /// </param> /// <param name='parameters'> /// Parameters supplied to the Create Image operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<Image>> BeginCreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string imageName, Image parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Deletes an Image. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. /// </param> /// <param name='imageName'> /// The name of the image. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<OperationStatusResponse>> BeginDeleteWithHttpMessagesAsync(string resourceGroupName, string imageName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of images under a resource group. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<IPage<Image>>> ListByResourceGroupNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Gets the list of Images in the subscription. Use nextLink property /// in the response to get the next page of Images. Do this till /// nextLink is not null to fetch all the Images. /// </summary> /// <param name='nextPageLink'> /// The NextLink from the previous successful call to List operation. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// 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> Task<AzureOperationResponse<IPage<Image>>> ListNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
using UnityEngine; using System.Collections; using System.Collections.Generic; using System.Threading; using Algorithms; using UnityEngine.UI; [System.Serializable] public enum TileType { Empty, Block, OneWay } [System.Serializable] public partial class Map : MonoBehaviour { /// <summary> /// The map's position in world space. Bottom left corner. /// </summary> public Vector3 position; /// <summary> /// The base tile sprite prefab that populates the map. /// Assigned in the inspector. /// </summary> public SpriteRenderer tilePrefab; /// <summary> /// The path finder. /// </summary> public PathFinderFast mPathFinder; /// <summary> /// The nodes that are fed to pathfinder. /// </summary> [HideInInspector] public byte[,] mGrid; /// <summary> /// The map's tile data. /// </summary> [HideInInspector] private TileType[,] tiles; /// <summary> /// The map's sprites. /// </summary> private SpriteRenderer[,] tilesSprites; /// <summary> /// A parent for all the sprites. Assigned from the inspector. /// </summary> public Transform mSpritesContainer; /// <summary> /// The size of a tile in pixels. /// </summary> static public int cTileSize = 16; /// <summary> /// The width of the map in tiles. /// </summary> public int mWidth = 50; /// <summary> /// The height of the map in tiles. /// </summary> public int mHeight = 42; public MapRoomData mapRoomSimple; public MapRoomData mapRoomOneWay; public Camera gameCamera; public Bot player; bool[] inputs; bool[] prevInputs; int lastMouseTileX = -1; int lastMouseTileY = -1; public KeyCode goLeftKey = KeyCode.A; public KeyCode goRightKey = KeyCode.D; public KeyCode goJumpKey = KeyCode.W; public KeyCode goDownKey = KeyCode.S; public RectTransform sliderHigh; public RectTransform sliderLow; public TileType GetTile(int x, int y) { if (x < 0 || x >= mWidth || y < 0 || y >= mHeight) return TileType.Block; return tiles[x, y]; } public bool IsOneWayPlatform(int x, int y) { if (x < 0 || x >= mWidth || y < 0 || y >= mHeight) return false; return (tiles[x, y] == TileType.OneWay); } public bool IsGround(int x, int y) { if (x < 0 || x >= mWidth || y < 0 || y >= mHeight) return false; return (tiles[x, y] == TileType.OneWay || tiles[x, y] == TileType.Block); } public bool IsObstacle(int x, int y) { if (x < 0 || x >= mWidth || y < 0 || y >= mHeight) return true; return (tiles[x, y] == TileType.Block); } public bool IsNotEmpty(int x, int y) { if (x < 0 || x >= mWidth || y < 0 || y >= mHeight) return true; return (tiles[x, y] != TileType.Empty); } public void InitPathFinder() { mPathFinder = new PathFinderFast(mGrid, this); mPathFinder.Formula = HeuristicFormula.Manhattan; //if false then diagonal movement will be prohibited mPathFinder.Diagonals = false; //if true then diagonal movement will have higher cost mPathFinder.HeavyDiagonals = false; //estimate of path length mPathFinder.HeuristicEstimate = 6; mPathFinder.PunishChangeDirection = false; mPathFinder.TieBreaker = false; mPathFinder.SearchLimit = 1000000; mPathFinder.DebugProgress = false; mPathFinder.DebugFoundPath = false; } public void GetMapTileAtPoint(Vector2 point, out int tileIndexX, out int tileIndexY) { tileIndexY =(int)((point.y - position.y + cTileSize/2.0f)/(float)(cTileSize)); tileIndexX =(int)((point.x - position.x + cTileSize/2.0f)/(float)(cTileSize)); } public Vector2i GetMapTileAtPoint(Vector2 point) { return new Vector2i((int)((point.x - position.x + cTileSize/2.0f)/(float)(cTileSize)), (int)((point.y - position.y + cTileSize/2.0f)/(float)(cTileSize))); } public Vector2 GetMapTilePosition(int tileIndexX, int tileIndexY) { return new Vector2( (float) (tileIndexX * cTileSize) + position.x, (float) (tileIndexY * cTileSize) + position.y ); } public Vector2 GetMapTilePosition(Vector2i tileCoords) { return new Vector2( (float) (tileCoords.x * cTileSize) + position.x, (float) (tileCoords.y * cTileSize) + position.y ); } public bool CollidesWithMapTile(AABB aabb, int tileIndexX, int tileIndexY) { var tilePos = GetMapTilePosition (tileIndexX, tileIndexY); return aabb.Overlaps(tilePos, new Vector2( (float)(cTileSize)/2.0f, (float)(cTileSize)/2.0f)); } public bool AnySolidBlockInRectangle(Vector2 start, Vector2 end) { return AnySolidBlockInRectangle(GetMapTileAtPoint(start), GetMapTileAtPoint(end)); } public bool AnySolidBlockInStripe(int x, int y0, int y1) { int startY, endY; if (y0 <= y1) { startY = y0; endY = y1; } else { startY = y1; endY = y0; } for (int y = startY; y <= endY; ++y) { if (GetTile(x, y) == TileType.Block) return true; } return false; } public bool AnySolidBlockInRectangle(Vector2i start, Vector2i end) { int startX, startY, endX, endY; if (start.x <= end.x) { startX = start.x; endX = end.x; } else { startX = end.x; endX = start.x; } if (start.y <= end.y) { startY = start.y; endY = end.y; } else { startY = end.y; endY = start.y; } for (int y = startY; y <= endY; ++y) { for (int x = startX; x <= endX; ++x) { if (GetTile(x, y) == TileType.Block) return true; } } return false; } public void SetTile(int x, int y, TileType type) { if (x <= 1 || x >= mWidth - 2 || y <= 1 || y >= mHeight - 2) return; tiles[x, y] = type; if (type == TileType.Block) { mGrid[x, y] = 0; AutoTile(type, x, y, 1, 8, 4, 4, 4, 4); tilesSprites[x, y].enabled = true; } else if (type == TileType.OneWay) { mGrid[x, y] = 1; tilesSprites[x, y].enabled = true; tilesSprites[x, y].transform.localScale = new Vector3(1.0f, 1.0f, 1.0f); tilesSprites[x, y].transform.eulerAngles = new Vector3(0.0f, 0.0f, 0.0f); tilesSprites[x, y].sprite = mDirtSprites[25]; } else { mGrid[x, y] = 1; tilesSprites[x, y].enabled = false; } AutoTile(type, x - 1, y, 1, 8, 4, 4, 4, 4); AutoTile(type, x + 1, y, 1, 8, 4, 4, 4, 4); AutoTile(type, x, y - 1, 1, 8, 4, 4, 4, 4); AutoTile(type, x, y + 1, 1, 8, 4, 4, 4, 4); } public void Start() { var mapRoom = mapRoomOneWay; mRandomNumber = new System.Random(); Application.targetFrameRate = 60; inputs = new bool[(int)KeyInput.Count]; prevInputs = new bool[(int)KeyInput.Count]; //set the position position = transform.position; mWidth = mapRoom.width; mHeight = mapRoom.height; tiles = new TileType[mWidth, mHeight]; tilesSprites = new SpriteRenderer[mapRoom.width, mapRoom.height]; mGrid = new byte[Mathf.NextPowerOfTwo((int)mWidth), Mathf.NextPowerOfTwo((int)mHeight)]; InitPathFinder(); Camera.main.orthographicSize = Camera.main.pixelHeight / 2; for (int y = 0; y < mHeight; ++y) { for (int x = 0; x < mWidth; ++x) { tilesSprites[x, y] = Instantiate<SpriteRenderer>(tilePrefab); tilesSprites[x, y].transform.parent = transform; tilesSprites[x, y].transform.position = position + new Vector3(cTileSize * x, cTileSize * y, 10.0f); if (mapRoom.tileData[y * mWidth + x] == TileType.Empty) SetTile(x, y, TileType.Empty); else if (mapRoom.tileData[y * mWidth + x] == TileType.Block) SetTile(x, y, TileType.Block); else SetTile(x, y, TileType.OneWay); } } for (int y = 0; y < mHeight; ++y) { tiles[1, y] = TileType.Block; tiles[mWidth - 2, y] = TileType.Block; } for (int x = 0; x < mWidth; ++x) { tiles[x, 1] = TileType.Block; tiles[x, mHeight - 2] = TileType.Block; } /*for (int y = 2; y < mHeight - 2; ++y) { for (int x = 2; x < mWidth - 2; ++x) { if (y < mHeight/4) SetTile(x, y, TileType.Block); } }*/ player.BotInit(inputs, prevInputs); player.mMap = this; player.mPosition = new Vector2(2 * Map.cTileSize, (mHeight / 2) * Map.cTileSize + player.mAABB.HalfSizeY); } void Update() { inputs[(int)KeyInput.GoRight] = Input.GetKey(goRightKey); inputs[(int)KeyInput.GoLeft] = Input.GetKey(goLeftKey); inputs[(int)KeyInput.GoDown] = Input.GetKey(goDownKey); inputs[(int)KeyInput.Jump] = Input.GetKey(goJumpKey); if (Input.GetKeyUp(KeyCode.Mouse0)) lastMouseTileX = lastMouseTileY = -1; Vector2 mousePos = Input.mousePosition; Vector2 cameraPos = Camera.main.transform.position; var mousePosInWorld = cameraPos + mousePos - new Vector2(gameCamera.pixelWidth / 2, gameCamera.pixelHeight / 2); int mouseTileX, mouseTileY; GetMapTileAtPoint(mousePosInWorld, out mouseTileX, out mouseTileY); Vector2 offsetMouse = (Vector2)(Input.mousePosition) - new Vector2(Camera.main.pixelWidth/2, Camera.main.pixelHeight/2); Vector2 bottomLeft = (Vector2)sliderLow.position + sliderLow.rect.min; Vector2 topRight = (Vector2)sliderHigh.position + sliderHigh.rect.max; if (Input.GetKeyDown(KeyCode.Tab)) Debug.Break(); //Debug.Log(mousePos + " " + bottomLeft + " " + topRight); if (mousePos.x > bottomLeft.x && mousePos.x < topRight.x && mousePos.y < topRight.y && mousePos.y > bottomLeft.y) return; if (Input.GetKeyDown(KeyCode.Mouse0)) { player.TappedOnTile(new Vector2i(mouseTileX, mouseTileY)); Debug.Log(mouseTileX + " " + mouseTileY); } if (Input.GetKey(KeyCode.Mouse1) || Input.GetKey(KeyCode.Mouse2)) { if (mouseTileX != lastMouseTileX || mouseTileY != lastMouseTileY || Input.GetKeyDown(KeyCode.Mouse1) || Input.GetKeyDown(KeyCode.Mouse2)) { if (!IsNotEmpty(mouseTileX, mouseTileY)) SetTile(mouseTileX, mouseTileY, Input.GetKey(KeyCode.Mouse1) ? TileType.Block : TileType.OneWay); else SetTile(mouseTileX, mouseTileY, TileType.Empty); lastMouseTileX = mouseTileX; lastMouseTileY = mouseTileY; Debug.Log(mouseTileX + " " + mouseTileY); } } } System.Random mRandomNumber; void AutoTile(TileType type, int x, int y, int rand4NeighbourTiles, int rand3NeighbourTiles, int rand2NeighbourPipeTiles, int rand2NeighbourCornerTiles, int rand1NeighbourTiles, int rand0NeighbourTiles) { if (x >= mWidth || x < 0 || y >= mHeight || y < 0) return; if (tiles[x, y] != TileType.Block) return; int tileOnLeft = tiles[x - 1, y] == tiles[x, y] ? 1 : 0; int tileOnRight = tiles[x + 1, y] == tiles[x, y] ? 1 : 0; int tileOnTop = tiles[x, y + 1] == tiles[x, y] ? 1 : 0; int tileOnBottom = tiles[x, y - 1] == tiles[x, y] ? 1 : 0; float scaleX = 1.0f; float scaleY = 1.0f; float rot = 0.0f; int id = 0; int sum = tileOnLeft + tileOnRight + tileOnTop + tileOnBottom; switch (sum) { case 0: id = 1 + mRandomNumber.Next(rand0NeighbourTiles); break; case 1: id = 1 + rand0NeighbourTiles + mRandomNumber.Next(rand1NeighbourTiles); if (tileOnRight == 1) scaleX = -1; else if (tileOnTop == 1) rot = -1; else if (tileOnBottom == 1) { rot = 1; scaleY = -1; } break; case 2: if (tileOnLeft + tileOnBottom == 2) { id = 1 + rand0NeighbourTiles + rand1NeighbourTiles + rand2NeighbourPipeTiles + mRandomNumber.Next(rand2NeighbourCornerTiles); } else if (tileOnRight + tileOnBottom == 2) { id = 1 + rand0NeighbourTiles + rand1NeighbourTiles + rand2NeighbourPipeTiles + mRandomNumber.Next(rand2NeighbourCornerTiles); scaleX = -1; } else if (tileOnTop + tileOnLeft == 2) { id = 1 + rand0NeighbourTiles + rand1NeighbourTiles + rand2NeighbourPipeTiles + mRandomNumber.Next(rand2NeighbourCornerTiles); scaleY = -1; } else if (tileOnTop + tileOnRight == 2) { id = 1 + rand0NeighbourTiles + rand1NeighbourTiles + rand2NeighbourPipeTiles + mRandomNumber.Next(rand2NeighbourCornerTiles); scaleX = -1; scaleY = -1; } else if (tileOnTop + tileOnBottom == 2) { id = 1 + rand0NeighbourTiles + rand1NeighbourTiles + mRandomNumber.Next(rand2NeighbourPipeTiles); rot = 1; } else if (tileOnRight + tileOnLeft == 2) id = 1 + rand0NeighbourTiles + rand1NeighbourTiles + mRandomNumber.Next(rand2NeighbourPipeTiles); break; case 3: id = 1 + rand0NeighbourTiles + rand1NeighbourTiles + rand2NeighbourPipeTiles + rand2NeighbourCornerTiles + mRandomNumber.Next(rand3NeighbourTiles); if (tileOnLeft == 0) { rot = 1; scaleX = -1; } else if (tileOnRight == 0) { rot = 1; scaleY = -1; } else if (tileOnBottom == 0) scaleY = -1; break; case 4: id = 1 + rand0NeighbourTiles + rand1NeighbourTiles + rand2NeighbourPipeTiles + rand2NeighbourCornerTiles + rand3NeighbourTiles + mRandomNumber.Next(rand4NeighbourTiles); break; } tilesSprites[x, y].transform.localScale = new Vector3(scaleX, scaleY, 1.0f); tilesSprites[x, y].transform.eulerAngles = new Vector3(0.0f, 0.0f, rot * 90.0f); tilesSprites[x, y].sprite = mDirtSprites[id - 1]; } public List<Sprite> mDirtSprites; void FixedUpdate() { player.BotUpdate(); } }
// --------------------------------------------------------------------------- // <copyright file="Flag.cs" company="Microsoft"> // Copyright (c) Microsoft Corporation. All rights reserved. // </copyright> // --------------------------------------------------------------------------- //----------------------------------------------------------------------- // <summary>Defines the Flag class.</summary> //----------------------------------------------------------------------- namespace Microsoft.Exchange.WebServices.Data { using System; /// <summary> /// Encapsulates information on the occurrence of a recurring appointment. /// </summary> public sealed class Flag : ComplexProperty { private ItemFlagStatus flagStatus; private DateTime startDate; private DateTime dueDate; private DateTime completeDate; /// <summary> /// Initializes a new instance of the <see cref="Flag"/> class. /// </summary> public Flag() { } /// <summary> /// Tries to read element from XML. /// </summary> /// <param name="reader">The reader.</param> /// <returns>True if element was read.</returns> internal override bool TryReadElementFromXml(EwsServiceXmlReader reader) { switch (reader.LocalName) { case XmlElementNames.FlagStatus: this.flagStatus = reader.ReadElementValue<ItemFlagStatus>(); return true; case XmlElementNames.StartDate: this.startDate = reader.ReadElementValueAsDateTime().Value; return true; case XmlElementNames.DueDate: this.dueDate = reader.ReadElementValueAsDateTime().Value; return true; case XmlElementNames.CompleteDate: this.completeDate = reader.ReadElementValueAsDateTime().Value; return true; default: return false; } } /// <summary> /// Loads from json. /// </summary> /// <param name="jsonProperty">The json property.</param> /// <param name="service">The service.</param> internal override void LoadFromJson(JsonObject jsonProperty, ExchangeService service) { foreach (string key in jsonProperty.Keys) { switch (key) { case XmlElementNames.FlagStatus: this.flagStatus = jsonProperty.ReadEnumValue<ItemFlagStatus>(key); break; case XmlElementNames.StartDate: this.startDate = service.ConvertUniversalDateTimeStringToLocalDateTime(jsonProperty.ReadAsString(key)).Value; break; case XmlElementNames.DueDate: this.dueDate = service.ConvertUniversalDateTimeStringToLocalDateTime(jsonProperty.ReadAsString(key)).Value; break; case XmlElementNames.CompleteDate: this.completeDate = service.ConvertUniversalDateTimeStringToLocalDateTime(jsonProperty.ReadAsString(key)).Value; break; default: break; } } } /// <summary> /// Writes elements to XML. /// </summary> /// <param name="writer">The writer.</param> internal override void WriteElementsToXml(EwsServiceXmlWriter writer) { writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.FlagStatus, this.FlagStatus); if (this.FlagStatus == ItemFlagStatus.Flagged && this.StartDate != null && this.DueDate != null) { writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.StartDate, this.StartDate); writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.DueDate, this.DueDate); } else if (this.FlagStatus == ItemFlagStatus.Complete && this.CompleteDate != null) { writer.WriteElementValue(XmlNamespace.Types, XmlElementNames.CompleteDate, this.CompleteDate); } } /// <summary> /// Serializes the property to a Json value. /// </summary> /// <param name="service">The service.</param> /// <returns> /// A Json value (either a JsonObject, an array of Json values, or a Json primitive) /// </returns> internal override object InternalToJson(ExchangeService service) { JsonObject jsonObject = new JsonObject(); jsonObject.Add(XmlElementNames.FlagStatus, this.FlagStatus); if (this.FlagStatus == ItemFlagStatus.Flagged && this.StartDate != null && this.DueDate != null) { jsonObject.Add(XmlElementNames.StartDate, this.StartDate); jsonObject.Add(XmlElementNames.DueDate, this.DueDate); } else if (this.FlagStatus == ItemFlagStatus.Complete && this.CompleteDate != null) { jsonObject.Add(XmlElementNames.CompleteDate, this.CompleteDate); } return jsonObject; } /// <summary> /// Validates this instance. /// </summary> internal void Validate() { EwsUtilities.ValidateParam(this.flagStatus, "FlagStatus"); } /// <summary> /// Gets or sets the flag status. /// </summary> public ItemFlagStatus FlagStatus { get { return this.flagStatus; } set { this.SetFieldValue<ItemFlagStatus>(ref this.flagStatus, value); } } /// <summary> /// Gets the start date. /// </summary> public DateTime StartDate { get { return this.startDate; } set { this.SetFieldValue<DateTime>(ref this.startDate, value); } } /// <summary> /// Gets the due date. /// </summary> public DateTime DueDate { get { return this.dueDate; } set { this.SetFieldValue<DateTime>(ref this.dueDate, value); } } /// <summary> /// Gets the complete date. /// </summary> public DateTime CompleteDate { get { return this.completeDate; } set { this.SetFieldValue<DateTime>(ref this.completeDate, value); } } } }
// // Copyright (c) Microsoft Corporation. All rights reserved. // namespace Microsoft.Zelig.Runtime.TypeSystem { using System; using System.Collections.Generic; using System.Threading; [DisableReferenceCounting] public abstract class BaseRepresentation { // // State // protected static int s_identity; private int m_identity; //--// protected CustomAttributeAssociationRepresentation[] m_customAttributes; //--// // // Constructor Methods // protected BaseRepresentation() { m_identity = Interlocked.Increment( ref s_identity ); m_customAttributes = CustomAttributeAssociationRepresentation.SharedEmptyArray; } // // MetaDataEquality Methods // public abstract bool EqualsThroughEquivalence( object obj , EquivalenceSet set ); public static bool EqualsThroughEquivalence( BaseRepresentation left , BaseRepresentation right , EquivalenceSet set ) { if(Object.ReferenceEquals( left, right )) { return true; } if(left != null && right != null) { return left.EqualsThroughEquivalence( right, set ); } return false; } public static bool ArrayEqualsThroughEquivalence<T>( T[] s , T[] d , EquivalenceSet set ) where T : BaseRepresentation { return ArrayEqualsThroughEquivalence( s, d, 0, -1, set ); } public static bool ArrayEqualsThroughEquivalence<T>( T[] s , T[] d , int offset , int count , EquivalenceSet set ) where T : BaseRepresentation { int sLen = s != null ? s.Length : 0; int dLen = d != null ? d.Length : 0; if(count < 0) { if(sLen != dLen) { return false; } count = sLen - offset; } else { if(sLen < count + offset || dLen < count + offset ) { return false; } } while(count > 0) { if(EqualsThroughEquivalence( s[offset], d[offset], set ) == false) { return false; } offset++; count--; } return true; } //--// // // Helper Methods // public virtual void ApplyTransformation( TransformationContext context ) { context.Push( this ); context.Transform( ref m_customAttributes ); context.Pop(); } //--// public void AddCustomAttribute( CustomAttributeAssociationRepresentation cca ) { m_customAttributes = ArrayUtility.AddUniqueToNotNullArray( m_customAttributes, cca ); } public void CopyCustomAttribute( CustomAttributeAssociationRepresentation caa ) { AddCustomAttribute( new CustomAttributeAssociationRepresentation( caa.CustomAttribute, this, caa.ParameterIndex ) ); } public void RemoveCustomAttribute( CustomAttributeAssociationRepresentation cca ) { m_customAttributes = ArrayUtility.RemoveUniqueFromNotNullArray( m_customAttributes, cca ); } public void RemoveCustomAttribute( CustomAttributeRepresentation ca ) { foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes) { if(caa.CustomAttribute == ca) { RemoveCustomAttribute( caa ); } } } public bool HasCustomAttribute( TypeRepresentation target ) { return FindCustomAttribute( target, -1 ) != null; } public CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target ) { return FindCustomAttribute( target, -1 ); } public List<CustomAttributeRepresentation> FindCustomAttributes( TypeRepresentation target ) { var lst = new List<CustomAttributeRepresentation>(); FindCustomAttributes( target, lst ); return lst; } public CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target , int index ) { return FindCustomAttribute( target, -1, index ); } public virtual void EnumerateCustomAttributes( CustomAttributeAssociationEnumerationCallback callback ) { foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes) { callback( caa ); } } //--// protected CustomAttributeRepresentation FindCustomAttribute( TypeRepresentation target , int paramIndex , int index ) { int pos = index >= 0 ? 0 : index; // So we don't have the double check in the loop. foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes) { if(caa.CustomAttribute.Constructor.OwnerType == target && caa.ParameterIndex == paramIndex ) { if(index == pos) { return caa.CustomAttribute; } pos++; } } return null; } protected void FindCustomAttributes( TypeRepresentation target, List<CustomAttributeRepresentation> lst ) { foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes) { if(caa.CustomAttribute.Constructor.OwnerType == target) { lst.Add( caa.CustomAttribute ); } } } //--// internal virtual void ProhibitUse( TypeSystem.Reachability reachability , bool fApply ) { reachability.ExpandProhibition( this ); foreach(CustomAttributeAssociationRepresentation caa in m_customAttributes) { reachability.ExpandProhibition( caa ); } } internal virtual void Reduce( TypeSystem.Reachability reachability , bool fApply ) { for(int i = m_customAttributes.Length; --i >= 0; ) { CustomAttributeAssociationRepresentation caa = m_customAttributes[i]; CHECKS.ASSERT( reachability.Contains( caa.Target ) == true, "{0} cannot be reachable since its owner is not in the Reachability set", caa ); if(reachability.Contains( caa.CustomAttribute.Constructor ) == false) { CHECKS.ASSERT( reachability.Contains( caa ) == false, "{0} cannot belong to both the Reachability and the Prohibition set", caa ); CHECKS.ASSERT( reachability.Contains( caa.CustomAttribute ) == false, "{0} cannot belong to both the Reachability and the Prohibition set", caa.CustomAttribute ); reachability.ExpandProhibition( caa ); reachability.ExpandProhibition( caa.CustomAttribute ); if(fApply) { if(m_customAttributes.Length == 1) { m_customAttributes = CustomAttributeAssociationRepresentation.SharedEmptyArray; return; } m_customAttributes = ArrayUtility.RemoveAtPositionFromNotNullArray( m_customAttributes, i ); } } } } //--// // // Access Methods // public int Identity { get { return m_identity; } } public CustomAttributeAssociationRepresentation[] CustomAttributes { get { return m_customAttributes; } } //--// // // Debug Methods // } }
/**************************************************************************** Tilde Copyright (c) 2008 Tantalus Media Pty Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ****************************************************************************/ namespace Tilde.LuaDebugger { partial class AutocompletePopup { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.components = new System.ComponentModel.Container(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(AutocompletePopup)); this.optionsListView = new System.Windows.Forms.ListView(); this.columnHeader1 = new System.Windows.Forms.ColumnHeader(); this.columnHeader2 = new System.Windows.Forms.ColumnHeader(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.valuesFilterButton = new System.Windows.Forms.ToolStripButton(); this.functionsFilterButton = new System.Windows.Forms.ToolStripButton(); this.tablesFilterButton = new System.Windows.Forms.ToolStripButton(); this.expressionLabel = new System.Windows.Forms.Label(); this.waitingPanel = new System.Windows.Forms.Panel(); this.progressBar = new System.Windows.Forms.ProgressBar(); this.mainPanel = new System.Windows.Forms.TableLayoutPanel(); this.tableLayoutPanel2 = new System.Windows.Forms.TableLayoutPanel(); this.errorPanel = new System.Windows.Forms.Panel(); this.errorLabel = new System.Windows.Forms.Label(); this.panel1 = new System.Windows.Forms.Panel(); this.imageList1 = new System.Windows.Forms.ImageList(this.components); this.toolStrip1.SuspendLayout(); this.waitingPanel.SuspendLayout(); this.mainPanel.SuspendLayout(); this.tableLayoutPanel2.SuspendLayout(); this.errorPanel.SuspendLayout(); this.panel1.SuspendLayout(); this.SuspendLayout(); // // optionsListView // this.optionsListView.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.optionsListView.Columns.AddRange(new System.Windows.Forms.ColumnHeader[] { this.columnHeader1, this.columnHeader2}); this.optionsListView.FullRowSelect = true; this.optionsListView.HeaderStyle = System.Windows.Forms.ColumnHeaderStyle.None; this.optionsListView.Location = new System.Drawing.Point(0, 0); this.optionsListView.Margin = new System.Windows.Forms.Padding(0); this.optionsListView.MaximumSize = new System.Drawing.Size(320, 240); this.optionsListView.Name = "optionsListView"; this.optionsListView.Size = new System.Drawing.Size(191, 182); this.optionsListView.Sorting = System.Windows.Forms.SortOrder.Ascending; this.optionsListView.TabIndex = 0; this.optionsListView.UseCompatibleStateImageBehavior = false; this.optionsListView.View = System.Windows.Forms.View.Details; this.optionsListView.ItemActivate += new System.EventHandler(this.optionsListView_ItemActivate); this.optionsListView.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.optionsListView_KeyPress); this.optionsListView.KeyDown += new System.Windows.Forms.KeyEventHandler(this.optionsListView_KeyDown); // // columnHeader1 // this.columnHeader1.DisplayIndex = 1; // // columnHeader2 // this.columnHeader2.DisplayIndex = 0; this.columnHeader2.Text = ""; // // toolStrip1 // this.toolStrip1.Dock = System.Windows.Forms.DockStyle.None; this.toolStrip1.GripStyle = System.Windows.Forms.ToolStripGripStyle.Hidden; this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.functionsFilterButton, this.tablesFilterButton, this.valuesFilterButton}); this.toolStrip1.Location = new System.Drawing.Point(0, 182); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(72, 25); this.toolStrip1.TabIndex = 1; this.toolStrip1.Text = "toolStrip1"; // // valuesFilterButton // this.valuesFilterButton.CheckOnClick = true; this.valuesFilterButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.valuesFilterButton.Image = ((System.Drawing.Image)(resources.GetObject("valuesFilterButton.Image"))); this.valuesFilterButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.valuesFilterButton.Name = "valuesFilterButton"; this.valuesFilterButton.Size = new System.Drawing.Size(23, 22); this.valuesFilterButton.Text = "Values"; this.valuesFilterButton.Click += new System.EventHandler(this.valuesFilterButton_Click); // // functionsFilterButton // this.functionsFilterButton.CheckOnClick = true; this.functionsFilterButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.functionsFilterButton.Image = ((System.Drawing.Image)(resources.GetObject("functionsFilterButton.Image"))); this.functionsFilterButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.functionsFilterButton.Name = "functionsFilterButton"; this.functionsFilterButton.Size = new System.Drawing.Size(23, 22); this.functionsFilterButton.Text = "Functions"; this.functionsFilterButton.Click += new System.EventHandler(this.functionsFilterButton_Click); // // tablesFilterButton // this.tablesFilterButton.CheckOnClick = true; this.tablesFilterButton.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image; this.tablesFilterButton.Image = ((System.Drawing.Image)(resources.GetObject("tablesFilterButton.Image"))); this.tablesFilterButton.ImageTransparentColor = System.Drawing.Color.Magenta; this.tablesFilterButton.Name = "tablesFilterButton"; this.tablesFilterButton.Size = new System.Drawing.Size(23, 22); this.tablesFilterButton.Text = "Tables"; this.tablesFilterButton.Click += new System.EventHandler(this.tablesFilterButton_Click); // // expressionLabel // this.expressionLabel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.expressionLabel.Location = new System.Drawing.Point(3, 0); this.expressionLabel.Margin = new System.Windows.Forms.Padding(3, 0, 3, 4); this.expressionLabel.Name = "expressionLabel"; this.expressionLabel.Size = new System.Drawing.Size(185, 15); this.expressionLabel.TabIndex = 2; this.expressionLabel.Text = "label1"; // // waitingPanel // this.waitingPanel.AutoSize = true; this.waitingPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.waitingPanel.Controls.Add(this.progressBar); this.waitingPanel.Location = new System.Drawing.Point(0, 19); this.waitingPanel.Margin = new System.Windows.Forms.Padding(0); this.waitingPanel.Name = "waitingPanel"; this.waitingPanel.Size = new System.Drawing.Size(191, 25); this.waitingPanel.TabIndex = 2; // // progressBar // this.progressBar.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.progressBar.Location = new System.Drawing.Point(3, 3); this.progressBar.Name = "progressBar"; this.progressBar.Size = new System.Drawing.Size(188, 19); this.progressBar.Style = System.Windows.Forms.ProgressBarStyle.Marquee; this.progressBar.TabIndex = 0; // // mainPanel // this.mainPanel.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.mainPanel.AutoSize = true; this.mainPanel.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.mainPanel.BackColor = System.Drawing.Color.Transparent; this.mainPanel.ColumnCount = 1; this.mainPanel.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.mainPanel.Controls.Add(this.optionsListView, 0, 0); this.mainPanel.Controls.Add(this.toolStrip1, 0, 1); this.mainPanel.Location = new System.Drawing.Point(0, 44); this.mainPanel.Margin = new System.Windows.Forms.Padding(0); this.mainPanel.Name = "mainPanel"; this.mainPanel.RowCount = 3; this.mainPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.mainPanel.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.mainPanel.RowStyles.Add(new System.Windows.Forms.RowStyle(System.Windows.Forms.SizeType.Absolute, 20F)); this.mainPanel.Size = new System.Drawing.Size(191, 227); this.mainPanel.TabIndex = 2; // // tableLayoutPanel2 // this.tableLayoutPanel2.AutoSize = true; this.tableLayoutPanel2.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.tableLayoutPanel2.BackColor = System.Drawing.Color.Transparent; this.tableLayoutPanel2.ColumnCount = 1; this.tableLayoutPanel2.ColumnStyles.Add(new System.Windows.Forms.ColumnStyle()); this.tableLayoutPanel2.Controls.Add(this.expressionLabel, 0, 0); this.tableLayoutPanel2.Controls.Add(this.waitingPanel, 0, 1); this.tableLayoutPanel2.Controls.Add(this.mainPanel, 0, 2); this.tableLayoutPanel2.Controls.Add(this.errorPanel, 0, 3); this.tableLayoutPanel2.Location = new System.Drawing.Point(0, 0); this.tableLayoutPanel2.Margin = new System.Windows.Forms.Padding(0); this.tableLayoutPanel2.Name = "tableLayoutPanel2"; this.tableLayoutPanel2.RowCount = 4; this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.RowStyles.Add(new System.Windows.Forms.RowStyle()); this.tableLayoutPanel2.Size = new System.Drawing.Size(191, 290); this.tableLayoutPanel2.TabIndex = 4; // // errorPanel // this.errorPanel.AutoSize = true; this.errorPanel.Controls.Add(this.errorLabel); this.errorPanel.Location = new System.Drawing.Point(3, 274); this.errorPanel.Name = "errorPanel"; this.errorPanel.Size = new System.Drawing.Size(29, 13); this.errorPanel.TabIndex = 6; // // errorLabel // this.errorLabel.AutoSize = true; this.errorLabel.ForeColor = System.Drawing.Color.Red; this.errorLabel.Location = new System.Drawing.Point(-3, 0); this.errorLabel.MaximumSize = new System.Drawing.Size(188, 0); this.errorLabel.Name = "errorLabel"; this.errorLabel.Size = new System.Drawing.Size(29, 13); this.errorLabel.TabIndex = 0; this.errorLabel.Text = "Error"; // // panel1 // this.panel1.AutoSize = true; this.panel1.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.panel1.BackColor = System.Drawing.Color.Transparent; this.panel1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D; this.panel1.Controls.Add(this.tableLayoutPanel2); this.panel1.Location = new System.Drawing.Point(1, 1); this.panel1.Name = "panel1"; this.panel1.Size = new System.Drawing.Size(195, 294); this.panel1.TabIndex = 5; // // imageList1 // this.imageList1.ColorDepth = System.Windows.Forms.ColorDepth.Depth8Bit; this.imageList1.ImageSize = new System.Drawing.Size(16, 16); this.imageList1.TransparentColor = System.Drawing.Color.Transparent; // // AutocompletePopup // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.AutoSizeMode = System.Windows.Forms.AutoSizeMode.GrowAndShrink; this.ClientSize = new System.Drawing.Size(475, 358); this.Controls.Add(this.panel1); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None; this.KeyPreview = true; this.Name = "AutocompletePopup"; this.ShowInTaskbar = false; this.StartPosition = System.Windows.Forms.FormStartPosition.Manual; this.Text = "AutocompletePopup"; this.Deactivate += new System.EventHandler(this.AutocompletePopup_Deactivate); this.KeyDown += new System.Windows.Forms.KeyEventHandler(this.AutocompletePopup_KeyDown); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); this.waitingPanel.ResumeLayout(false); this.mainPanel.ResumeLayout(false); this.mainPanel.PerformLayout(); this.tableLayoutPanel2.ResumeLayout(false); this.tableLayoutPanel2.PerformLayout(); this.errorPanel.ResumeLayout(false); this.errorPanel.PerformLayout(); this.panel1.ResumeLayout(false); this.panel1.PerformLayout(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.ListView optionsListView; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton valuesFilterButton; private System.Windows.Forms.ToolStripButton functionsFilterButton; private System.Windows.Forms.ToolStripButton tablesFilterButton; private System.Windows.Forms.Label expressionLabel; private System.Windows.Forms.Panel waitingPanel; private System.Windows.Forms.ProgressBar progressBar; private System.Windows.Forms.TableLayoutPanel mainPanel; private System.Windows.Forms.TableLayoutPanel tableLayoutPanel2; private System.Windows.Forms.ColumnHeader columnHeader1; private System.Windows.Forms.Panel panel1; private System.Windows.Forms.ImageList imageList1; private System.Windows.Forms.ColumnHeader columnHeader2; private System.Windows.Forms.Panel errorPanel; private System.Windows.Forms.Label errorLabel; } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace RestSamples.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 0.17.0.0 // Changes may cause incorrect behavior and will be lost if the code is // regenerated. namespace Microsoft.Azure.Management.DataLake.Store { using System; using System.Linq; using System.Collections.Generic; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; using Microsoft.Rest; using Microsoft.Rest.Serialization; using Newtonsoft.Json; using Microsoft.Rest.Azure.OData; using Microsoft.Rest.Azure; using Models; /// <summary> /// AccountOperations operations. /// </summary> internal partial class AccountOperations : IServiceOperations<DataLakeStoreAccountManagementClient>, IAccountOperations { /// <summary> /// Tests the existence of the specified Data Lake Store firewall rule. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account from which to test the firewall /// rule's existence. /// </param> /// <param name='firewallRuleName'> /// The name of the firewall rule to test for existence. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<bool>> FirewallRuleExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, string firewallRuleName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (firewallRuleName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "firewallRuleName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("firewallRuleName", firewallRuleName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "GetFirewallRule", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}/firewallRules/{firewallRuleName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName)); _url = _url.Replace("{firewallRuleName}", Uri.EscapeDataString(firewallRuleName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; if(_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase)) { var _toReturn = new AzureOperationResponse<bool>(); _toReturn.Request = _httpRequest; _toReturn.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); _toReturn.Body = false; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _toReturn); } return _toReturn; } } } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<bool>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _result.Body = true; } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } /// <summary> /// Tests whether the specified Data Lake Store account exists. /// </summary> /// <param name='resourceGroupName'> /// The name of the Azure resource group that contains the Data Lake Store /// account. /// </param> /// <param name='accountName'> /// The name of the Data Lake Store account to test existence of. /// </param> /// <param name='customHeaders'> /// Headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="ValidationException"> /// Thrown when a required parameter is null /// </exception> /// <return> /// A response object containing the response body and response headers. /// </return> public async Task<AzureOperationResponse<bool>> ExistsWithHttpMessagesAsync(string resourceGroupName, string accountName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)) { if (resourceGroupName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "resourceGroupName"); } if (accountName == null) { throw new ValidationException(ValidationRules.CannotBeNull, "accountName"); } if (this.Client.ApiVersion == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.ApiVersion"); } if (this.Client.SubscriptionId == null) { throw new ValidationException(ValidationRules.CannotBeNull, "this.Client.SubscriptionId"); } // Tracing bool _shouldTrace = ServiceClientTracing.IsEnabled; string _invocationId = null; if (_shouldTrace) { _invocationId = ServiceClientTracing.NextInvocationId.ToString(); Dictionary<string, object> tracingParameters = new Dictionary<string, object>(); tracingParameters.Add("resourceGroupName", resourceGroupName); tracingParameters.Add("accountName", accountName); tracingParameters.Add("cancellationToken", cancellationToken); ServiceClientTracing.Enter(_invocationId, this, "Get", tracingParameters); } // Construct URL var _baseUrl = this.Client.BaseUri.AbsoluteUri; var _url = new Uri(new Uri(_baseUrl + (_baseUrl.EndsWith("/") ? "" : "/")), "subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.DataLakeStore/accounts/{accountName}").ToString(); _url = _url.Replace("{resourceGroupName}", Uri.EscapeDataString(resourceGroupName)); _url = _url.Replace("{accountName}", Uri.EscapeDataString(accountName)); _url = _url.Replace("{subscriptionId}", Uri.EscapeDataString(this.Client.SubscriptionId)); List<string> _queryParameters = new List<string>(); if (this.Client.ApiVersion != null) { _queryParameters.Add(string.Format("api-version={0}", Uri.EscapeDataString(this.Client.ApiVersion))); } if (_queryParameters.Count > 0) { _url += "?" + string.Join("&", _queryParameters); } // Create HTTP transport objects HttpRequestMessage _httpRequest = new HttpRequestMessage(); HttpResponseMessage _httpResponse = null; _httpRequest.Method = new HttpMethod("GET"); _httpRequest.RequestUri = new Uri(_url); // Set Headers if (this.Client.GenerateClientRequestId != null && this.Client.GenerateClientRequestId.Value) { _httpRequest.Headers.TryAddWithoutValidation("x-ms-client-request-id", Guid.NewGuid().ToString()); } if (this.Client.AcceptLanguage != null) { if (_httpRequest.Headers.Contains("accept-language")) { _httpRequest.Headers.Remove("accept-language"); } _httpRequest.Headers.TryAddWithoutValidation("accept-language", this.Client.AcceptLanguage); } if (customHeaders != null) { foreach(var _header in customHeaders) { if (_httpRequest.Headers.Contains(_header.Key)) { _httpRequest.Headers.Remove(_header.Key); } _httpRequest.Headers.TryAddWithoutValidation(_header.Key, _header.Value); } } // Serialize Request string _requestContent = null; // Set Credentials if (this.Client.Credentials != null) { cancellationToken.ThrowIfCancellationRequested(); await this.Client.Credentials.ProcessHttpRequestAsync(_httpRequest, cancellationToken).ConfigureAwait(false); } // Send Request if (_shouldTrace) { ServiceClientTracing.SendRequest(_invocationId, _httpRequest); } cancellationToken.ThrowIfCancellationRequested(); _httpResponse = await this.Client.HttpClient.SendAsync(_httpRequest, cancellationToken).ConfigureAwait(false); if (_shouldTrace) { ServiceClientTracing.ReceiveResponse(_invocationId, _httpResponse); } HttpStatusCode _statusCode = _httpResponse.StatusCode; cancellationToken.ThrowIfCancellationRequested(); string _responseContent = null; if ((int)_statusCode != 200) { var ex = new CloudException(string.Format("Operation returned an invalid status code '{0}'", _statusCode)); try { _responseContent = await _httpResponse.Content.ReadAsStringAsync().ConfigureAwait(false); CloudError _errorBody = SafeJsonConvert.DeserializeObject<CloudError>(_responseContent, this.Client.DeserializationSettings); if (_errorBody != null) { ex = new CloudException(_errorBody.Message); ex.Body = _errorBody; if (_httpResponse.StatusCode == HttpStatusCode.NotFound && ex.Body.Code.Equals("ResourceNotFound", StringComparison.OrdinalIgnoreCase)) { var _toReturn = new AzureOperationResponse<bool>(); _toReturn.Request = _httpRequest; _toReturn.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _toReturn.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); _toReturn.Body = false; if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _toReturn); } return _toReturn; } } } } catch (JsonException) { // Ignore the exception } ex.Request = new HttpRequestMessageWrapper(_httpRequest, _requestContent); ex.Response = new HttpResponseMessageWrapper(_httpResponse, _responseContent); if (_httpResponse.Headers.Contains("x-ms-request-id")) { ex.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } if (_shouldTrace) { ServiceClientTracing.Error(_invocationId, ex); } _httpRequest.Dispose(); if (_httpResponse != null) { _httpResponse.Dispose(); } throw ex; } // Create Result var _result = new AzureOperationResponse<bool>(); _result.Request = _httpRequest; _result.Response = _httpResponse; if (_httpResponse.Headers.Contains("x-ms-request-id")) { _result.RequestId = _httpResponse.Headers.GetValues("x-ms-request-id").FirstOrDefault(); } // Deserialize Response if ((int)_statusCode == 200) { _result.Body = true; } if (_shouldTrace) { ServiceClientTracing.Exit(_invocationId, _result); } return _result; } } }
using System; using NUnit.Framework; using System.Collections.ObjectModel; namespace OpenQA.Selenium { [TestFixture] public class ExecutingAsyncJavascriptTest : DriverTestFixture { private IJavaScriptExecutor executor; private TimeSpan originalTimeout = TimeSpan.MinValue; [SetUp] public void SetUpEnvironment() { if (driver is IJavaScriptExecutor) { executor = (IJavaScriptExecutor)driver; } try { originalTimeout = driver.Manage().Timeouts().AsynchronousJavaScript; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(1); } catch (NotImplementedException) { } } [TearDown] public void TearDownEnvironment() { driver.Manage().Timeouts().AsynchronousJavaScript = originalTimeout; } [Test] public void ShouldNotTimeoutIfCallbackInvokedImmediately() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1](123);"); Assert.IsInstanceOf<long>(result); Assert.AreEqual(123, (long)result); } [Test] public void ShouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NeitherNullNorUndefined() { driver.Url = ajaxyPage; Assert.AreEqual(123, (long)executor.ExecuteAsyncScript("arguments[arguments.length - 1](123);")); driver.Url = ajaxyPage; Assert.AreEqual("abc", executor.ExecuteAsyncScript("arguments[arguments.length - 1]('abc');").ToString()); driver.Url = ajaxyPage; Assert.IsFalse((bool)executor.ExecuteAsyncScript("arguments[arguments.length - 1](false);")); driver.Url = ajaxyPage; Assert.IsTrue((bool)executor.ExecuteAsyncScript("arguments[arguments.length - 1](true);")); } [Test] public void ShouldBeAbleToReturnJavascriptPrimitivesFromAsyncScripts_NullAndUndefined() { driver.Url = ajaxyPage; Assert.IsNull(executor.ExecuteAsyncScript("arguments[arguments.length - 1](null);")); Assert.IsNull(executor.ExecuteAsyncScript("arguments[arguments.length - 1]();")); } [Test] public void ShouldBeAbleToReturnAnArrayLiteralFromAnAsyncScript() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1]([]);"); Assert.IsNotNull(result); Assert.IsInstanceOf<ReadOnlyCollection<object>>(result); Assert.AreEqual(0, ((ReadOnlyCollection<object>)result).Count); } [Test] public void ShouldBeAbleToReturnAnArrayObjectFromAnAsyncScript() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1](new Array());"); Assert.IsNotNull(result); Assert.IsInstanceOf<ReadOnlyCollection<object>>(result); Assert.AreEqual(0, ((ReadOnlyCollection<object>)result).Count); } [Test] public void ShouldBeAbleToReturnArraysOfPrimitivesFromAsyncScripts() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1]([null, 123, 'abc', true, false]);"); Assert.IsNotNull(result); Assert.IsInstanceOf<ReadOnlyCollection<object>>(result); ReadOnlyCollection<object> resultList = result as ReadOnlyCollection<object>; Assert.AreEqual(5, resultList.Count); Assert.IsNull(resultList[0]); Assert.AreEqual(123, (long)resultList[1]); Assert.AreEqual("abc", resultList[2].ToString()); Assert.IsTrue((bool)resultList[3]); Assert.IsFalse((bool)resultList[4]); } [Test] public void ShouldBeAbleToReturnWebElementsFromAsyncScripts() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1](document.body);"); Assert.IsInstanceOf<IWebElement>(result); Assert.AreEqual("body", ((IWebElement)result).TagName.ToLower()); } [Test] public void ShouldBeAbleToReturnArraysOfWebElementsFromAsyncScripts() { driver.Url = ajaxyPage; object result = executor.ExecuteAsyncScript("arguments[arguments.length - 1]([document.body, document.body]);"); Assert.IsNotNull(result); Assert.IsInstanceOf<ReadOnlyCollection<IWebElement>>(result); ReadOnlyCollection<IWebElement> resultsList = (ReadOnlyCollection<IWebElement>)result; Assert.AreEqual(2, resultsList.Count); Assert.IsInstanceOf<IWebElement>(resultsList[0]); Assert.IsInstanceOf<IWebElement>(resultsList[1]); Assert.AreEqual("body", ((IWebElement)resultsList[0]).TagName.ToLower()); Assert.AreEqual(((IWebElement)resultsList[0]), ((IWebElement)resultsList[1])); } [Test] public void ShouldTimeoutIfScriptDoesNotInvokeCallback() { driver.Url = ajaxyPage; Assert.Throws<WebDriverTimeoutException>(() => executor.ExecuteAsyncScript("return 1 + 2;")); } [Test] public void ShouldTimeoutIfScriptDoesNotInvokeCallbackWithAZeroTimeout() { driver.Url = ajaxyPage; Assert.Throws<WebDriverTimeoutException>(() => executor.ExecuteAsyncScript("window.setTimeout(function() {}, 0);")); } [Test] public void ShouldNotTimeoutIfScriptCallsbackInsideAZeroTimeout() { driver.Url = ajaxyPage; executor.ExecuteAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.setTimeout(function() { callback(123); }, 0)"); } [Test] public void ShouldTimeoutIfScriptDoesNotInvokeCallbackWithLongTimeout() { driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromMilliseconds(500); driver.Url = ajaxyPage; Assert.Throws<WebDriverTimeoutException>(() => executor.ExecuteAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.setTimeout(callback, 1500);")); } [Test] public void ShouldDetectPageLoadsWhileWaitingOnAnAsyncScriptAndReturnAnError() { driver.Url = ajaxyPage; Assert.Throws<InvalidOperationException>(() => executor.ExecuteAsyncScript("window.location = '" + dynamicPage + "';")); } [Test] public void ShouldCatchErrorsWhenExecutingInitialScript() { driver.Url = ajaxyPage; Assert.Throws<InvalidOperationException>(() => executor.ExecuteAsyncScript("throw Error('you should catch this!');")); } [Test] public void ShouldBeAbleToExecuteAsynchronousScripts() { // Reset the timeout to the 30-second default instead of zero. driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(30); driver.Url = ajaxyPage; IWebElement typer = driver.FindElement(By.Name("typer")); typer.SendKeys("bob"); Assert.AreEqual("bob", typer.GetAttribute("value")); driver.FindElement(By.Id("red")).Click(); driver.FindElement(By.Name("submit")).Click(); Assert.AreEqual(1, GetNumberOfDivElements(), "There should only be 1 DIV at this point, which is used for the butter message"); driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(10); string text = (string)executor.ExecuteAsyncScript( "var callback = arguments[arguments.length - 1];" + "window.registerListener(arguments[arguments.length - 1]);"); Assert.AreEqual("bob", text); Assert.AreEqual("", typer.GetAttribute("value")); Assert.AreEqual(2, GetNumberOfDivElements(), "There should be 1 DIV (for the butter message) + 1 DIV (for the new label)"); } [Test] public void ShouldBeAbleToPassMultipleArgumentsToAsyncScripts() { driver.Url = ajaxyPage; long result = (long)executor.ExecuteAsyncScript("arguments[arguments.length - 1](arguments[0] + arguments[1]);", 1, 2); Assert.AreEqual(3, result); } [Test] public void ShouldBeAbleToMakeXMLHttpRequestsAndWaitForTheResponse() { string script = "var url = arguments[0];" + "var callback = arguments[arguments.length - 1];" + // Adapted from http://www.quirksmode.org/js/xmlhttp.html "var XMLHttpFactories = [" + " function () {return new XMLHttpRequest()}," + " function () {return new ActiveXObject('Msxml2.XMLHTTP')}," + " function () {return new ActiveXObject('Msxml3.XMLHTTP')}," + " function () {return new ActiveXObject('Microsoft.XMLHTTP')}" + "];" + "var xhr = false;" + "while (!xhr && XMLHttpFactories.length) {" + " try {" + " xhr = XMLHttpFactories.shift().call();" + " } catch (e) {}" + "}" + "if (!xhr) throw Error('unable to create XHR object');" + "xhr.open('GET', url, true);" + "xhr.onreadystatechange = function() {" + " if (xhr.readyState == 4) callback(xhr.responseText);" + "};" + "xhr.send();"; driver.Url = ajaxyPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(3); string response = (string)executor.ExecuteAsyncScript(script, sleepingPage + "?time=2"); Assert.AreEqual("<html><head><title>Done</title></head><body>Slept for 2s</body></html>", response.Trim()); } [Test] [IgnoreBrowser(Browser.Android, "Does not handle async alerts")] [IgnoreBrowser(Browser.Chrome, "Does not handle async alerts")] [IgnoreBrowser(Browser.Edge, "Does not handle async alerts")] [IgnoreBrowser(Browser.HtmlUnit, "Does not handle async alerts")] [IgnoreBrowser(Browser.IE, "Handling async alerts isn't done by the ExecuteAsyncScript command.")] [IgnoreBrowser(Browser.IPhone, "Does not handle async alerts")] [IgnoreBrowser(Browser.Opera, "Does not handle async alerts")] [IgnoreBrowser(Browser.Safari, "Does not handle async alerts")] [IgnoreBrowser(Browser.Firefox, "Unexpected alert from JavaScript not handled properly. Spec difference.")] public void ThrowsIfScriptTriggersAlert() { driver.Url = simpleTestPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); try { ((IJavaScriptExecutor)driver).ExecuteAsyncScript( "setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('Look! An alert!'); }, 50);"); Assert.Fail("Expected UnhandledAlertException"); } catch (UnhandledAlertException) { // Expected exception } // Shouldn't throw string title = driver.Title; } [Test] [IgnoreBrowser(Browser.Android, "Does not handle async alerts")] [IgnoreBrowser(Browser.Chrome, "Does not handle async alerts")] [IgnoreBrowser(Browser.Edge, "Does not handle async alerts")] [IgnoreBrowser(Browser.HtmlUnit, "Does not handle async alerts")] [IgnoreBrowser(Browser.IE, "Handling async alerts isn't done by the ExecuteAsyncScript command.")] [IgnoreBrowser(Browser.IPhone, "Does not handle async alerts")] [IgnoreBrowser(Browser.Opera, "Does not handle async alerts")] [IgnoreBrowser(Browser.Safari, "Does not handle async alerts")] [IgnoreBrowser(Browser.Firefox, "Unexpected alert from JavaScript not handled properly. Spec difference.")] public void ThrowsIfAlertHappensDuringScript() { driver.Url = slowLoadingAlertPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); try { ((IJavaScriptExecutor)driver).ExecuteAsyncScript("setTimeout(arguments[0], 1000);"); Assert.Fail("Expected UnhandledAlertException"); } catch (UnhandledAlertException) { //Expected exception } // Shouldn't throw string title = driver.Title; } [Test] [IgnoreBrowser(Browser.Android, "Does not handle async alerts")] [IgnoreBrowser(Browser.Chrome, "Does not handle async alerts")] [IgnoreBrowser(Browser.Edge, "Does not handle async alerts")] [IgnoreBrowser(Browser.HtmlUnit, "Does not handle async alerts")] [IgnoreBrowser(Browser.IE, "Handling async alerts isn't done by the ExecuteAsyncScript command.")] [IgnoreBrowser(Browser.IPhone, "Does not handle async alerts")] [IgnoreBrowser(Browser.Opera, "Does not handle async alerts")] [IgnoreBrowser(Browser.Safari, "Does not handle async alerts")] [IgnoreBrowser(Browser.Firefox, "Unexpected alert from JavaScript not handled properly. Spec difference.")] public void ThrowsIfScriptTriggersAlertWhichTimesOut() { driver.Url = simpleTestPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); try { ((IJavaScriptExecutor)driver) .ExecuteAsyncScript("setTimeout(function() { window.alert('Look! An alert!'); }, 50);"); Assert.Fail("Expected UnhandledAlertException"); } catch (UnhandledAlertException) { // Expected exception } // Shouldn't throw string title = driver.Title; } [Test] [IgnoreBrowser(Browser.Android, "Does not handle async alerts")] [IgnoreBrowser(Browser.Chrome, "Does not handle async alerts")] [IgnoreBrowser(Browser.Edge, "Does not handle async alerts")] [IgnoreBrowser(Browser.HtmlUnit, "Does not handle async alerts")] [IgnoreBrowser(Browser.IE, "Handling async alerts isn't done by the ExecuteAsyncScript command.")] [IgnoreBrowser(Browser.IPhone, "Does not handle async alerts")] [IgnoreBrowser(Browser.Opera, "Does not handle async alerts")] [IgnoreBrowser(Browser.Safari, "Does not handle async alerts")] [IgnoreBrowser(Browser.Firefox, "Unexpected alert from JavaScript not handled properly. Spec difference.")] public void ThrowsIfAlertHappensDuringScriptWhichTimesOut() { driver.Url = slowLoadingAlertPage; driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); try { ((IJavaScriptExecutor)driver).ExecuteAsyncScript(""); Assert.Fail("Expected UnhandledAlertException"); } catch (UnhandledAlertException) { //Expected exception } // Shouldn't throw string title = driver.Title; } [Test] [IgnoreBrowser(Browser.Android, "Does not handle async alerts")] [IgnoreBrowser(Browser.Chrome, "Does not handle async alerts")] [IgnoreBrowser(Browser.Edge, "Does not handle async alerts")] [IgnoreBrowser(Browser.HtmlUnit, "Does not handle async alerts")] [IgnoreBrowser(Browser.IE, "Handling async alerts isn't done by the ExecuteAsyncScript command.")] [IgnoreBrowser(Browser.IPhone, "Does not handle async alerts")] [IgnoreBrowser(Browser.Opera, "Does not handle async alerts")] [IgnoreBrowser(Browser.Safari, "Does not handle async alerts")] [IgnoreBrowser(Browser.Firefox, "Unexpected alert from JavaScript not handled properly. Spec difference.")] public void IncludesAlertTextInUnhandledAlertException() { driver.Manage().Timeouts().AsynchronousJavaScript = TimeSpan.FromSeconds(5); string alertText = "Look! An alert!"; try { ((IJavaScriptExecutor)driver).ExecuteAsyncScript( "setTimeout(arguments[0], 200) ; setTimeout(function() { window.alert('" + alertText + "'); }, 50);"); Assert.Fail("Expected UnhandledAlertException"); } catch (UnhandledAlertException e) { Assert.AreEqual(alertText, e.AlertText); } } private long GetNumberOfDivElements() { IJavaScriptExecutor jsExecutor = driver as IJavaScriptExecutor; // Selenium does not support "findElements" yet, so we have to do this through a script. return (long)jsExecutor.ExecuteScript("return document.getElementsByTagName('div').length;"); } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Runtime.InteropServices; namespace System.IO { partial class FileSystemInfo : IFileSystemObject { /// <summary>The last cached stat information about the file.</summary> private Interop.Sys.FileStatus _fileStatus; /// <summary>Whether the target is a symlink.</summary> private bool _isSymlink; /// <summary> /// Whether we've successfully cached a stat structure. /// -1 if we need to refresh _fileStatus, 0 if we've successfully cached one, /// or any other value that serves as an errno error code from the /// last time we tried and failed to refresh _fileStatus. /// </summary> private int _fileStatusInitialized = -1; internal IFileSystemObject FileSystemObject { get { return this; } } internal void Invalidate() { _fileStatusInitialized = -1; } FileAttributes IFileSystemObject.Attributes { get { EnsureStatInitialized(); FileAttributes attrs = default(FileAttributes); if (IsDirectoryAssumesInitialized) { attrs |= FileAttributes.Directory; } if (IsReadOnlyAssumesInitialized) { attrs |= FileAttributes.ReadOnly; } if (_isSymlink) { attrs |= FileAttributes.ReparsePoint; } if (Path.GetFileName(FullPath).StartsWith(".")) { attrs |= FileAttributes.Hidden; } return attrs != default(FileAttributes) ? attrs : FileAttributes.Normal; } set { // Validate that only flags from the attribute are being provided. This is an // approximation for the validation done by the Win32 function. const FileAttributes allValidFlags = FileAttributes.Archive | FileAttributes.Compressed | FileAttributes.Device | FileAttributes.Directory | FileAttributes.Encrypted | FileAttributes.Hidden | FileAttributes.Hidden | FileAttributes.IntegrityStream | FileAttributes.Normal | FileAttributes.NoScrubData | FileAttributes.NotContentIndexed | FileAttributes.Offline | FileAttributes.ReadOnly | FileAttributes.ReparsePoint | FileAttributes.SparseFile | FileAttributes.System | FileAttributes.Temporary; if ((value & ~allValidFlags) != 0) { throw new ArgumentException(SR.Arg_InvalidFileAttrs, "value"); } // The only thing we can reasonably change is whether the file object is readonly, // just changing its permissions accordingly. EnsureStatInitialized(); IsReadOnlyAssumesInitialized = (value & FileAttributes.ReadOnly) != 0; _fileStatusInitialized = -1; } } /// <summary>Gets whether stat reported this system object as a directory.</summary> private bool IsDirectoryAssumesInitialized { get { return (_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFDIR; } } /// <summary> /// Gets or sets whether the file is read-only. This is based on the read/write/execute /// permissions of the object. /// </summary> private bool IsReadOnlyAssumesInitialized { get { Interop.Sys.Permissions readBit, writeBit; if (_fileStatus.Uid == Interop.Sys.GetEUid()) // does the user effectively own the file? { readBit = Interop.Sys.Permissions.S_IRUSR; writeBit = Interop.Sys.Permissions.S_IWUSR; } else if (_fileStatus.Gid == Interop.Sys.GetEGid()) // does the user belong to a group that effectively owns the file? { readBit = Interop.Sys.Permissions.S_IRGRP; writeBit = Interop.Sys.Permissions.S_IWGRP; } else // everyone else { readBit = Interop.Sys.Permissions.S_IROTH; writeBit = Interop.Sys.Permissions.S_IWOTH; } return (_fileStatus.Mode & (int)readBit) != 0 && // has read permission (_fileStatus.Mode & (int)writeBit) == 0; // but not write permission } set { int newMode = _fileStatus.Mode; if (value) // true if going from writable to readable, false if going from readable to writable { // Take away all write permissions from user/group/everyone newMode &= ~(int)(Interop.Sys.Permissions.S_IWUSR | Interop.Sys.Permissions.S_IWGRP | Interop.Sys.Permissions.S_IWOTH); } else if ((newMode & (int)Interop.Sys.Permissions.S_IRUSR) != 0) { // Give write permission to the owner if the owner has read permission newMode |= (int)Interop.Sys.Permissions.S_IWUSR; } // Change the permissions on the file if (newMode != _fileStatus.Mode) { bool isDirectory = this is DirectoryInfo; Interop.CheckIo(Interop.Sys.ChMod(FullPath, newMode), FullPath, isDirectory); } } } bool IFileSystemObject.Exists { get { if (_fileStatusInitialized == -1) { Refresh(); } return _fileStatusInitialized == 0 && // avoid throwing if Refresh failed; instead just return false (this is DirectoryInfo) == IsDirectoryAssumesInitialized; } } DateTimeOffset IFileSystemObject.CreationTime { get { EnsureStatInitialized(); return (_fileStatus.Flags & Interop.Sys.FileStatusFlags.HasBirthTime) != 0 ? DateTimeOffset.FromUnixTimeSeconds(_fileStatus.BirthTime).ToLocalTime() : default(DateTimeOffset); } set { // The ctime in Unix can be interpreted differently by different formats so there isn't // a reliable way to set this; however, we can't just do nothing since the FileSystemWatcher // specifically looks for this call to make a Metatdata Change, so we should set the // LastAccessTime of the file to cause the metadata change we need. LastAccessTime = LastAccessTime; } } DateTimeOffset IFileSystemObject.LastAccessTime { get { EnsureStatInitialized(); return DateTimeOffset.FromUnixTimeSeconds(_fileStatus.ATime).ToLocalTime(); } set { SetAccessWriteTimes(value.ToUnixTimeSeconds(), null); } } DateTimeOffset IFileSystemObject.LastWriteTime { get { EnsureStatInitialized(); return DateTimeOffset.FromUnixTimeSeconds(_fileStatus.MTime).ToLocalTime(); } set { SetAccessWriteTimes(null, value.ToUnixTimeSeconds()); } } private void SetAccessWriteTimes(long? accessTime, long? writeTime) { _fileStatusInitialized = -1; // force a refresh so that we have an up-to-date times for values not being overwritten EnsureStatInitialized(); Interop.Sys.UTimBuf buf; buf.AcTime = accessTime ?? _fileStatus.ATime; buf.ModTime = writeTime ?? _fileStatus.MTime; bool isDirectory = this is DirectoryInfo; Interop.CheckIo(Interop.Sys.UTime(FullPath, ref buf), FullPath, isDirectory); _fileStatusInitialized = -1; } long IFileSystemObject.Length { get { EnsureStatInitialized(); return _fileStatus.Size; } } void IFileSystemObject.Refresh() { // This should not throw, instead we store the result so that we can throw it // when someone actually accesses a property. // Use LStat so that we don't follow a symlink, at least not initially. // If we find that it is a symlink, we can then use Stat to get the real data // but remember that this is a symlink so we can report it appropriately in the // attributes we give back. Note that this behavior differs from Windows, which // always does the effective equivalent of LStat. But that also means that functionality // like EnumerateFiles would fail on a symlink to a directory, and given their prevalence // on unix systems, that would be quite problematic. int result = Interop.Sys.LStat(FullPath, out _fileStatus); if (result >= 0) { // Successfully got stats. if ((_fileStatus.Mode & Interop.Sys.FileTypes.S_IFMT) == Interop.Sys.FileTypes.S_IFLNK) { // If it's a symlink, get the stats for the actual target. _isSymlink = true; result = Interop.Sys.Stat(FullPath, out _fileStatus); if (result >= 0) { _fileStatusInitialized = 0; return; } } else { _fileStatusInitialized = 0; return; } } // Couldn't get stats on the object. var errorInfo = Interop.Sys.GetLastErrorInfo(); _fileStatusInitialized = errorInfo.RawErrno; } private void EnsureStatInitialized() { if (_fileStatusInitialized == -1) { Refresh(); } if (_fileStatusInitialized != 0) { int errno = _fileStatusInitialized; _fileStatusInitialized = -1; var errorInfo = new Interop.ErrorInfo(errno); // Windows distinguishes between whether the directory or the file isn't found, // and throws a different exception in these cases. We attempt to approximate that // here; there is a race condition here, where something could change between // when the error occurs and our checks, but it's the best we can do, and the // worst case in such a race condition (which could occur if the file system is // being manipulated concurrently with these checks) is that we throw a // FileNotFoundException instead of DirectoryNotFoundexception. // directoryError is true only if a FileNotExists error was provided and the parent // directory of the file represented by _fullPath is nonexistent bool directoryError = (errorInfo.Error == Interop.Error.ENOENT && !Directory.Exists(Path.GetDirectoryName(PathHelpers.TrimEndingDirectorySeparator(FullPath)))); // The destFile's path is invalid throw Interop.GetExceptionForIoErrno(errorInfo, FullPath, directoryError); } } } }
// This file is part of the C5 Generic Collection Library for C# and CLI // See https://github.com/sestoft/C5/blob/master/LICENSE for licensing details. using NUnit.Framework; using System; namespace C5.Tests.arrays.circularqueue { using CollectionOfInt = CircularQueue<int>; [TestFixture] public class GenericTesters { [Test] public void TestEvents() { CollectionOfInt factory() { return new CollectionOfInt(); } new C5.Tests.Templates.Events.QueueTester<CollectionOfInt>().Test(factory); new C5.Tests.Templates.Events.StackTester<CollectionOfInt>().Test(factory); } //[Test] //public void Extensible() //{ // TODO: Test Circular Queue for Clone(?) and Serializable // C5.Tests.Templates.Extensible.Clone.Tester<CollectionOfInt>(); // C5.Tests.Templates.Extensible.Serialization.Tester<CollectionOfInt>(); //} } //[TestFixture] public class Template { [SetUp] public void Init() { } [Test] public void LeTest() { } [TearDown] public void Dispose() { } } [TestFixture] public class Formatting { private CircularQueue<int> coll; private IFormatProvider rad16; [SetUp] public void Init() { coll = new CircularQueue<int>(); rad16 = new RadixFormatProvider(16); } [TearDown] public void Dispose() { coll = null; rad16 = null; } [Test] public void Format() { Assert.AreEqual("{ }", coll.ToString()); foreach (int i in new int[] { -4, 28, 129, 65530 }) { coll.Enqueue(i); } Assert.AreEqual("{ -4, 28, 129, 65530 }", coll.ToString()); Assert.AreEqual("{ -4, 1C, 81, FFFA }", coll.ToString(null, rad16)); Assert.AreEqual("{ -4, 28, 129... }", coll.ToString("L14", null)); Assert.AreEqual("{ -4, 1C, 81... }", coll.ToString("L14", rad16)); } } [TestFixture] public class CircularQueue { private CircularQueue<int> queue; [SetUp] public void Init() { queue = new CircularQueue<int>(); } private void loadup1() { queue.Enqueue(11); queue.Enqueue(12); queue.Enqueue(13); queue.Dequeue(); queue.Enqueue(103); queue.Enqueue(14); queue.Enqueue(15); } private void loadup2() { loadup1(); for (int i = 0; i < 4; i++) { queue.Dequeue(); queue.Enqueue(1000 + i); } } private void loadup3() { for (int i = 0; i < 18; i++) { queue.Enqueue(i); Assert.IsTrue(queue.Check()); } for (int i = 0; i < 14; i++) { Assert.IsTrue(queue.Check()); queue.Dequeue(); } } [Test] public void Expand() { Assert.IsTrue(queue.Check()); loadup3(); Assert.IsTrue(IC.Eq(queue, 14, 15, 16, 17)); } [Test] public void Simple() { loadup1(); Assert.IsTrue(queue.Check()); Assert.AreEqual(5, queue.Count); Assert.IsTrue(IC.Eq(queue, 12, 13, 103, 14, 15)); Assert.AreEqual(12, queue.Choose()); } [Test] public void Stack() { queue.Push(1); Assert.IsTrue(queue.Check()); queue.Push(2); Assert.IsTrue(queue.Check()); queue.Push(3); Assert.IsTrue(queue.Check()); Assert.AreEqual(3, queue.Pop()); Assert.IsTrue(queue.Check()); Assert.AreEqual(2, queue.Pop()); Assert.IsTrue(queue.Check()); Assert.AreEqual(1, queue.Pop()); Assert.IsTrue(queue.Check()); } [Test] public void BadChoose() { Assert.Throws<NoSuchItemException>(() => queue.Choose()); } [Test] public void BadDequeue() { Assert.Throws<NoSuchItemException>(() => queue.Dequeue()); } [Test] public void Simple2() { loadup2(); Assert.IsTrue(queue.Check()); Assert.AreEqual(5, queue.Count); Assert.IsTrue(IC.Eq(queue, 15, 1000, 1001, 1002, 1003)); Assert.AreEqual(15, queue.Choose()); } [Test] public void Counting() { Assert.IsTrue(queue.IsEmpty); Assert.AreEqual(0, queue.Count); Assert.AreEqual(Speed.Constant, queue.CountSpeed); queue.Enqueue(11); Assert.IsFalse(queue.IsEmpty); queue.Enqueue(12); Assert.AreEqual(2, queue.Count); } //This test by Steve Wallace uncovered a bug in the indexing. [Test] public void SW200602() { C5.CircularQueue<int> list = new C5.CircularQueue<int>(8); for (int count = 0; count <= 7; count++) { list.Enqueue(count); } int end = list.Count; for (int index = 0; index < end; index++) { Assert.AreEqual(index, list[0]); list.Dequeue(); } } [TearDown] public void Dispose() { queue = null; } } }
using System; using System.Collections; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using System.Reflection; namespace FleetOpsCalendar.Areas.HelpPage { /// <summary> /// This class will create an object of a given type and populate it with sample data. /// </summary> public class ObjectGenerator { private const int DefaultCollectionSize = 3; 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. See License.txt in the project root for license information. using System; using System.Threading; using System.Diagnostics; using System.Globalization; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using Microsoft.Build.Framework; using Microsoft.Build.Utilities; using Microsoft.VisualStudio.Shell.Interop; using Microsoft.VisualStudio.Shell; using Microsoft.VisualStudio.TextManager.Interop; using Microsoft.Win32; using IOleServiceProvider = Microsoft.VisualStudio.OLE.Interop.IServiceProvider; namespace Microsoft.VisualStudio.FSharp.ProjectSystem { public static class LoggingConstants { public const string DefaultVSRegistryRoot = @"Software\Microsoft\VisualStudio\15.0"; public const string BuildVerbosityRegistrySubKey = @"General"; public const string BuildVerbosityRegistryValue = "MSBuildLoggerVerbosity"; public const string UpToDateVerbosityRegistryValue = "U2DCheckVerbosity"; } /// <summary> /// This class implements an MSBuild logger that output events to VS outputwindow and tasklist. /// </summary> [ComVisible(true)] public sealed class IDEBuildLogger : Logger { // TODO: Remove these constants when we have a version that supports getting the verbosity using automation. private string buildVerbosityRegistryRoot = LoggingConstants.DefaultVSRegistryRoot; // TODO: Re-enable this constants when we have a version that suppoerts getting the verbosity using automation. private int currentIndent; private IVsOutputWindowPane outputWindowPane; private string errorString = SR.GetString(SR.Error, CultureInfo.CurrentUICulture); private string warningString = SR.GetString(SR.Warning, CultureInfo.CurrentUICulture); private bool isLogTaskDone; private IVsHierarchy hierarchy; private IServiceProvider serviceProvider; private IVsLanguageServiceBuildErrorReporter2 errorReporter; private bool haveCachedRegistry = false; public string WarningString { get { return this.warningString; } set { this.warningString = value; } } public string ErrorString { get { return this.errorString; } set { this.errorString = value; } } public bool IsLogTaskDone { get { return this.isLogTaskDone; } set { this.isLogTaskDone = value; } } /// <summary> /// When building from within VS, setting this will /// enable the logger to retrive the verbosity from /// the correct registry hive. /// </summary> public string BuildVerbosityRegistryRoot { get { return buildVerbosityRegistryRoot; } set { buildVerbosityRegistryRoot = value; } } /// <summary> /// Set to null to avoid writing to the output window /// </summary> public IVsOutputWindowPane OutputWindowPane { get { return outputWindowPane; } set { outputWindowPane = value; } } public IVsLanguageServiceBuildErrorReporter2 ErrorReporter { get { return errorReporter; } set { errorReporter = value; } } internal IDEBuildLogger(IVsOutputWindowPane output, IVsHierarchy hierarchy, IVsLanguageServiceBuildErrorReporter2 errorReporter) { if (hierarchy == null) throw new ArgumentNullException("hierarchy"); this.errorReporter = errorReporter; this.outputWindowPane = output; this.hierarchy = hierarchy; IOleServiceProvider site; Microsoft.VisualStudio.ErrorHandler.ThrowOnFailure(hierarchy.GetSite(out site)); this.serviceProvider = new Shell.ServiceProvider (site); } public override void Initialize(IEventSource eventSource) { if (null == eventSource) { throw new ArgumentNullException("eventSource"); } // Note that the MSBuild logger thread does not have an exception handler, so // we swallow all exceptions (lest some random bad thing bring down the process). eventSource.BuildStarted += new BuildStartedEventHandler(BuildStartedHandler); eventSource.BuildFinished += new BuildFinishedEventHandler(BuildFinishedHandler); eventSource.ProjectStarted += new ProjectStartedEventHandler(ProjectStartedHandler); eventSource.ProjectFinished += new ProjectFinishedEventHandler(ProjectFinishedHandler); eventSource.TargetStarted += new TargetStartedEventHandler(TargetStartedHandler); eventSource.TargetFinished += new TargetFinishedEventHandler(TargetFinishedHandler); eventSource.TaskStarted += new TaskStartedEventHandler(TaskStartedHandler); eventSource.TaskFinished += new TaskFinishedEventHandler(TaskFinishedHandler); eventSource.CustomEventRaised += new CustomBuildEventHandler(CustomHandler); eventSource.ErrorRaised += new BuildErrorEventHandler(ErrorHandler); eventSource.WarningRaised += new BuildWarningEventHandler(WarningHandler); eventSource.MessageRaised += new BuildMessageEventHandler(MessageHandler); } /// <summary> /// This is the delegate for error events. /// </summary> private void ErrorHandler(object sender, BuildErrorEventArgs errorEvent) { try { AddToErrorList( errorEvent, errorEvent.Subcategory, errorEvent.Code, errorEvent.File, errorEvent.LineNumber, errorEvent.ColumnNumber, errorEvent.EndLineNumber, errorEvent.EndColumnNumber); } catch (Exception e) { Debug.Assert(false, "Problem adding error to error list: " + e.Message + " at " + e.TargetSite); } } /// <summary> /// This is the delegate for warning events. /// </summary> private void WarningHandler(object sender, BuildWarningEventArgs errorEvent) { try { AddToErrorList( errorEvent, errorEvent.Subcategory, errorEvent.Code, errorEvent.File, errorEvent.LineNumber, errorEvent.ColumnNumber, errorEvent.EndLineNumber, errorEvent.EndColumnNumber); } catch (Exception e) { Debug.Assert(false, "Problem adding warning to warning list: " + e.Message + " at " + e.TargetSite); } } /// <summary> /// Private internal class for capturing full compiler error line/column span information /// </summary> private class DefaultCompilerError : CompilerError { private int endLine; private int endColumn; public int EndLine { get { return endLine; } set { endLine = value; } } public int EndColumn { get { return endColumn; } set { endColumn = value; } } public DefaultCompilerError(string fileName, int startLine, int startColumn, int endLine, int endColumn, string errorNumber, string errorText) : base(fileName, startLine, startColumn, errorNumber, errorText) { EndLine = endLine; EndColumn = endColumn; } } private void Output(string s) { // Various events can call SetOutputLogger(null), which will null out "this.OutputWindowPane". // So we capture a reference to it. At some point in the future, after this build finishes, // the pane reference we have will no longer accept input from us. // But here there is no race, because // - we only log user-invoked builds to the Output window // - user-invoked buils always run MSBuild ASYNC // - in an ASYNC build, the BuildCoda uses UIThread.Run() to schedule itself to be run on the UI thread // - UIThread.Run() protects against re-entrancy and thus always preserves the queuing order of its actions // - the pane is good until at least the point when BuildCoda runs and we declare to MSBuild that we are finished with this build var pane = this.OutputWindowPane; // copy to capture in delegate UIThread.Run(delegate() { try { pane.OutputStringThreadSafe(s); } catch (Exception e) { Debug.Assert(false, "We would like to know if this happens; exception in IDEBuildLogger.Output(): " + e.ToString()); // Don't crash process due to random exception, just swallow it } }); } /// <summary> /// Add the error/warning to the error list and potentially to the output window. /// </summary> private void AddToErrorList( BuildEventArgs errorEvent, string subcategory, string errorCode, string file, int startLine, int startColumn, int endLine, int endColumn) { if (file == null) file = String.Empty; bool isWarning = errorEvent is BuildWarningEventArgs; Shell.TaskPriority priority = isWarning ? Shell.TaskPriority.Normal : Shell.TaskPriority.High; TextSpan span; span.iStartLine = startLine; span.iStartIndex = startColumn; span.iEndLine = endLine < startLine ? span.iStartLine : endLine; span.iEndIndex = (endColumn < startColumn) && (span.iStartLine == span.iEndLine) ? span.iStartIndex : endColumn; if (OutputWindowPane != null && (this.Verbosity != LoggerVerbosity.Quiet || errorEvent is BuildErrorEventArgs)) { // Format error and output it to the output window string message = this.FormatMessage(errorEvent.Message); DefaultCompilerError e = new DefaultCompilerError(file, span.iStartLine, span.iStartIndex, span.iEndLine, span.iEndIndex, errorCode, message); e.IsWarning = isWarning; Output(GetFormattedErrorMessage(e)); } UIThread.Run(delegate() { IVsUIShellOpenDocument openDoc = serviceProvider.GetService(typeof(IVsUIShellOpenDocument)) as IVsUIShellOpenDocument; if (openDoc == null) return; IVsWindowFrame frame; IOleServiceProvider sp; IVsUIHierarchy hier; uint itemid; Guid logicalView = VSConstants.LOGVIEWID_Code; IVsTextLines buffer = null; // JAF // Notes about acquiring the buffer: // If the file physically exists then this will open the document in the current project. It doesn't matter if the file is a member of the project. // Also, it doesn't matter if this is an F# file. For example, an error in Microsoft.Common.targets will cause a file to be opened here. // However, opening the document does not mean it will be shown in VS. if (!Microsoft.VisualStudio.ErrorHandler.Failed(openDoc.OpenDocumentViaProject(file, ref logicalView, out sp, out hier, out itemid, out frame)) && frame != null) { object docData; frame.GetProperty((int)__VSFPROPID.VSFPROPID_DocData, out docData); // Get the text lines buffer = docData as IVsTextLines; if (buffer == null) { IVsTextBufferProvider bufferProvider = docData as IVsTextBufferProvider; if (bufferProvider != null) { bufferProvider.GetTextBuffer(out buffer); } } } // Need to adjust line and column indexing for the task window, which assumes zero-based values if (span.iStartLine > 0 && span.iStartIndex > 0) { span.iStartLine -= 1; span.iEndLine -= 1; span.iStartIndex -= 1; span.iEndIndex -= 1; } // Add error to task list var taskText = global::FSharp.Compiler.ErrorLogger.NewlineifyErrorString(errorEvent.Message); if (errorReporter != null) { errorReporter.ReportError2(taskText, errorCode, (VSTASKPRIORITY) priority, span.iStartLine, span.iStartIndex, span.iEndLine, span.iEndIndex, file); } }); } /// <summary> /// This is the delegate for Message event types /// </summary> private void MessageHandler(object sender, BuildMessageEventArgs messageEvent) { try { if (LogAtImportance(messageEvent.Importance)) { LogEvent(sender, messageEvent); } } catch (Exception e) { Debug.Assert(false, "Problem logging message event: " + e.Message + " at " + e.TargetSite); // swallow the exception } } /// <summary> /// This is the delegate for BuildStartedHandler events. /// </summary> private void BuildStartedHandler(object sender, BuildStartedEventArgs buildEvent) { try { this.haveCachedRegistry = false; if (LogAtImportance(MessageImportance.Normal)) { LogEvent(sender, buildEvent); } } catch (Exception e) { Debug.Assert(false, "Problem logging buildstarted event: " + e.Message + " at " + e.TargetSite); // swallow the exception } finally { if (errorReporter != null) { errorReporter.ClearErrors(); } } } /// <summary> /// This is the delegate for BuildFinishedHandler events. /// </summary> /// <param name="sender"></param> /// <param name="buildEvent"></param> private void BuildFinishedHandler(object sender, BuildFinishedEventArgs buildEvent) { try { if (LogAtImportance(buildEvent.Succeeded ? MessageImportance.Normal : MessageImportance.High)) { if (this.outputWindowPane != null) Output(Environment.NewLine); LogEvent(sender, buildEvent); } } catch (Exception e) { Debug.Assert(false, "Problem logging buildfinished event: " + e.Message + " at " + e.TargetSite); // swallow the exception } } /// <summary> /// This is the delegate for ProjectStartedHandler events. /// </summary> private void ProjectStartedHandler(object sender, ProjectStartedEventArgs buildEvent) { try { if (LogAtImportance(MessageImportance.Normal)) { LogEvent(sender, buildEvent); } } catch (Exception e) { Debug.Assert(false, "Problem logging projectstarted event: " + e.Message + " at " + e.TargetSite); // swallow the exception } } /// <summary> /// This is the delegate for ProjectFinishedHandler events. /// </summary> private void ProjectFinishedHandler(object sender, ProjectFinishedEventArgs buildEvent) { try { if (LogAtImportance(buildEvent.Succeeded ? MessageImportance.Normal : MessageImportance.High)) { LogEvent(sender, buildEvent); } } catch (Exception e) { Debug.Assert(false, "Problem logging projectfinished event: " + e.Message + " at " + e.TargetSite); // swallow the exception } } /// <summary> /// This is the delegate for TargetStartedHandler events. /// </summary> private void TargetStartedHandler(object sender, TargetStartedEventArgs buildEvent) { try { if (LogAtImportance(MessageImportance.Normal)) { LogEvent(sender, buildEvent); } } catch (Exception e) { Debug.Assert(false, "Problem logging targetstarted event: " + e.Message + " at " + e.TargetSite); // swallow the exception } finally { ++this.currentIndent; } } /// <summary> /// This is the delegate for TargetFinishedHandler events. /// </summary> private void TargetFinishedHandler(object sender, TargetFinishedEventArgs buildEvent) { try { --this.currentIndent; if ((isLogTaskDone) && LogAtImportance(buildEvent.Succeeded ? MessageImportance.Normal : MessageImportance.High)) { LogEvent(sender, buildEvent); } } catch (Exception e) { Debug.Assert(false, "Problem logging targetfinished event: " + e.Message + " at " + e.TargetSite); // swallow the exception } } /// <summary> /// This is the delegate for TaskStartedHandler events. /// </summary> private void TaskStartedHandler(object sender, TaskStartedEventArgs buildEvent) { try { if (LogAtImportance(MessageImportance.Normal)) { LogEvent(sender, buildEvent); } } catch (Exception e) { Debug.Assert(false, "Problem logging taskstarted event: " + e.Message + " at " + e.TargetSite); // swallow the exception } finally { ++this.currentIndent; } } /// <summary> /// This is the delegate for TaskFinishedHandler events. /// </summary> private void TaskFinishedHandler(object sender, TaskFinishedEventArgs buildEvent) { try { --this.currentIndent; if ((isLogTaskDone) && LogAtImportance(buildEvent.Succeeded ? MessageImportance.Normal : MessageImportance.High)) { LogEvent(sender, buildEvent); } } catch (Exception e) { Debug.Assert(false, "Problem logging taskfinished event: " + e.Message + " at " + e.TargetSite); // swallow the exception } } /// <summary> /// This is the delegate for CustomHandler events. /// </summary> /// <param name="sender"></param> /// <param name="buildEvent"></param> private void CustomHandler(object sender, CustomBuildEventArgs buildEvent) { try { LogEvent(sender, buildEvent); } catch (Exception e) { Debug.Assert(false, "Problem logging custom event: " + e.Message + " at " + e.TargetSite); // swallow the exception } } /// <summary> /// This method takes a MessageImportance and returns true if messages /// at importance i should be loggeed. Otherwise return false. /// </summary> private bool LogAtImportance(MessageImportance importance) { // If importance is too low for current settings, ignore the event bool logIt = false; this.SetVerbosity(); switch (this.Verbosity) { case LoggerVerbosity.Quiet: logIt = false; break; case LoggerVerbosity.Minimal: logIt = (importance == MessageImportance.High); break; case LoggerVerbosity.Normal: logIt = (importance == MessageImportance.Normal) || (importance == MessageImportance.High); break; case LoggerVerbosity.Detailed: logIt = (importance == MessageImportance.Low) || (importance == MessageImportance.Normal) || (importance == MessageImportance.High); break; case LoggerVerbosity.Diagnostic: logIt = true; break; default: Debug.Fail("Unknown Verbosity level. Ignoring will cause everything to be logged"); break; } return logIt; } /// <summary> /// This is the method that does the main work of logging an event /// when one is sent to this logger. /// </summary> private void LogEvent(object sender, BuildEventArgs buildEvent) { try { // Fill in the Message text if (OutputWindowPane != null && !String.IsNullOrEmpty(buildEvent.Message)) { int startingSize = this.currentIndent + buildEvent.Message.Length + 1; StringBuilder msg = new StringBuilder(startingSize); if (this.currentIndent > 0) { msg.Append('\t', this.currentIndent); } msg.AppendLine(buildEvent.Message); Output(msg.ToString()); } } catch (Exception e) { try { System.Diagnostics.Debug.Assert(false, "Error thrown from IDEBuildLogger::LogEvent"); System.Diagnostics.Debug.Assert(false, e.ToString()); // For retail, also try to show in the output window. Output(e.ToString()); } catch { // We're going to throw the original exception anyway } throw; } } /// <summary> /// This is called when the build complete. /// </summary> private void ShutdownLogger() { } /// <summary> /// Format error messages for the task list /// </summary> /// <param name="e"></param> /// <returns></returns> private string GetFormattedErrorMessage(DefaultCompilerError e) { if (e == null) return String.Empty; string errCode = (e.IsWarning) ? this.warningString : this.errorString; StringBuilder fileRef = new StringBuilder(); // JAF: // Even if fsc.exe returns a canonical message with no file at all, MSBuild will set the file to the name // of the task (FSC). In principle, e.FileName will not be null or empty but handle this case anyway. bool thereIsAFile = !string.IsNullOrEmpty(e.FileName); bool thereIsASpan = e.Line!=0 || e.Column!=0 || e.EndLine!=0 || e.EndColumn!=0; if (thereIsAFile) { fileRef.AppendFormat(CultureInfo.CurrentUICulture, "{0}", e.FileName); if (thereIsASpan) { fileRef.AppendFormat(CultureInfo.CurrentUICulture, "({0},{1})", e.Line, e.Column); } fileRef.AppendFormat(CultureInfo.CurrentUICulture, ":"); } fileRef.AppendFormat(CultureInfo.CurrentUICulture, " {0} {1}: {2}", errCode, e.ErrorNumber, e.ErrorText); return fileRef.ToString(); } /// <summary> /// Formats the message that is to be output. /// </summary> /// <param name="message">The message string.</param> /// <returns>The new message</returns> private string FormatMessage(string message) { if (string.IsNullOrEmpty(message)) { return Environment.NewLine; } StringBuilder sb = new StringBuilder(message.Length + Environment.NewLine.Length); sb.AppendLine(message); return sb.ToString(); } /// <summary> /// Sets the verbosity level. /// </summary> private void SetVerbosity() { // TODO: This should be replaced when we have a version that supports automation. if (!this.haveCachedRegistry) { string verbosityKey = String.Format(CultureInfo.InvariantCulture, @"{0}\{1}", BuildVerbosityRegistryRoot, LoggingConstants.BuildVerbosityRegistrySubKey); using (RegistryKey subKey = Registry.CurrentUser.OpenSubKey(verbosityKey)) { if (subKey != null) { object valueAsObject = subKey.GetValue(LoggingConstants.BuildVerbosityRegistryValue); if (valueAsObject != null) { this.Verbosity = (LoggerVerbosity)((int)valueAsObject); } } } this.haveCachedRegistry = true; } // TODO: Continue this code to get the Verbosity when we have a version that supports automation to get the Verbosity. //EnvDTE.DTE dte = this.serviceProvider.GetService(typeof(EnvDTE.DTE)) as EnvDTE.DTE; //EnvDTE.Properties properties = dte.get_Properties(EnvironmentCategory, ProjectsAndSolutionSubCategory); } } /// <summary> /// Helper for logging to the output window /// </summary> public sealed class OutputWindowLogger { private readonly Func<bool> predicate; private readonly Action<string> print; /// <summary> /// Helper to create output window logger for project up-to-date check /// </summary> /// <param name="pane">Output window pane to use for logging</param> /// <returns>Logger</returns> public static OutputWindowLogger CreateUpToDateCheckLogger(IVsOutputWindowPane pane) { string upToDateVerbosityKey = String.Format(CultureInfo.InvariantCulture, @"{0}\{1}", LoggingConstants.DefaultVSRegistryRoot, LoggingConstants.BuildVerbosityRegistrySubKey); var shouldLog = false; using (RegistryKey subKey = Registry.CurrentUser.OpenSubKey(upToDateVerbosityKey)) { if (subKey != null) { object valueAsObject = subKey.GetValue(LoggingConstants.UpToDateVerbosityRegistryValue); if (valueAsObject != null && valueAsObject is int) { shouldLog = ((int)valueAsObject) == 1; } } } return new OutputWindowLogger(() => shouldLog, pane); } /// <summary> /// Creates a logger instance /// </summary> /// <param name="shouldLog">Predicate that will be called when logging. Should return true if logging is to be performed, false otherwise.</param> /// <param name="pane">The output pane where logging should be targeted</param> public OutputWindowLogger(Func<bool> shouldLog, IVsOutputWindowPane pane) { this.predicate = shouldLog; if (pane is IVsOutputWindowPaneNoPump) { var asNoPump = pane as IVsOutputWindowPaneNoPump; this.print = (s) => asNoPump.OutputStringNoPump(s); } else { this.print = (s) => pane.OutputStringThreadSafe(s); } } /// <summary> /// Logs a message to the output window, if the original predicate returns true /// </summary> /// <param name="message">Log message, can be a String.Format-style format string</param> /// <param name="args">Optional aruments for format string</param> public void WriteLine(string message, params object[] args) { if (this.predicate()) { var s = String.Format(message, args); s = String.Format("{0}{1}", s, Environment.NewLine); this.print(s); } } } }
namespace Macabresoft.Macabre2D.UI.Common; using System; using System.ComponentModel; using System.Windows.Input; using Avalonia.Input; using Macabresoft.Core; using Macabresoft.Macabre2D.Framework; using Microsoft.Xna.Framework; using ReactiveUI; /// <summary> /// Interface for interacting with the editor and its many gizmos. /// </summary> public interface IEditorService : INotifyPropertyChanged { /// <summary> /// Occurs when camera centering is requested. /// </summary> event EventHandler CenterCameraRequested; /// <summary> /// Occurs when focus is requested for an entity. /// </summary> event EventHandler<IEntity> FocusRequested; /// <summary> /// Gets a command to request the camera to be centered on the scene. /// </summary> ICommand RequestCenterCameraCommand { get; } /// <summary> /// Gets a command to request focus of the currently selected entity. /// </summary> ICommand RequestFocusCommand { get; } /// <summary> /// Gets or sets the color of selected colliders. /// </summary> Color ColliderColor { get; set; } /// <summary> /// Gets or sets the cursor type. /// </summary> StandardCursorType CursorType { get; set; } /// <summary> /// Gets or sets the drop shadow color. /// </summary> Color DropShadowColor { get; set; } /// <summary> /// Gets or sets the number of divisions between major grid lines. /// </summary> /// <value>The number of divisions.</value> byte GridDivisions { get; set; } /// <summary> /// Gets or sets the selected gizmo. /// </summary> GizmoKind SelectedGizmo { get; set; } /// <summary> /// Gets or sets the selected tab. /// </summary> EditorTabs SelectedTab { get; set; } /// <summary> /// Gets or sets the selection color. /// </summary> Color SelectionColor { get; set; } /// <summary> /// Gets or sets a value indicating whether to show the editor grid. /// </summary> bool ShowGrid { get; set; } /// <summary> /// Gets or sets the color of the x axis. /// </summary> Color XAxisColor { get; set; } /// <summary> /// Gets or sets the color of the y axis. /// </summary> Color YAxisColor { get; set; } } /// <summary> /// A service for interacting with the editor and its many gizmos. /// </summary> public class EditorService : ReactiveObject, IEditorService { private readonly IEntityService _entityService; private readonly IEditorSettingsService _settingsService; private Color _colliderColor = DefinedColors.MacabresoftBone; private Color _dropShadowColor = DefinedColors.MacabresoftBlack * 0.4f; private byte _gridDivisions = 5; private Color _selectionColor = DefinedColors.MacabresoftYellow; private bool _showGrid = true; private StandardCursorType _standardCursorType = StandardCursorType.None; private Color _xAxisColor = DefinedColors.ZvukostiGreen; private Color _yAxisColor = DefinedColors.MacabresoftRed; /// <inheritdoc /> public event EventHandler CenterCameraRequested; /// <inheritdoc /> public event EventHandler<IEntity> FocusRequested; /// <summary> /// Initializes a new instance of the <see cref="EditorService" /> class. /// </summary> /// <param name="entityService"></param> /// <param name="settingsService">The editor settings service.</param> public EditorService( IEntityService entityService, IEditorSettingsService settingsService) : base() { this._entityService = entityService; this._settingsService = settingsService; this.RequestCenterCameraCommand = ReactiveCommand.Create(this.RequestCenterCamera); this.RequestFocusCommand = ReactiveCommand.Create( this.RequestFocus, this._entityService.WhenAny(x => x.Selected, y => y.Value != null)); } /// <inheritdoc /> public ICommand RequestCenterCameraCommand { get; } /// <inheritdoc /> public ICommand RequestFocusCommand { get; } /// <inheritdoc /> public Color ColliderColor { get => this._colliderColor; set => this.RaiseAndSetIfChanged(ref this._colliderColor, value); } /// <inheritdoc /> public StandardCursorType CursorType { get => this._standardCursorType; set => this.RaiseAndSetIfChanged(ref this._standardCursorType, value); } /// <inheritdoc /> public Color DropShadowColor { get => this._dropShadowColor; set => this.RaiseAndSetIfChanged(ref this._dropShadowColor, value); } /// <inheritdoc /> public byte GridDivisions { get => this._gridDivisions; set => this.RaiseAndSetIfChanged(ref this._gridDivisions, value); } /// <inheritdoc /> public GizmoKind SelectedGizmo { get => this._settingsService.Settings.LastGizmoSelected; set { this._settingsService.Settings.LastGizmoSelected = value; this.RaisePropertyChanged(); } } /// <inheritdoc /> public EditorTabs SelectedTab { get => this._settingsService.Settings.LastTabSelected; set { this._settingsService.Settings.LastTabSelected = value; this.RaisePropertyChanged(); } } /// <inheritdoc /> public Color SelectionColor { get => this._selectionColor; set => this.RaiseAndSetIfChanged(ref this._selectionColor, value); } /// <inheritdoc /> public bool ShowGrid { get => this._showGrid; set => this.RaiseAndSetIfChanged(ref this._showGrid, value); } /// <inheritdoc /> public Color XAxisColor { get => this._xAxisColor; set => this.RaiseAndSetIfChanged(ref this._xAxisColor, value); } /// <inheritdoc /> public Color YAxisColor { get => this._yAxisColor; set => this.RaiseAndSetIfChanged(ref this._yAxisColor, value); } private void RequestCenterCamera() { this.CenterCameraRequested.SafeInvoke(this); } private void RequestFocus() { this.FocusRequested.SafeInvoke(this, this._entityService.Selected); } }
// Copyright (c) 2007, Clarius Consulting, Manas Technology Solutions, InSTEDD, and Contributors. // All rights reserved. Licensed under the BSD 3-Clause License; see License.txt. using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Diagnostics; using System.Linq.Expressions; using Moq.Expressions.Visitors; namespace Moq { internal sealed class ExpressionComparer : IEqualityComparer<Expression> { public static readonly ExpressionComparer Default = new ExpressionComparer(); private ExpressionComparer() { } public bool Equals(Expression x, Expression y) { if (object.ReferenceEquals(x, y)) { return true; } if (x == null || y == null) { return false; } if (x.NodeType == y.NodeType) { switch (x.NodeType) { case ExpressionType.Negate: case ExpressionType.NegateChecked: case ExpressionType.Not: case ExpressionType.Convert: case ExpressionType.ConvertChecked: case ExpressionType.ArrayLength: case ExpressionType.Quote: case ExpressionType.TypeAs: case ExpressionType.UnaryPlus: return this.EqualsUnary((UnaryExpression)x, (UnaryExpression)y); case ExpressionType.Add: case ExpressionType.AddChecked: case ExpressionType.Assign: case ExpressionType.Subtract: case ExpressionType.SubtractChecked: case ExpressionType.Multiply: case ExpressionType.MultiplyChecked: case ExpressionType.Divide: case ExpressionType.Modulo: case ExpressionType.And: case ExpressionType.AndAlso: case ExpressionType.Or: case ExpressionType.OrElse: case ExpressionType.LessThan: case ExpressionType.LessThanOrEqual: case ExpressionType.GreaterThan: case ExpressionType.GreaterThanOrEqual: case ExpressionType.Equal: case ExpressionType.NotEqual: case ExpressionType.Coalesce: case ExpressionType.ArrayIndex: case ExpressionType.RightShift: case ExpressionType.LeftShift: case ExpressionType.ExclusiveOr: case ExpressionType.Power: return this.EqualsBinary((BinaryExpression)x, (BinaryExpression)y); case ExpressionType.TypeIs: return this.EqualsTypeBinary((TypeBinaryExpression)x, (TypeBinaryExpression)y); case ExpressionType.Conditional: return this.EqualsConditional((ConditionalExpression)x, (ConditionalExpression)y); case ExpressionType.Constant: return EqualsConstant((ConstantExpression)x, (ConstantExpression)y); case ExpressionType.Parameter: return this.EqualsParameter((ParameterExpression)x, (ParameterExpression)y); case ExpressionType.MemberAccess: return this.EqualsMember((MemberExpression)x, (MemberExpression)y); case ExpressionType.Call: return this.EqualsMethodCall((MethodCallExpression)x, (MethodCallExpression)y); case ExpressionType.Lambda: return this.EqualsLambda((LambdaExpression)x, (LambdaExpression)y); case ExpressionType.New: return this.EqualsNew((NewExpression)x, (NewExpression)y); case ExpressionType.NewArrayInit: case ExpressionType.NewArrayBounds: return this.EqualsNewArray((NewArrayExpression)x, (NewArrayExpression)y); case ExpressionType.Index: return this.EqualsIndex((IndexExpression)x, (IndexExpression)y); case ExpressionType.Invoke: return this.EqualsInvocation((InvocationExpression)x, (InvocationExpression)y); case ExpressionType.MemberInit: return this.EqualsMemberInit((MemberInitExpression)x, (MemberInitExpression)y); case ExpressionType.ListInit: return this.EqualsListInit((ListInitExpression)x, (ListInitExpression)y); } } if (x.NodeType == ExpressionType.Extension || y.NodeType == ExpressionType.Extension) { return this.EqualsExtension(x, y); } return false; } public int GetHashCode(Expression obj) { return obj == null ? 0 : obj.GetHashCode(); } private static bool Equals<T>(ReadOnlyCollection<T> x, ReadOnlyCollection<T> y, Func<T, T, bool> comparer) { if (x.Count != y.Count) { return false; } for (var index = 0; index < x.Count; index++) { if (!comparer(x[index], y[index])) { return false; } } return true; } private bool EqualsBinary(BinaryExpression x, BinaryExpression y) { return x.Method == y.Method && this.Equals(x.Left, y.Left) && this.Equals(x.Right, y.Right) && this.Equals(x.Conversion, y.Conversion); } private bool EqualsConditional(ConditionalExpression x, ConditionalExpression y) { return this.Equals(x.Test, y.Test) && this.Equals(x.IfTrue, y.IfTrue) && this.Equals(x.IfFalse, y.IfFalse); } private static bool EqualsConstant(ConstantExpression x, ConstantExpression y) { return object.Equals(x.Value, y.Value); } private bool EqualsElementInit(ElementInit x, ElementInit y) { return x.AddMethod == y.AddMethod && Equals(x.Arguments, y.Arguments, this.Equals); } private bool EqualsIndex(IndexExpression x, IndexExpression y) { return this.Equals(x.Object, y.Object) && Equals(x.Indexer, y.Indexer) && Equals(x.Arguments, y.Arguments, this.Equals); } private bool EqualsInvocation(InvocationExpression x, InvocationExpression y) { return this.Equals(x.Expression, y.Expression) && Equals(x.Arguments, y.Arguments, this.Equals); } private bool EqualsLambda(LambdaExpression x, LambdaExpression y) { return x.GetType() == y.GetType() && this.Equals(x.Body, y.Body) && Equals(x.Parameters, y.Parameters, this.EqualsParameter); } private bool EqualsListInit(ListInitExpression x, ListInitExpression y) { return this.EqualsNew(x.NewExpression, y.NewExpression) && Equals(x.Initializers, y.Initializers, this.EqualsElementInit); } private bool EqualsMemberAssignment(MemberAssignment x, MemberAssignment y) { return this.Equals(x.Expression, y.Expression); } private bool EqualsMemberBinding(MemberBinding x, MemberBinding y) { if (x.BindingType == y.BindingType && x.Member == y.Member) { return x.BindingType switch { MemberBindingType.Assignment => this.EqualsMemberAssignment((MemberAssignment)x, (MemberAssignment)y), MemberBindingType.MemberBinding => this.EqualsMemberMemberBinding((MemberMemberBinding)x, (MemberMemberBinding)y), MemberBindingType.ListBinding => this.EqualsMemberListBinding((MemberListBinding)x, (MemberListBinding)y), _ => throw new ArgumentOutOfRangeException(nameof(x)), }; } return false; } private bool EqualsMember(MemberExpression x, MemberExpression y) { // If any of the two nodes represents an access to a captured variable, // we want to compare its value, not its identity. (`EvaluateCaptures` is // a no-op in all other cases, so it is safe to apply "just in case".) var rx = x.Apply(EvaluateCaptures.Rewriter); var ry = y.Apply(EvaluateCaptures.Rewriter); if (rx == x && ry == y) { return x.Member == y.Member && this.Equals(x.Expression, y.Expression); } else { // Rewriting occurred, we might no longer have two `MemberExpression`s: return this.Equals(rx, ry); } } private bool EqualsMemberInit(MemberInitExpression x, MemberInitExpression y) { return this.EqualsNew(x.NewExpression, y.NewExpression) && Equals(x.Bindings, y.Bindings, this.EqualsMemberBinding); } private bool EqualsMemberListBinding(MemberListBinding x, MemberListBinding y) { return Equals(x.Initializers, y.Initializers, this.EqualsElementInit); } private bool EqualsMemberMemberBinding(MemberMemberBinding x, MemberMemberBinding y) { return Equals(x.Bindings, y.Bindings, this.EqualsMemberBinding); } private bool EqualsMethodCall(MethodCallExpression x, MethodCallExpression y) { return x.Method == y.Method && this.Equals(x.Object, y.Object) && Equals(x.Arguments, y.Arguments, this.Equals); } private bool EqualsNewArray(NewArrayExpression x, NewArrayExpression y) { return x.Type == y.Type && Equals(x.Expressions, y.Expressions, this.Equals); } private bool EqualsNew(NewExpression x, NewExpression y) { return x.Constructor == y.Constructor && Equals(x.Arguments, y.Arguments, this.Equals); } private bool EqualsParameter(ParameterExpression x, ParameterExpression y) { return x.Type == y.Type; } private bool EqualsTypeBinary(TypeBinaryExpression x, TypeBinaryExpression y) { return x.TypeOperand == y.TypeOperand && this.Equals(x.Expression, y.Expression); } private bool EqualsUnary(UnaryExpression x, UnaryExpression y) { return x.Method == y.Method && this.Equals(x.Operand, y.Operand); } private bool EqualsExtension(Expression x, Expression y) { // For now, we only care about our own `MatchExpression` extension; // if we wanted to be more thorough, we'd try to reduce `x` and `y`, // then compare the reduced nodes. return x.IsMatch(out var xm) && y.IsMatch(out var ym) && object.Equals(xm, ym); } } }
/* * Licensed to the Apache Software Foundation (ASF) Under one or more * contributor license agreements. See the NOTICE file distributed with * this work for Additional information regarding copyright ownership. * The ASF licenses this file to You Under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed Under the License is distributed on an "AS Is" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations Under the License. */ namespace NPOI.SS.Formula.Functions { using System; using NPOI.SS.Formula.Eval; using System.Text; /** * Implementation for Excel function OFFSet()<p/> * * OFFSet returns an area reference that Is a specified number of rows and columns from a * reference cell or area.<p/> * * <b>Syntax</b>:<br/> * <b>OFFSet</b>(<b>reference</b>, <b>rows</b>, <b>cols</b>, height, width)<p/> * <b>reference</b> Is the base reference.<br/> * <b>rows</b> Is the number of rows up or down from the base reference.<br/> * <b>cols</b> Is the number of columns left or right from the base reference.<br/> * <b>height</b> (default same height as base reference) Is the row Count for the returned area reference.<br/> * <b>width</b> (default same width as base reference) Is the column Count for the returned area reference.<br/> * * @author Josh Micich */ public class Offset : Function { // These values are specific to BIFF8 private const int LAST_VALID_ROW_INDEX = 0xFFFF; private const int LAST_VALID_COLUMN_INDEX = 0xFF; /** * Exceptions are used within this class to help simplify flow control when error conditions * are enCountered */ [Serializable] private class EvalEx : Exception { private ErrorEval _error; public EvalEx(ErrorEval error) { _error = error; } public ErrorEval GetError() { return _error; } } /** * A one dimensional base + offset. Represents either a row range or a column range. * Two instances of this class toGether specify an area range. */ /* package */ public class LinearOffsetRange { private int _offset; private int _Length; public LinearOffsetRange(int offset, int length) { if (length == 0) { // handled that condition much earlier throw new ArgumentException("Length may not be zero"); } _offset = offset; _Length = length; } public short FirstIndex { get { return (short)_offset; } } public short LastIndex { get { return (short)(_offset + _Length - 1); } } /** * Moves the range by the specified translation amount.<p/> * * This method also 'normalises' the range: Excel specifies that the width and height * parameters (Length field here) cannot be negative. However, OFFSet() does produce * sensible results in these cases. That behavior Is replicated here. <p/> * * @param translationAmount may be zero negative or positive * * @return the equivalent <c>LinearOffsetRange</c> with a positive Length, moved by the * specified translationAmount. */ public LinearOffsetRange NormaliseAndTranslate(int translationAmount) { if (_Length > 0) { if (translationAmount == 0) { return this; } return new LinearOffsetRange(translationAmount + _offset, _Length); } return new LinearOffsetRange(translationAmount + _offset + _Length + 1, -_Length); } public bool IsOutOfBounds(int lowValidIx, int highValidIx) { if (_offset < lowValidIx) { return true; } if (LastIndex > highValidIx) { return true; } return false; } public override String ToString() { StringBuilder sb = new StringBuilder(64); sb.Append(GetType().Name).Append(" ["); sb.Append(_offset).Append("...").Append(LastIndex); sb.Append("]"); return sb.ToString(); } } /** * Encapsulates either an area or cell reference which may be 2d or 3d. */ private class BaseRef { private const int INVALID_SHEET_INDEX = -1; private int _firstRowIndex; private int _firstColumnIndex; private int _width; private int _height; private RefEval _refEval; private AreaEval _areaEval; public BaseRef(RefEval re) { _refEval = re; _areaEval = null; _firstRowIndex = re.Row; _firstColumnIndex = re.Column; _height = 1; _width = 1; } public BaseRef(AreaEval ae) { _refEval = null; _areaEval = ae; _firstRowIndex = ae.FirstRow; _firstColumnIndex = ae.FirstColumn; _height = ae.LastRow - ae.FirstRow + 1; _width = ae.LastColumn - ae.FirstColumn + 1; } public int Width { get { return _width; } } public int Height { get { return _height; } } public int FirstRowIndex { get { return _firstRowIndex; } } public int FirstColumnIndex { get { return _firstColumnIndex; } } public AreaEval Offset(int relFirstRowIx, int relLastRowIx,int relFirstColIx, int relLastColIx) { if (_refEval == null) { return _areaEval.Offset(relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); } return _refEval.Offset(relFirstRowIx, relLastRowIx, relFirstColIx, relLastColIx); } } public ValueEval Evaluate(ValueEval[] args, int srcCellRow, int srcCellCol) { if (args.Length < 3 || args.Length > 5) { return ErrorEval.VALUE_INVALID; } try { BaseRef baseRef = EvaluateBaseRef(args[0]); int rowOffset = EvaluateIntArg(args[1], srcCellRow, srcCellCol); int columnOffset = EvaluateIntArg(args[2], srcCellRow, srcCellCol); int height = baseRef.Height; int width = baseRef.Width; // optional arguments // If height or width is omitted, it is assumed to be the same height or width as reference. switch (args.Length) { case 5: if (!(args[4] is MissingArgEval)) { width = EvaluateIntArg(args[4], srcCellRow, srcCellCol); } // fall-through to pick up height if (!(args[3] is MissingArgEval)) { height = EvaluateIntArg(args[3], srcCellRow, srcCellCol); } break; case 4: if (!(args[3] is MissingArgEval)) { height = EvaluateIntArg(args[3], srcCellRow, srcCellCol); } break; default: break; } // Zero height or width raises #REF! error if (height == 0 || width == 0) { return ErrorEval.REF_INVALID; } LinearOffsetRange rowOffsetRange = new LinearOffsetRange(rowOffset, height); LinearOffsetRange colOffsetRange = new LinearOffsetRange(columnOffset, width); return CreateOffset(baseRef, rowOffsetRange, colOffsetRange); } catch (EvaluationException e) { return e.GetErrorEval(); } } private static AreaEval CreateOffset(BaseRef baseRef, LinearOffsetRange orRow, LinearOffsetRange orCol) { LinearOffsetRange absRows = orRow.NormaliseAndTranslate(baseRef.FirstRowIndex); LinearOffsetRange absCols = orCol.NormaliseAndTranslate(baseRef.FirstColumnIndex); if (absRows.IsOutOfBounds(0, LAST_VALID_ROW_INDEX)) { throw new EvaluationException(ErrorEval.REF_INVALID); } if (absCols.IsOutOfBounds(0, LAST_VALID_COLUMN_INDEX)) { throw new EvaluationException(ErrorEval.REF_INVALID); } return baseRef.Offset(orRow.FirstIndex, orRow.LastIndex, orCol.FirstIndex, orCol.LastIndex); } private static BaseRef EvaluateBaseRef(ValueEval eval) { if (eval is RefEval) { return new BaseRef((RefEval)eval); } if (eval is AreaEval) { return new BaseRef((AreaEval)eval); } if (eval is ErrorEval) { throw new EvalEx((ErrorEval)eval); } throw new EvalEx(ErrorEval.VALUE_INVALID); } /** * OFFSet's numeric arguments (2..5) have similar Processing rules */ public static int EvaluateIntArg(ValueEval eval, int srcCellRow, int srcCellCol) { double d = EvaluateDoubleArg(eval, srcCellRow, srcCellCol); return ConvertDoubleToInt(d); } /** * Fractional values are silently truncated by Excel. * Truncation Is toward negative infinity. */ /* package */ public static int ConvertDoubleToInt(double d) { // Note - the standard java type conversion from double to int truncates toward zero. // but Math.floor() truncates toward negative infinity return (int)Math.Floor(d); } private static double EvaluateDoubleArg(ValueEval eval, int srcCellRow, int srcCellCol) { ValueEval ve = OperandResolver.GetSingleValue(eval, srcCellRow, srcCellCol); if (ve is NumericValueEval) { return ((NumericValueEval)ve).NumberValue; } if (ve is StringEval) { StringEval se = (StringEval)ve; double d = OperandResolver.ParseDouble(se.StringValue); if (double.IsNaN(d)) { throw new EvalEx(ErrorEval.VALUE_INVALID); } return d; } if (ve is BoolEval) { // in the context of OFFSet, bools resolve to 0 and 1. if (((BoolEval)ve).BooleanValue) { return 1; } return 0; } throw new Exception("Unexpected eval type (" + ve.GetType().Name + ")"); } } }
#region --- License --- /* Copyright (c) 2006 - 2008 The Open Toolkit library. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. Note: This code has been heavily modified for the Duality framework. */ #endregion using System; using System.Runtime.InteropServices; namespace Duality { /// <summary> /// Represents a 4D vector using four single-precision floating-point numbers. /// </summary> [StructLayout(LayoutKind.Sequential)] public struct Vector4 : IEquatable<Vector4> { /// <summary> /// Defines a unit-length Vector4 that points towards the X-axis. /// </summary> public static Vector4 UnitX = new Vector4(1, 0, 0, 0); /// <summary> /// Defines a unit-length Vector4 that points towards the Y-axis. /// </summary> public static Vector4 UnitY = new Vector4(0, 1, 0, 0); /// <summary> /// Defines a unit-length Vector4 that points towards the Z-axis. /// </summary> public static Vector4 UnitZ = new Vector4(0, 0, 1, 0); /// <summary> /// Defines a unit-length Vector4 that points towards the W-axis. /// </summary> public static Vector4 UnitW = new Vector4(0, 0, 0, 1); /// <summary> /// Defines a zero-length Vector4. /// </summary> public static Vector4 Zero = new Vector4(0, 0, 0, 0); /// <summary> /// Defines an instance with all components set to 1. /// </summary> public static readonly Vector4 One = new Vector4(1, 1, 1, 1); /// <summary> /// The X component of the Vector4. /// </summary> public float X; /// <summary> /// The Y component of the Vector4. /// </summary> public float Y; /// <summary> /// The Z component of the Vector4. /// </summary> public float Z; /// <summary> /// The W component of the Vector4. /// </summary> public float W; /// <summary> /// Gets or sets an OpenTK.Vector2 with the X and Y components of this instance. /// </summary> public Vector2 Xy { get { return new Vector2(this.X, this.Y); } set { this.X = value.X; this.Y = value.Y; } } /// <summary> /// Gets or sets an OpenTK.Vector3 with the X, Y and Z components of this instance. /// </summary> public Vector3 Xyz { get { return new Vector3(this.X, this.Y, this.Z); } set { this.X = value.X; this.Y = value.Y; this.Z = value.Z; } } /// <summary> /// Gets the length (magnitude) of the vector. /// </summary> /// <seealso cref="LengthSquared"/> public float Length { get { return (float)System.Math.Sqrt( this.X * this.X + this.Y * this.Y + this.Z * this.Z + this.W * this.W); } } /// <summary> /// Gets the square of the vector length (magnitude). /// </summary> /// <remarks> /// This property avoids the costly square root operation required by the Length property. This makes it more suitable /// for comparisons. /// </remarks> /// <see cref="Length"/> public float LengthSquared { get { return this.X * this.X + this.Y * this.Y + this.Z * this.Z + this.W * this.W; } } /// <summary> /// Returns a normalized version of this vector. /// </summary> public Vector4 Normalized { get { float length = this.Length; if (length < 1e-15f) return Vector4.Zero; float scale = 1.0f / length; return new Vector4( this.X * scale, this.Y * scale, this.Z * scale, this.W * scale); } } /// <summary> /// Gets or sets the value at the index of the Vector. /// </summary> public float this[int index] { get { switch (index) { case 0: return this.X; case 1: return this.Y; case 2: return this.Z; case 3: return this.W; default: throw new IndexOutOfRangeException("Vector4 access at index: " + index); } } set { switch (index) { case 0: this.X = value; return; case 1: this.Y = value; return; case 2: this.Z = value; return; case 3: this.W = value; return; default: throw new IndexOutOfRangeException("Vector4 access at index: " + index); } } } /// <summary> /// Scales the Vector4 to unit length. /// </summary> public void Normalize() { float length = this.Length; if (length < 1e-15f) { this = Vector4.Zero; } else { float scale = 1.0f / length; this.X *= scale; this.Y *= scale; this.Z *= scale; this.W *= scale; } } /// <summary> /// Constructs a new instance. /// </summary> /// <param name="value">The value that will initialize this instance.</param> public Vector4(float value) { this.X = value; this.Y = value; this.Z = value; this.W = value; } /// <summary> /// Constructs a new Vector4. /// </summary> /// <param name="x">The x component of the Vector4.</param> /// <param name="y">The y component of the Vector4.</param> /// <param name="z">The z component of the Vector4.</param> /// <param name="w">The w component of the Vector4.</param> public Vector4(float x, float y, float z, float w) { this.X = x; this.Y = y; this.Z = z; this.W = w; } /// <summary> /// Constructs a new Vector4 from the given Vector2. /// </summary> /// <param name="v">The Vector2 to copy components from.</param> public Vector4(Vector2 v) { this.X = v.X; this.Y = v.Y; this.Z = 0.0f; this.W = 0.0f; } /// <summary> /// Constructs a new Vector4 from the given Vector2. /// </summary> /// <param name="v">The Vector2 to copy components from.</param> /// <param name="z"></param> public Vector4(Vector2 v, float z) { this.X = v.X; this.Y = v.Y; this.Z = z; this.W = 0.0f; } /// <summary> /// Constructs a new Vector4 from the given Vector2. /// </summary> /// <param name="v">The Vector2 to copy components from.</param> /// <param name="z"></param> /// <param name="w"></param> public Vector4(Vector2 v, float z, float w) { this.X = v.X; this.Y = v.Y; this.Z = z; this.W = w; } /// <summary> /// Constructs a new Vector4 from the given Vector3. /// The w component is initialized to 0. /// </summary> /// <param name="v">The Vector3 to copy components from.</param> /// <remarks><seealso cref="Vector4(Vector3, float)"/></remarks> public Vector4(Vector3 v) { this.X = v.X; this.Y = v.Y; this.Z = v.Z; this.W = 0.0f; } /// <summary> /// Constructs a new Vector4 from the specified Vector3 and w component. /// </summary> /// <param name="v">The Vector3 to copy components from.</param> /// <param name="w">The w component of the new Vector4.</param> public Vector4(Vector3 v, float w) { this.X = v.X; this.Y = v.Y; this.Z = v.Z; this.W = w; } /// <summary> /// Adds two vectors. /// </summary> /// <param name="a">Left operand.</param> /// <param name="b">Right operand.</param> /// <param name="result">Result of operation.</param> public static void Add(ref Vector4 a, ref Vector4 b, out Vector4 result) { result = new Vector4(a.X + b.X, a.Y + b.Y, a.Z + b.Z, a.W + b.W); } /// <summary> /// Subtract one Vector from another /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">Result of subtraction</param> public static void Subtract(ref Vector4 a, ref Vector4 b, out Vector4 result) { result = new Vector4(a.X - b.X, a.Y - b.Y, a.Z - b.Z, a.W - b.W); } /// <summary> /// Multiplies a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector4 vector, float scale, out Vector4 result) { result = new Vector4(vector.X * scale, vector.Y * scale, vector.Z * scale, vector.W * scale); } /// <summary> /// Multiplies a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Multiply(ref Vector4 vector, ref Vector4 scale, out Vector4 result) { result = new Vector4(vector.X * scale.X, vector.Y * scale.Y, vector.Z * scale.Z, vector.W * scale.W); } /// <summary> /// Divides a vector by a scalar. /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector4 vector, float scale, out Vector4 result) { Multiply(ref vector, 1 / scale, out result); } /// <summary> /// Divide a vector by the components of a vector (scale). /// </summary> /// <param name="vector">Left operand.</param> /// <param name="scale">Right operand.</param> /// <param name="result">Result of the operation.</param> public static void Divide(ref Vector4 vector, ref Vector4 scale, out Vector4 result) { result = new Vector4(vector.X / scale.X, vector.Y / scale.Y, vector.Z / scale.Z, vector.W / scale.W); } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise minimum</returns> public static Vector4 Min(Vector4 a, Vector4 b) { a.X = a.X < b.X ? a.X : b.X; a.Y = a.Y < b.Y ? a.Y : b.Y; a.Z = a.Z < b.Z ? a.Z : b.Z; a.W = a.W < b.W ? a.W : b.W; return a; } /// <summary> /// Calculate the component-wise minimum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise minimum</param> public static void Min(ref Vector4 a, ref Vector4 b, out Vector4 result) { result.X = a.X < b.X ? a.X : b.X; result.Y = a.Y < b.Y ? a.Y : b.Y; result.Z = a.Z < b.Z ? a.Z : b.Z; result.W = a.W < b.W ? a.W : b.W; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <returns>The component-wise maximum</returns> public static Vector4 Max(Vector4 a, Vector4 b) { a.X = a.X > b.X ? a.X : b.X; a.Y = a.Y > b.Y ? a.Y : b.Y; a.Z = a.Z > b.Z ? a.Z : b.Z; a.W = a.W > b.W ? a.W : b.W; return a; } /// <summary> /// Calculate the component-wise maximum of two vectors /// </summary> /// <param name="a">First operand</param> /// <param name="b">Second operand</param> /// <param name="result">The component-wise maximum</param> public static void Max(ref Vector4 a, ref Vector4 b, out Vector4 result) { result.X = a.X > b.X ? a.X : b.X; result.Y = a.Y > b.Y ? a.Y : b.Y; result.Z = a.Z > b.Z ? a.Z : b.Z; result.W = a.W > b.W ? a.W : b.W; } /// <summary> /// Calculate the dot product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <returns>The dot product of the two inputs</returns> public static float Dot(Vector4 left, Vector4 right) { return left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W; } /// <summary> /// Calculate the dot product of two vectors /// </summary> /// <param name="left">First operand</param> /// <param name="right">Second operand</param> /// <param name="result">The dot product of the two inputs</param> public static void Dot(ref Vector4 left, ref Vector4 right, out float result) { result = left.X * right.X + left.Y * right.Y + left.Z * right.Z + left.W * right.W; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <returns>a when blend=0, b when blend=1, and a linear combination otherwise</returns> public static Vector4 Lerp(Vector4 a, Vector4 b, float blend) { a.X = blend * (b.X - a.X) + a.X; a.Y = blend * (b.Y - a.Y) + a.Y; a.Z = blend * (b.Z - a.Z) + a.Z; a.W = blend * (b.W - a.W) + a.W; return a; } /// <summary> /// Returns a new Vector that is the linear blend of the 2 given Vectors /// </summary> /// <param name="a">First input vector</param> /// <param name="b">Second input vector</param> /// <param name="blend">The blend factor. a when blend=0, b when blend=1.</param> /// <param name="result">a when blend=0, b when blend=1, and a linear combination otherwise</param> public static void Lerp(ref Vector4 a, ref Vector4 b, float blend, out Vector4 result) { result.X = blend * (b.X - a.X) + a.X; result.Y = blend * (b.Y - a.Y) + a.Y; result.Z = blend * (b.Z - a.Z) + a.Z; result.W = blend * (b.W - a.W) + a.W; } /// <summary> /// Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <returns>The transformed vector</returns> public static Vector4 Transform(Vector4 vec, Matrix4 mat) { Vector4 result; Transform(ref vec, ref mat, out result); return result; } /// <summary> /// Transform a Vector by the given Matrix</summary> /// <param name="vec">The vector to transform</param> /// <param name="mat">The desired transformation</param> /// <param name="result">The transformed vector</param> public static void Transform(ref Vector4 vec, ref Matrix4 mat, out Vector4 result) { result.X = vec.X * mat.Row0.X + vec.Y * mat.Row1.X + vec.Z * mat.Row2.X + vec.W * mat.Row3.X; result.Y = vec.X * mat.Row0.Y + vec.Y * mat.Row1.Y + vec.Z * mat.Row2.Y + vec.W * mat.Row3.Y; result.Z = vec.X * mat.Row0.Z + vec.Y * mat.Row1.Z + vec.Z * mat.Row2.Z + vec.W * mat.Row3.Z; result.W = vec.X * mat.Row0.W + vec.Y * mat.Row1.W + vec.Z * mat.Row2.W + vec.W * mat.Row3.W; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <returns>The result of the operation.</returns> public static Vector4 Transform(Vector4 vec, Quaternion quat) { Vector4 result; Transform(ref vec, ref quat, out result); return result; } /// <summary> /// Transforms a vector by a quaternion rotation. /// </summary> /// <param name="vec">The vector to transform.</param> /// <param name="quat">The quaternion to rotate the vector by.</param> /// <param name="result">The result of the operation.</param> public static void Transform(ref Vector4 vec, ref Quaternion quat, out Vector4 result) { Quaternion v = new Quaternion(vec.X, vec.Y, vec.Z, vec.W), i, t; Quaternion.Invert(ref quat, out i); Quaternion.Multiply(ref quat, ref v, out t); Quaternion.Multiply(ref t, ref i, out v); result = new Vector4(v.X, v.Y, v.Z, v.W); } /// <summary> /// Adds two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator +(Vector4 left, Vector4 right) { return new Vector4( left.X + right.X, left.Y + right.Y, left.Z + right.Z, left.W + right.W); } /// <summary> /// Subtracts two instances. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator -(Vector4 left, Vector4 right) { return new Vector4( left.X - right.X, left.Y - right.Y, left.Z - right.Z, left.W - right.W); } /// <summary> /// Negates an instance. /// </summary> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator -(Vector4 vec) { return new Vector4( -vec.X, -vec.Y, -vec.Z, -vec.W); } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator *(Vector4 vec, float scale) { return new Vector4( vec.X * scale, vec.Y * scale, vec.Z * scale, vec.W * scale); } /// <summary> /// Scales an instance by a vector. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator *(Vector4 vec, Vector4 scale) { return new Vector4( vec.X * scale.X, vec.Y * scale.Y, vec.Z * scale.Z, vec.W * scale.W); } /// <summary> /// Multiplies an instance by a scalar. /// </summary> /// <param name="scale">The scalar.</param> /// <param name="vec">The instance.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator *(float scale, Vector4 vec) { return vec * scale; } /// <summary> /// Divides an instance by a scalar. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator /(Vector4 vec, float scale) { return vec * (1.0f / scale); } /// <summary> /// Divides an instance by a vector. /// </summary> /// <param name="vec">The instance.</param> /// <param name="scale">The scalar.</param> /// <returns>The result of the calculation.</returns> public static Vector4 operator /(Vector4 vec, Vector4 scale) { return new Vector4( vec.X / scale.X, vec.Y / scale.Y, vec.Z / scale.Z, vec.W / scale.W); } /// <summary> /// Compares two instances for equality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left equals right; false otherwise.</returns> public static bool operator ==(Vector4 left, Vector4 right) { return left.Equals(right); } /// <summary> /// Compares two instances for inequality. /// </summary> /// <param name="left">The first instance.</param> /// <param name="right">The second instance.</param> /// <returns>True, if left does not equa lright; false otherwise.</returns> public static bool operator !=(Vector4 left, Vector4 right) { return !left.Equals(right); } /// <summary> /// Returns a System.String that represents the current Vector4. /// </summary> public override string ToString() { return string.Format("({0}, {1}, {2}, {3})", this.X, this.Y, this.Z, this.W); } /// <summary> /// Returns the hashcode for this instance. /// </summary> /// <returns>A System.Int32 containing the unique hashcode for this instance.</returns> public override int GetHashCode() { return this.X.GetHashCode() ^ this.Y.GetHashCode() ^ this.Z.GetHashCode() ^ this.W.GetHashCode(); } /// <summary> /// Indicates whether this instance and a specified object are equal. /// </summary> /// <param name="obj">The object to compare to.</param> /// <returns>True if the instances are equal; false otherwise.</returns> public override bool Equals(object obj) { if (!(obj is Vector4)) return false; return this.Equals((Vector4)obj); } /// <summary> /// Indicates whether the current vector is equal to another vector.</summary> /// <param name="other">A vector to compare with this vector.</param> /// <returns>true if the current vector is equal to the vector parameter; otherwise, false.</returns> public bool Equals(Vector4 other) { return this.X == other.X && this.Y == other.Y && this.Z == other.Z && this.W == other.W; } } }
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="Extensions.cs" company="Rare Crowds Inc"> // Copyright 2012-2013 Rare Crowds, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // -------------------------------------------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Linq; using DataAccessLayer; using Diagnostics; using Newtonsoft.Json; namespace EntityUtilities { /// <summary> /// Useful extensions /// </summary> public static class Extensions { /// <summary>Serialize entity to JSON.</summary> /// <param name="entity">The entity</param> /// <returns>JSON string. </returns> public static string SerializeToJson(this IEntity entity) { return SerializeToJson(entity, new EntitySerializationFilter()); } /// <summary>Serialize a raw entity to Json.</summary> /// <param name="entity">The entity.</param> /// <param name="filter">The entity filter.</param> /// <returns>A JSON string.</returns> public static string SerializeToJson(this IEntity entity, IEntityFilter filter) { return EntityJsonSerializer.SerializeToJson(entity, filter); } /// <summary> /// Serializes an enumerable of entities to a json list /// </summary> /// <param name="entities">The entities</param> /// <typeparam name="TEntity">The type of entity.</typeparam> /// <returns>The json list</returns> public static string SerializeToJson<TEntity>(this IEnumerable<TEntity> entities) where TEntity : IEntity { return SerializeToJson(entities, new EntitySerializationFilter()); } /// <summary> /// Serializes an enumerable of entities to a json list /// </summary> /// <param name="entities">The entities</param> /// <param name="filter">The entity filter.</param> /// <typeparam name="TEntity">The type of entity.</typeparam> /// <returns>The json list</returns> public static string SerializeToJson<TEntity>( this IEnumerable<TEntity> entities, IEntityFilter filter) where TEntity : IEntity { var queryValues = filter == null ? null : filter.EntityQueries.QueryStringParams; // Certain queries may have user imposed limits. The user may specify any combination of the following query values: // 1. "NumObjects" to limit the number of return values // 2. "Top" to indicate return values from the top of the list // 3. "Skip" to indicate the return values skip this number from the top of the list. // 4. "OrderBy" to indicate which property is the key for the returned order // to account for these, use a combination of the Linq Skip and Take // ToDo: Implement OrderBy if (queryValues != null && queryValues.Keys.Contains("numobjects") && queryValues.Keys.Contains("skip")) { string[] entityJsons = entities .Select(e => e.SerializeToJson(filter)) .Skip(Convert.ToInt32(queryValues["skip"], CultureInfo.InvariantCulture)) .Take(Convert.ToInt32(queryValues["numobjects"], CultureInfo.InvariantCulture)) .ToArray(); return "[" + string.Join(", ", entityJsons) + "]"; } // ToDo: this may be redundant with "Top". This will always have the same effect as using Top since NumObjects is // ToDo: selecting a count to return from the top if (queryValues != null && queryValues.Keys.Contains("numobjects")) { string[] entityJsons = entities .Select(e => e.SerializeToJson(filter)) .Take(Convert.ToInt32(queryValues["numobjects"], CultureInfo.InvariantCulture)) .ToArray(); return "[" + string.Join(", ", entityJsons) + "]"; } if (queryValues != null && queryValues.Keys.Contains("top") && queryValues.Keys.Contains("skip")) { string[] entityJsons = entities .Select(e => e.SerializeToJson(filter)) .Skip(Convert.ToInt32(queryValues["skip"], CultureInfo.InvariantCulture)) .Take(Convert.ToInt32(queryValues["top"], CultureInfo.InvariantCulture)) .ToArray(); return "[" + string.Join(", ", entityJsons) + "]"; } if (queryValues != null && queryValues.Keys.Contains("top")) { string[] entityJsons = entities .Select(e => e.SerializeToJson(filter)) .Take(Convert.ToInt32(queryValues["top"], CultureInfo.InvariantCulture)) .ToArray(); return "[" + string.Join(", ", entityJsons) + "]"; } string[] entityJsons2 = entities .Select(e => e.SerializeToJson(filter)) .Where(e => !string.IsNullOrEmpty(e)) .ToArray(); return "[" + string.Join(", ", entityJsons2) + "]"; } /// <summary> /// Serialize the Association to a dictionary representation of a Json object that will be part of a collection. /// ExternalName will be omitted because that will be the collection name. /// </summary> /// <param name="this">The association</param> /// <returns>A dictionary compatible with JavascriptSerializer.Serialize</returns> public static Dictionary<string, object> SerializeToJsonCollectionFragmentDictionary(this Association @this) { var jsonCollectionFragment = new Dictionary<string, object> { { "TargetEntityId", (string)@this.TargetEntityId }, { "TargetEntityCategory", @this.TargetEntityCategory }, { "TargetExternalType", @this.TargetExternalType }, { "AssociationType", Association.StringFromAssociationType(@this.AssociationType) } }; return jsonCollectionFragment; } /// <summary>Sets the custom configuration settings for the entity</summary> /// <param name="this">The entity</param> /// <param name="settings">The settings</param> [SuppressMessage("Microsoft.Design", "CA1011", Justification = "IRawEntity should not be used outside the DAL")] public static void SetConfigSettings(this IEntity @this, IDictionary<string, string> settings) { var json = JsonConvert.SerializeObject(settings); @this.SetSystemProperty("config", json); } /// <summary>Gets the custom configuration settings for the entity</summary> /// <param name="this">The entity</param> /// <returns>The settings</returns> [SuppressMessage("Microsoft.Design", "CA1011", Justification = "IRawEntity should not be used outside the DAL")] public static IDictionary<string, string> GetConfigSettings(this IEntity @this) { var configJson = @this.TryGetSystemProperty<string>("config"); return configJson != null ? JsonConvert.DeserializeObject<IDictionary<string, string>>(configJson) : new Dictionary<string, string>(); } /// <summary>Sets a system property</summary> /// <param name="this">The entity</param> /// <param name="propertyName">System property name</param> /// <param name="propertyValue">System property value</param> [SuppressMessage("Microsoft.Design", "CA1011", Justification = "IRawEntity should not be used outside the DAL")] public static void SetSystemProperty(this IEntity @this, string propertyName, dynamic propertyValue) { var property = @this.Properties .Where(p => p.Name.ToUpperInvariant() == propertyName.ToUpperInvariant()) .SingleOrDefault(); if (property == null) { @this.Properties.Add(property = new EntityProperty(propertyName, propertyValue, PropertyFilter.System)); } else { property.Value = propertyValue; } } /// <summary> /// Gets whether an entity has a value for the specified system property /// </summary> /// <param name="this">The entity</param> /// <param name="propertyName">System property name</param> /// <returns>True if the entity has a value for the system property; otherwise, false.</returns> [SuppressMessage("Microsoft.Design", "CA1011", Justification = "IRawEntity should not be used outside the DAL")] public static bool HasSystemProperty(this IEntity @this, string propertyName) { return @this.Properties .Any(p => p.Name.ToUpperInvariant() == propertyName.ToUpperInvariant() && p.IsSystemProperty); } /// <summary>Tries to get a system property</summary> /// <typeparam name="TValue">Type of the value</typeparam> /// <param name="this">The entity</param> /// <param name="propertyName">System property name</param> /// <returns>System property value</returns> [SuppressMessage("Microsoft.Design", "CA1011", Justification = "IRawEntity should not be used outside the DAL")] public static TValue GetSystemProperty<TValue>(this IEntity @this, string propertyName) { if (!HasSystemProperty(@this, propertyName)) { throw new ArgumentException("System property not found: {0}".FormatInvariant(propertyName), "propertyName"); } return TryGetSystemProperty<TValue>(@this, propertyName); } /// <summary>Tries to get a system property</summary> /// <typeparam name="TValue">Type of the value</typeparam> /// <param name="this">The entity</param> /// <param name="propertyName">System property name</param> /// <returns>System property value</returns> [SuppressMessage("Microsoft.Design", "CA1011", Justification = "IRawEntity should not be used outside the DAL")] public static TValue TryGetSystemProperty<TValue>(this IEntity @this, string propertyName) { if (!HasSystemProperty(@this, propertyName)) { return default(TValue); } return (TValue)(dynamic)@this.Properties .Where(p => p.Name.ToUpperInvariant() == propertyName.ToUpperInvariant()) .Select(p => p.Value) .Single(); } /// <summary>Sets the type of user as the UserEntity.ExternalType</summary> /// <param name="this">The UserEntity</param> /// <param name="userType">The user type</param> /// <exception cref="ArgumentException">Attempted to set UserType.Unknown</exception> [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for UserEntity")] public static void SetUserType(this UserEntity @this, UserType userType) { if (userType == UserType.Unknown) { throw new ArgumentException("Cannot set user type to {0}".FormatInvariant(userType), "userType"); } @this.ExternalType = userType.ToString(); } /// <summary>Gets the type of user from the UserEntity.ExternalType</summary> /// <param name="this">The UserEntity</param> /// <returns>The user type</returns> [SuppressMessage("Microsoft.Design", "CA1011", Justification = "Only valid for UserEntity")] public static UserType GetUserType(this UserEntity @this) { UserType value; return Enum.TryParse<UserType>(@this.ExternalType, true, out value) ? value : UserType.Unknown; } /// <summary>Sets the entity's owner</summary> /// <param name="this">The entity</param> /// <param name="userId">The UserEntity.UserId of the owner</param> public static void SetOwnerId(this IEntity @this, string userId) { @this.SetPropertyByName<string>("OwnerId", userId); } /// <summary>Gets the entity's owner</summary> /// <param name="this">The entity</param> /// <returns>The UserEntity.UserId of the owner</returns> public static string GetOwnerId(this IEntity @this) { return @this.TryGetPropertyByName<string>("OwnerId", null); } /// <summary>Safely gets a numeric property for an entity</summary> /// <remarks>Any errors are caught and logged as warnings</remarks> /// <param name="this">The entity</param> /// <param name="propertyName">Property name</param> /// <returns>The property value if available; otherwise, null</returns> [SuppressMessage("Microsoft.Design", "CA1031", Justification = "Try pattern must not throw. Exception is logged.")] public static int? TryGetNumericPropertyValue(this IEntity @this, string propertyName) { try { try { var value = @this.TryGetPropertyValueByName(propertyName); return value != null ? (int?)(double)value : null; } catch (ArgumentException ae) { if (!ae.Message.ToLowerInvariant().Contains("expected type")) { throw; } // Try to coerce a number from the serialization value return Convert.ToInt32( @this.TryGetPropertyValueByName(propertyName).SerializationValue, CultureInfo.InvariantCulture); } } catch (Exception e) { LogManager.Log( LogLevels.Warning, "Error getting property '{0}' from entity '{1}' ({2}): {3}", propertyName, @this.ExternalName, @this.ExternalEntityId, e); return null; } } } }
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System; using System.Globalization; using Xunit; public static class UInt32Tests { [Fact] public static void TestCtor() { UInt32 i = new UInt32(); Assert.True(i == 0); i = 41; Assert.True(i == 41); } [Fact] public static void TestMaxValue() { UInt32 max = UInt32.MaxValue; Assert.True(max == (UInt32)0xFFFFFFFF); } [Fact] public static void TestMinValue() { UInt32 min = UInt32.MinValue; Assert.True(min == 0); } [Fact] public static void TestCompareToObject() { UInt32 i = 234; IComparable comparable = i; Assert.Equal(1, comparable.CompareTo(null)); Assert.Equal(0, comparable.CompareTo((UInt32)234)); Assert.True(comparable.CompareTo(UInt32.MinValue) > 0); Assert.True(comparable.CompareTo((UInt32)0) > 0); Assert.True(comparable.CompareTo((UInt32)(23)) > 0); Assert.True(comparable.CompareTo((UInt32)123) > 0); Assert.True(comparable.CompareTo((UInt32)456) < 0); Assert.True(comparable.CompareTo(UInt32.MaxValue) < 0); Assert.Throws<ArgumentException>(() => comparable.CompareTo("a")); } [Fact] public static void TestCompareTo() { UInt32 i = 234; Assert.Equal(0, i.CompareTo((UInt32)234)); Assert.True(i.CompareTo(UInt32.MinValue) > 0); Assert.True(i.CompareTo((UInt32)0) > 0); Assert.True(i.CompareTo((UInt32)123) > 0); Assert.True(i.CompareTo((UInt32)456) < 0); Assert.True(i.CompareTo(UInt32.MaxValue) < 0); } [Fact] public static void TestEqualsObject() { UInt32 i = 789; object obj1 = (UInt32)789; Assert.True(i.Equals(obj1)); object obj3 = (UInt32)0; Assert.True(!i.Equals(obj3)); } [Fact] public static void TestEquals() { UInt32 i = 911; Assert.True(i.Equals((UInt32)911)); Assert.True(!i.Equals((UInt32)0)); } [Fact] public static void TestGetHashCode() { UInt32 i1 = 123; UInt32 i2 = 654; Assert.NotEqual(0, i1.GetHashCode()); Assert.NotEqual(i1.GetHashCode(), i2.GetHashCode()); } [Fact] public static void TestToString() { UInt32 i1 = 6310; Assert.Equal("6310", i1.ToString()); } [Fact] public static void TestToStringFormatProvider() { var numberFormat = new System.Globalization.NumberFormatInfo(); UInt32 i1 = 6310; Assert.Equal("6310", i1.ToString(numberFormat)); } [Fact] public static void TestToStringFormat() { UInt32 i1 = 6310; Assert.Equal("6310", i1.ToString("G")); UInt32 i2 = 8249; Assert.Equal("8249", i2.ToString("g")); UInt32 i3 = 2468; Assert.Equal("2,468.00", i3.ToString("N")); UInt32 i4 = 0x248; Assert.Equal("248", i4.ToString("x")); } [Fact] public static void TestToStringFormatFormatProvider() { var numberFormat = new System.Globalization.NumberFormatInfo(); UInt32 i1 = 6310; Assert.Equal("6310", i1.ToString("G", numberFormat)); UInt32 i2 = 8249; Assert.Equal("8249", i2.ToString("g", numberFormat)); numberFormat.NegativeSign = "xx"; // setting it to trash to make sure it doesn't show up numberFormat.NumberGroupSeparator = "*"; numberFormat.NumberNegativePattern = 0; UInt32 i3 = 2468; Assert.Equal("2*468.00", i3.ToString("N", numberFormat)); } [Fact] public static void TestParse() { Assert.Equal<UInt32>(123, UInt32.Parse("123")); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyle() { Assert.Equal<UInt32>(0x123, UInt32.Parse("123", NumberStyles.HexNumber)); Assert.Equal<UInt32>(1000, UInt32.Parse("1,000", NumberStyles.AllowThousands)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseFormatProvider() { var nfi = new NumberFormatInfo(); Assert.Equal<UInt32>(123, UInt32.Parse("123", nfi)); //TODO: Negative tests once we get better exceptions } [Fact] public static void TestParseNumberStyleFormatProvider() { var nfi = new NumberFormatInfo(); Assert.Equal<UInt32>(0x123, UInt32.Parse("123", NumberStyles.HexNumber, nfi)); nfi.CurrencySymbol = "$"; Assert.Equal<UInt32>(1000, UInt32.Parse("$1,000", NumberStyles.Currency, nfi)); //TODO: Negative tests once we get better exception support } [Fact] public static void TestTryParse() { // Defaults NumberStyles.Integer = NumberStyles.AllowLeadingWhite | NumberStyles.AllowTrailingWhite | NumberStyles.AllowLeadingSign UInt32 i; Assert.True(UInt32.TryParse("123", out i)); // Simple Assert.Equal<UInt32>(123, i); Assert.False(UInt32.TryParse("-385", out i)); // LeadingSign negative Assert.True(UInt32.TryParse(" 678 ", out i)); // Leading/Trailing whitespace Assert.Equal<UInt32>(678, i); Assert.False(UInt32.TryParse("$1000", out i)); // Currency Assert.False(UInt32.TryParse("1,000", out i)); // Thousands Assert.False(UInt32.TryParse("abc", out i)); // Hex digits Assert.False(UInt32.TryParse("678.90", out i)); // Decimal Assert.False(UInt32.TryParse("(135)", out i)); // Parentheses Assert.False(UInt32.TryParse("1E23", out i)); // Exponent } [Fact] public static void TestTryParseNumberStyleFormatProvider() { UInt32 i; var nfi = new NumberFormatInfo(); Assert.True(UInt32.TryParse("123", NumberStyles.Any, nfi, out i)); // Simple positive Assert.Equal<UInt32>(123, i); Assert.True(UInt32.TryParse("123", NumberStyles.HexNumber, nfi, out i)); // Simple Hex Assert.Equal<UInt32>(0x123, i); nfi.CurrencySymbol = "$"; Assert.True(UInt32.TryParse("$1,000", NumberStyles.Currency, nfi, out i)); // Currency/Thousands postive Assert.Equal<UInt32>(1000, i); Assert.False(UInt32.TryParse("abc", NumberStyles.None, nfi, out i)); // Hex Number negative Assert.True(UInt32.TryParse("abc", NumberStyles.HexNumber, nfi, out i)); // Hex Number positive Assert.Equal<UInt32>(0xabc, i); Assert.False(UInt32.TryParse("678.90", NumberStyles.Integer, nfi, out i)); // Decimal Assert.False(UInt32.TryParse(" 678 ", NumberStyles.None, nfi, out i)); // Trailing/Leading whitespace negative Assert.False(UInt32.TryParse("(135)", NumberStyles.AllowParentheses, nfi, out i)); // Parenthese negative } }
using System; using System.IO; using System.Text; namespace GuruComponents.Netrix.HtmlFormatting.Elements { sealed class FormattedTextWriter : TextWriter { private TextWriter baseWriter; private string indentString; private int currentColumn; private int indentLevel; private bool indentPending; private bool onNewLine; public override Encoding Encoding { get { return baseWriter.Encoding; } } public override string NewLine { get { return baseWriter.NewLine; } set { baseWriter.NewLine = value; } } public int Indent { get { return indentLevel; } set { if (value < 0) { value = 0; } indentLevel = value; } } public FormattedTextWriter(TextWriter writer, string indentString) { baseWriter = writer; this.indentString = indentString; onNewLine = true; currentColumn = 0; } public override void Close() { baseWriter.Close(); } public override void Flush() { baseWriter.Flush(); } public static bool HasBackWhiteSpace(string s) { if (s == null || s.Length == 0) { return false; } else { return Char.IsWhiteSpace(s[s.Length - 1]); } } public static bool HasFrontWhiteSpace(string s) { if (s == null || s.Length == 0) { return false; } else { return Char.IsWhiteSpace(s[0]); } } public static bool IsWhiteSpace(string s) { for (int i = 0; i < s.Length; i++) { if (!Char.IsWhiteSpace(s[i])) { return false; } } return true; } private string MakeSingleLine(string s) { StringBuilder stringBuilder = new StringBuilder(); int i = 0; while (i < s.Length) { char ch = s[i]; if (Char.IsWhiteSpace(ch)) { stringBuilder.Append(' '); for (; i < s.Length && Char.IsWhiteSpace(s[i]); i++) { } } else { stringBuilder.Append(ch); i++; } } return stringBuilder.ToString(); } public static string Trim(string text, bool frontWhiteSpace) { if (text.Length == 0) { return String.Empty; } if (IsWhiteSpace(text)) { if (frontWhiteSpace) { return " "; } else { return String.Empty; } } string str = text.Trim(); if (frontWhiteSpace && HasFrontWhiteSpace(text)) { str = String.Concat(" ", str); } if (HasBackWhiteSpace(text)) { str = String.Concat(str, " "); } return str; } private void OutputIndent() { if (indentPending) { for (int i = 0; i < indentLevel; i++) { baseWriter.Write(indentString); } indentPending = false; } } public void WriteLiteral(string s) { if (s.Length != 0) { StringReader stringReader = new StringReader(s); string str1 = stringReader.ReadLine(); string str2 = stringReader.ReadLine(); while (str1 != null) { Write(str1); str1 = str2; str2 = stringReader.ReadLine(); if (str1 != null) { WriteLine(); } if (str2 != null) { str1 = str1.Trim(); } else if (str1 != null) { str1 = Trim(str1, false); } } } } public void WriteLiteralWrapped(string s, int maxLength) { if (s.Length != 0) { string[] strs = MakeSingleLine(s).Split(null); if (HasFrontWhiteSpace(s)) { Write(' '); } for (int i = 0; i < (int)strs.Length; i++) { if (strs[i].Length > 0) { Write(strs[i]); if (i < (int)strs.Length - 1 && strs[i + 1].Length > 0) { if (currentColumn > maxLength) { WriteLine(); } else { Write(' '); } } } } if (HasBackWhiteSpace(s) && !IsWhiteSpace(s)) { Write(' '); } } } public void WriteLineIfNotOnNewLine() { if (!onNewLine) { baseWriter.WriteLine(); onNewLine = true; currentColumn = 0; indentPending = true; } } public override void Write(string s) { OutputIndent(); baseWriter.Write(s); onNewLine = false; currentColumn += s.Length; } public override void Write(bool value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(char value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn++; } public override void Write(char[] buffer) { OutputIndent(); baseWriter.Write(buffer); onNewLine = false; currentColumn += (int)buffer.Length; } public override void Write(char[] buffer, int index, int count) { OutputIndent(); baseWriter.Write(buffer, index, count); onNewLine = false; currentColumn += count; } public override void Write(double value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(float value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(int value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(long value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(object value) { OutputIndent(); baseWriter.Write(value); onNewLine = false; currentColumn += value.ToString().Length; } public override void Write(string format, object arg0) { OutputIndent(); string str = String.Format(format, arg0); baseWriter.Write(str); onNewLine = false; currentColumn += str.Length; } public override void Write(string format, object arg0, object arg1) { OutputIndent(); string str = String.Format(format, arg0, arg1); baseWriter.Write(str); onNewLine = false; currentColumn += str.Length; } public override void Write(string format, params object[] arg) { OutputIndent(); string str = String.Format(format, arg); baseWriter.Write(str); onNewLine = false; currentColumn += str.Length; } public override void WriteLine(string s) { OutputIndent(); baseWriter.WriteLine(s); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine() { OutputIndent(); baseWriter.WriteLine(); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(bool value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(char value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(char[] buffer) { OutputIndent(); baseWriter.WriteLine(buffer); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(char[] buffer, int index, int count) { OutputIndent(); baseWriter.WriteLine(buffer, index, count); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(double value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(float value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(int value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(long value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(object value) { OutputIndent(); baseWriter.WriteLine(value); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(string format, object arg0) { OutputIndent(); baseWriter.WriteLine(format, arg0); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(string format, object arg0, object arg1) { OutputIndent(); baseWriter.WriteLine(format, arg0, arg1); indentPending = true; onNewLine = true; currentColumn = 0; } public override void WriteLine(string format, params object[] arg) { OutputIndent(); baseWriter.WriteLine(format, arg); indentPending = true; currentColumn = 0; onNewLine = true; } } }
// // enum.cs: Enum handling. // // Author: Miguel de Icaza (miguel@gnu.org) // Ravi Pratap (ravi@ximian.com) // Marek Safar (marek.safar@seznam.cz) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2001 Ximian, Inc (http://www.ximian.com) // Copyright 2003-2003 Novell, Inc (http://www.novell.com) // Copyright 2011 Xamarin Inc // using System; #if STATIC using MetaType = IKVM.Reflection.Type; using IKVM.Reflection; #else using MetaType = System.Type; using System.Reflection; #endif namespace Mono.CSharp { public class EnumMember : Const { class EnumTypeExpr : TypeExpr { public override TypeSpec ResolveAsType (IMemberContext ec) { type = ec.CurrentType; eclass = ExprClass.Type; return type; } } public EnumMember (Enum parent, MemberName name, Attributes attrs) : base (parent, new EnumTypeExpr (), Modifiers.PUBLIC, name, attrs) { } static bool IsValidEnumType (TypeSpec t) { switch (t.BuiltinType) { case BuiltinTypeSpec.Type.Int: case BuiltinTypeSpec.Type.UInt: case BuiltinTypeSpec.Type.Long: case BuiltinTypeSpec.Type.Byte: case BuiltinTypeSpec.Type.SByte: case BuiltinTypeSpec.Type.Short: case BuiltinTypeSpec.Type.UShort: case BuiltinTypeSpec.Type.ULong: case BuiltinTypeSpec.Type.Char: return true; default: return t.IsEnum; } } public override Constant ConvertInitializer (ResolveContext rc, Constant expr) { if (expr is EnumConstant) expr = ((EnumConstant) expr).Child; var underlying = ((Enum) Parent).UnderlyingType; if (expr != null) { expr = expr.ImplicitConversionRequired (rc, underlying, Location); if (expr != null && !IsValidEnumType (expr.Type)) { Enum.Error_1008 (Location, Report); expr = null; } } if (expr == null) expr = New.Constantify (underlying, Location); return new EnumConstant (expr, MemberType); } public override bool Define () { if (!ResolveMemberType ()) return false; const FieldAttributes attr = FieldAttributes.Public | FieldAttributes.Static | FieldAttributes.Literal; FieldBuilder = Parent.TypeBuilder.DefineField (Name, MemberType.GetMetaInfo (), attr); spec = new ConstSpec (Parent.Definition, this, MemberType, FieldBuilder, ModFlags, initializer); Parent.MemberCache.AddMember (spec); return true; } public override void Accept (StructuralVisitor visitor) { visitor.Visit (this); } } /// <summary> /// Enumeration container /// </summary> public class Enum : TypeDefinition { // // Implicit enum member initializer, used when no constant value is provided // sealed class ImplicitInitializer : Expression { readonly EnumMember prev; readonly EnumMember current; public ImplicitInitializer (EnumMember current, EnumMember prev) { this.current = current; this.prev = prev; } public override bool ContainsEmitWithAwait () { return false; } public override Expression CreateExpressionTree (ResolveContext ec) { throw new NotSupportedException ("Missing Resolve call"); } protected override Expression DoResolve (ResolveContext rc) { // We are the first member if (prev == null) { return New.Constantify (current.Parent.Definition, Location); } var c = ((ConstSpec) prev.Spec).GetConstant (rc) as EnumConstant; try { return c.Increment (); } catch (OverflowException) { rc.Report.Error (543, current.Location, "The enumerator value `{0}' is outside the range of enumerator underlying type `{1}'", current.GetSignatureForError (), ((Enum) current.Parent).UnderlyingType.GetSignatureForError ()); return New.Constantify (current.Parent.Definition, current.Location); } } public override void Emit (EmitContext ec) { throw new NotSupportedException ("Missing Resolve call"); } } public static readonly string UnderlyingValueField = "value__"; const Modifiers AllowedModifiers = Modifiers.NEW | Modifiers.PUBLIC | Modifiers.PROTECTED | Modifiers.INTERNAL | Modifiers.PRIVATE; readonly FullNamedExpression underlying_type_expr; public Enum (TypeContainer parent, FullNamedExpression type, Modifiers mod_flags, MemberName name, Attributes attrs) : base (parent, name, attrs, MemberKind.Enum) { underlying_type_expr = type; var accmods = IsTopLevel ? Modifiers.INTERNAL : Modifiers.PRIVATE; ModFlags = ModifiersExtensions.Check (AllowedModifiers, mod_flags, accmods, Location, Report); spec = new EnumSpec (null, this, null, null, ModFlags); } #region Properties public override AttributeTargets AttributeTargets { get { return AttributeTargets.Enum; } } public FullNamedExpression BaseTypeExpression { get { return underlying_type_expr; } } protected override TypeAttributes TypeAttr { get { return base.TypeAttr | TypeAttributes.Class | TypeAttributes.Sealed; } } public TypeSpec UnderlyingType { get { return ((EnumSpec) spec).UnderlyingType; } } #endregion public override void Accept (StructuralVisitor visitor) { visitor.Visit (this); } public void AddEnumMember (EnumMember em) { if (em.Name == UnderlyingValueField) { Report.Error (76, em.Location, "An item in an enumeration cannot have an identifier `{0}'", UnderlyingValueField); return; } AddMember (em); } public static void Error_1008 (Location loc, Report Report) { Report.Error (1008, loc, "Type byte, sbyte, short, ushort, int, uint, long or ulong expected"); } protected override void DoDefineContainer () { ((EnumSpec) spec).UnderlyingType = underlying_type_expr == null ? Compiler.BuiltinTypes.Int : underlying_type_expr.Type; TypeBuilder.DefineField (UnderlyingValueField, UnderlyingType.GetMetaInfo (), FieldAttributes.Public | FieldAttributes.SpecialName | FieldAttributes.RTSpecialName); DefineBaseTypes (); } protected override bool DoDefineMembers () { for (int i = 0; i < Members.Count; ++i) { EnumMember em = (EnumMember) Members[i]; if (em.Initializer == null) { em.Initializer = new ImplicitInitializer (em, i == 0 ? null : (EnumMember) Members[i - 1]); } em.Define (); } return true; } public override bool IsUnmanagedType () { return true; } protected override TypeSpec[] ResolveBaseTypes (out FullNamedExpression base_class) { base_type = Compiler.BuiltinTypes.Enum; base_class = null; return null; } protected override bool VerifyClsCompliance () { if (!base.VerifyClsCompliance ()) return false; switch (UnderlyingType.BuiltinType) { case BuiltinTypeSpec.Type.UInt: case BuiltinTypeSpec.Type.ULong: case BuiltinTypeSpec.Type.UShort: Report.Warning (3009, 1, Location, "`{0}': base type `{1}' is not CLS-compliant", GetSignatureForError (), TypeManager.CSharpName (UnderlyingType)); break; } return true; } } class EnumSpec : TypeSpec { TypeSpec underlying; public EnumSpec (TypeSpec declaringType, ITypeDefinition definition, TypeSpec underlyingType, MetaType info, Modifiers modifiers) : base (MemberKind.Enum, declaringType, definition, info, modifiers | Modifiers.SEALED) { this.underlying = underlyingType; } public TypeSpec UnderlyingType { get { return underlying; } set { if (underlying != null) throw new InternalErrorException ("UnderlyingType reset"); underlying = value; } } public static TypeSpec GetUnderlyingType (TypeSpec t) { return ((EnumSpec) t.GetDefinition ()).UnderlyingType; } public static bool IsValidUnderlyingType (TypeSpec type) { switch (type.BuiltinType) { case BuiltinTypeSpec.Type.Int: case BuiltinTypeSpec.Type.UInt: case BuiltinTypeSpec.Type.Long: case BuiltinTypeSpec.Type.Byte: case BuiltinTypeSpec.Type.SByte: case BuiltinTypeSpec.Type.Short: case BuiltinTypeSpec.Type.UShort: case BuiltinTypeSpec.Type.ULong: return true; } return false; } } }
// Copyright (c) The Avalonia Project. All rights reserved. // Licensed under the MIT license. See licence.md file in the project root for full license information. using System; using System.Collections.Generic; using System.Linq; using Avalonia.Collections; using Avalonia.Controls.Presenters; using Avalonia.Controls.Templates; using Avalonia.Data; using Avalonia.Input; using Avalonia.LogicalTree; using Avalonia.Markup.Data; using Avalonia.UnitTests; using Xunit; namespace Avalonia.Controls.UnitTests { public class TreeViewTests { [Fact] public void Items_Should_Be_Created() { var target = new TreeView { Template = CreateTreeViewTemplate(), Items = CreateTestTreeData(), DataTemplates = CreateNodeDataTemplate(), }; ApplyTemplates(target); Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0)); Assert.Equal(new[] { "Child1", "Child2", "Child3" }, ExtractItemHeader(target, 1)); Assert.Equal(new[] { "Grandchild2a" }, ExtractItemHeader(target, 2)); } [Fact] public void Items_Should_Be_Created_Using_ItemTemplate_If_Present() { TreeView target; var root = new TestRoot { Child = target = new TreeView { Template = CreateTreeViewTemplate(), Items = CreateTestTreeData(), ItemTemplate = new FuncTreeDataTemplate<Node>( _ => new Canvas(), x => x.Children), } }; ApplyTemplates(target); var items = target.ItemContainerGenerator.Index.Items .OfType<TreeViewItem>() .ToList(); Assert.Equal(5, items.Count); Assert.All(items, x => Assert.IsType<Canvas>(x.HeaderPresenter.Child)); } [Fact] public void Root_ItemContainerGenerator_Containers_Should_Be_Root_Containers() { var target = new TreeView { Template = CreateTreeViewTemplate(), Items = CreateTestTreeData(), DataTemplates = CreateNodeDataTemplate(), }; ApplyTemplates(target); var container = (TreeViewItem)target.ItemContainerGenerator.Containers.Single().ContainerControl; var header = (TextBlock)container.Header; Assert.Equal("Root", header.Text); } [Fact] public void Root_TreeContainerFromItem_Should_Return_Descendant_Item() { var tree = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = tree, DataTemplates = CreateNodeDataTemplate(), }; // For TreeViewItem to find its parent TreeView, OnAttachedToLogicalTree needs // to be called, which requires an IStyleRoot. var root = new TestRoot(); root.Child = target; ApplyTemplates(target); var container = target.ItemContainerGenerator.Index.ContainerFromItem( tree[0].Children[1].Children[0]); Assert.NotNull(container); var header = ((TreeViewItem)container).Header; var headerContent = ((TextBlock)header).Text; Assert.Equal("Grandchild2a", headerContent); } [Fact] public void Clicking_Item_Should_Select_It() { var tree = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = tree, DataTemplates = CreateNodeDataTemplate(), }; var visualRoot = new TestRoot(); visualRoot.Child = target; ApplyTemplates(target); var item = tree[0].Children[1].Children[0]; var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item); Assert.NotNull(container); container.RaiseEvent(new PointerPressedEventArgs { RoutedEvent = InputElement.PointerPressedEvent, MouseButton = MouseButton.Left, }); Assert.Equal(item, target.SelectedItem); Assert.True(container.IsSelected); } [Fact] public void Setting_SelectedItem_Should_Set_Container_Selected() { var tree = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = tree, DataTemplates = CreateNodeDataTemplate(), }; var visualRoot = new TestRoot(); visualRoot.Child = target; ApplyTemplates(target); var item = tree[0].Children[1].Children[0]; var container = (TreeViewItem)target.ItemContainerGenerator.Index.ContainerFromItem(item); Assert.NotNull(container); target.SelectedItem = item; Assert.True(container.IsSelected); } [Fact] public void LogicalChildren_Should_Be_Set() { var target = new TreeView { Template = CreateTreeViewTemplate(), Items = new[] { "Foo", "Bar", "Baz " }, }; ApplyTemplates(target); var result = target.GetLogicalChildren() .OfType<TreeViewItem>() .Select(x => x.Header) .OfType<TextBlock>() .Select(x => x.Text) .ToList(); Assert.Equal(new[] { "Foo", "Bar", "Baz " }, result); } [Fact] public void Removing_Item_Should_Remove_Itself_And_Children_From_Index() { var tree = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), DataTemplates = CreateNodeDataTemplate(), Items = tree, }; var root = new TestRoot(); root.Child = target; ApplyTemplates(target); Assert.Equal(5, target.ItemContainerGenerator.Index.Items.Count()); tree[0].Children.RemoveAt(1); Assert.Equal(3, target.ItemContainerGenerator.Index.Items.Count()); } [Fact] public void DataContexts_Should_Be_Correctly_Set() { var items = new object[] { "Foo", new Node { Value = "Bar" }, new TextBlock { Text = "Baz" }, new TreeViewItem { Header = "Qux" }, }; var target = new TreeView { Template = CreateTreeViewTemplate(), DataContext = "Base", DataTemplates = new DataTemplates { new FuncDataTemplate<Node>(x => new Button { Content = x }) }, Items = items, }; ApplyTemplates(target); var dataContexts = target.Presenter.Panel.Children .Cast<Control>() .Select(x => x.DataContext) .ToList(); Assert.Equal( new object[] { items[0], items[1], "Base", "Base" }, dataContexts); } [Fact] public void Control_Item_Should_Not_Be_NameScope() { var items = new object[] { new TreeViewItem(), }; var target = new TreeView { Template = CreateTreeViewTemplate(), Items = items, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var item = target.Presenter.Panel.LogicalChildren[0]; Assert.Null(NameScope.GetNameScope((TreeViewItem)item)); } [Fact] public void DataTemplate_Created_Item_Should_Be_NameScope() { var items = new object[] { "foo", }; var target = new TreeView { Template = CreateTreeViewTemplate(), Items = items, }; target.ApplyTemplate(); target.Presenter.ApplyTemplate(); var item = target.Presenter.Panel.LogicalChildren[0]; Assert.NotNull(NameScope.GetNameScope((TreeViewItem)item)); } [Fact] public void Should_React_To_Children_Changing() { var data = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = data, DataTemplates = CreateNodeDataTemplate(), }; ApplyTemplates(target); Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0)); Assert.Equal(new[] { "Child1", "Child2", "Child3" }, ExtractItemHeader(target, 1)); Assert.Equal(new[] { "Grandchild2a" }, ExtractItemHeader(target, 2)); // Make sure that the binding to Node.Children does not get collected. GC.Collect(); data[0].Children = new AvaloniaList<Node> { new Node { Value = "NewChild1", } }; Assert.Equal(new[] { "Root" }, ExtractItemHeader(target, 0)); Assert.Equal(new[] { "NewChild1" }, ExtractItemHeader(target, 1)); } [Fact] public void Keyboard_Navigation_Should_Move_To_Last_Selected_Node() { using (UnitTestApplication.Start(TestServices.RealFocus)) { var focus = FocusManager.Instance; var navigation = AvaloniaLocator.Current.GetService<IKeyboardNavigationHandler>(); var data = CreateTestTreeData(); var target = new TreeView { Template = CreateTreeViewTemplate(), Items = data, DataTemplates = CreateNodeDataTemplate(), }; var button = new Button(); var root = new TestRoot { Child = new StackPanel { Children = { target, button }, } }; ApplyTemplates(target); var item = data[0].Children[0]; var node = target.ItemContainerGenerator.Index.ContainerFromItem(item); Assert.NotNull(node); target.SelectedItem = item; node.Focus(); Assert.Same(node, focus.Current); navigation.Move(focus.Current, NavigationDirection.Next); Assert.Same(button, focus.Current); navigation.Move(focus.Current, NavigationDirection.Next); Assert.Same(node, focus.Current); } } private void ApplyTemplates(TreeView tree) { tree.ApplyTemplate(); tree.Presenter.ApplyTemplate(); ApplyTemplates(tree.Presenter.Panel.Children); } private void ApplyTemplates(IEnumerable<IControl> controls) { foreach (TreeViewItem control in controls) { control.Template = CreateTreeViewItemTemplate(); control.ApplyTemplate(); control.Presenter.ApplyTemplate(); control.HeaderPresenter.ApplyTemplate(); ApplyTemplates(control.Presenter.Panel.Children); } } private IList<Node> CreateTestTreeData() { return new AvaloniaList<Node> { new Node { Value = "Root", Children = new AvaloniaList<Node> { new Node { Value = "Child1", }, new Node { Value = "Child2", Children = new AvaloniaList<Node> { new Node { Value = "Grandchild2a", }, }, }, new Node { Value = "Child3", }, } } }; } private DataTemplates CreateNodeDataTemplate() { return new DataTemplates { new TestTreeDataTemplate() }; } private IControlTemplate CreateTreeViewTemplate() { return new FuncControlTemplate<TreeView>(parent => new ItemsPresenter { Name = "PART_ItemsPresenter", [~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty], }); } private IControlTemplate CreateTreeViewItemTemplate() { return new FuncControlTemplate<TreeViewItem>(parent => new Panel { Children = new Controls { new ContentPresenter { Name = "PART_HeaderPresenter", [~ContentPresenter.ContentProperty] = parent[~TreeViewItem.HeaderProperty], }, new ItemsPresenter { Name = "PART_ItemsPresenter", [~ItemsPresenter.ItemsProperty] = parent[~ItemsControl.ItemsProperty], } } }); } private List<string> ExtractItemHeader(TreeView tree, int level) { return ExtractItemContent(tree.Presenter.Panel, 0, level) .Select(x => x.Header) .OfType<TextBlock>() .Select(x => x.Text) .ToList(); } private IEnumerable<TreeViewItem> ExtractItemContent(IPanel panel, int currentLevel, int level) { foreach (TreeViewItem container in panel.Children) { if (container.Template == null) { container.Template = CreateTreeViewItemTemplate(); container.ApplyTemplate(); } if (currentLevel == level) { yield return container; } else { foreach (var child in ExtractItemContent(container.Presenter.Panel, currentLevel + 1, level)) { yield return child; } } } } private class Node : NotifyingBase { private IAvaloniaList<Node> _children; public string Value { get; set; } public IAvaloniaList<Node> Children { get { return _children; } set { _children = value; RaisePropertyChanged(nameof(Children)); } } } private class TestTreeDataTemplate : ITreeDataTemplate { public IControl Build(object param) { var node = (Node)param; return new TextBlock { Text = node.Value }; } public bool SupportsRecycling => false; public InstancedBinding ItemsSelector(object item) { var obs = new ExpressionObserver(item, nameof(Node.Children)); return new InstancedBinding(obs); } public bool Match(object data) { return data is Node; } } } }
/* * @author Valentin Simonov / http://va.lent.in/ */ using System; using System.Collections.Generic; using TouchScript.Utils; using TouchScript.Pointers; using UnityEngine; using UnityEngine.Profiling; namespace TouchScript.Gestures { /// <summary> /// Converts Pointer events for target object into separate events to be used somewhere else. /// </summary> [AddComponentMenu("TouchScript/Gestures/Meta Gesture")] [HelpURL("http://touchscript.github.io/docs/html/T_TouchScript_Gestures_MetaGesture.htm")] public sealed class MetaGesture : Gesture { #region Constants /// <summary> /// Message dispatched when a pointer begins. /// </summary> public const string POINTER_PRESSED_MESSAGE = "OnPointerPressed"; /// <summary> /// Message dispatched when a pointer moves. /// </summary> public const string POINTER_MOVED_MESSAGE = "OnPointerMoved"; /// <summary> /// Message dispatched when a pointer ends. /// </summary> public const string POINTER_RELEASED_MESSAGE = "OnPointerReleased"; /// <summary> /// Message dispatched when a pointer is cancelled. /// </summary> public const string POINTER_CANCELLED_MESSAGE = "OnPointerCancelled"; #endregion #region Events /// <summary> /// Occurs when a pointer is added. /// </summary> public event EventHandler<MetaGestureEventArgs> PointerPressed { add { pointerPressedInvoker += value; } remove { pointerPressedInvoker -= value; } } /// <summary> /// Occurs when a pointer is updated. /// </summary> public event EventHandler<MetaGestureEventArgs> PointerUpdated { add { pointerUpdatedInvoker += value; } remove { pointerUpdatedInvoker -= value; } } /// <summary> /// Occurs when a pointer is removed. /// </summary> public event EventHandler<MetaGestureEventArgs> PointerReleased { add { pointerReleasedInvoker += value; } remove { pointerReleasedInvoker -= value; } } /// <summary> /// Occurs when a pointer is cancelled. /// </summary> public event EventHandler<MetaGestureEventArgs> PointerCancelled { add { pointerCancelledInvoker += value; } remove { pointerCancelledInvoker -= value; } } // Needed to overcome iOS AOT limitations private EventHandler<MetaGestureEventArgs> pointerPressedInvoker, pointerUpdatedInvoker, pointerReleasedInvoker, pointerCancelledInvoker; #endregion #region Private variables private CustomSampler gestureSampler; #endregion #region Unity /// <inheritdoc /> protected override void Awake() { base.Awake(); gestureSampler = CustomSampler.Create("[TouchScript] Meta Gesture"); } [ContextMenu("Basic Editor")] private void switchToBasicEditor() { basicEditor = true; } #endregion #region Gesture callbacks /// <inheritdoc /> protected override void pointersPressed(IList<Pointer> pointers) { gestureSampler.Begin(); base.pointersPressed(pointers); if (State == GestureState.Idle) setState(GestureState.Began); var length = pointers.Count; if (pointerPressedInvoker != null) { for (var i = 0; i < length; i++) pointerPressedInvoker.InvokeHandleExceptions(this, new MetaGestureEventArgs(pointers[i])); } if (UseSendMessage && SendMessageTarget != null) { for (var i = 0; i < length; i++) SendMessageTarget.SendMessage(POINTER_PRESSED_MESSAGE, pointers[i], SendMessageOptions.DontRequireReceiver); } gestureSampler.End(); } /// <inheritdoc /> protected override void pointersUpdated(IList<Pointer> pointers) { gestureSampler.Begin(); base.pointersUpdated(pointers); if (State == GestureState.Began || State == GestureState.Changed) setState(GestureState.Changed); var length = pointers.Count; if (pointerUpdatedInvoker != null) { for (var i = 0; i < length; i++) pointerUpdatedInvoker.InvokeHandleExceptions(this, new MetaGestureEventArgs(pointers[i])); } if (UseSendMessage && SendMessageTarget != null) { for (var i = 0; i < length; i++) SendMessageTarget.SendMessage(POINTER_MOVED_MESSAGE, pointers[i], SendMessageOptions.DontRequireReceiver); } gestureSampler.End(); } /// <inheritdoc /> protected override void pointersReleased(IList<Pointer> pointers) { gestureSampler.Begin(); base.pointersReleased(pointers); if ((State == GestureState.Began || State == GestureState.Changed) && NumPointers == 0) setState(GestureState.Ended); var length = pointers.Count; if (pointerReleasedInvoker != null) { for (var i = 0; i < length; i++) pointerReleasedInvoker.InvokeHandleExceptions(this, new MetaGestureEventArgs(pointers[i])); } if (UseSendMessage && SendMessageTarget != null) { for (var i = 0; i < length; i++) SendMessageTarget.SendMessage(POINTER_RELEASED_MESSAGE, pointers[i], SendMessageOptions.DontRequireReceiver); } gestureSampler.End(); } /// <inheritdoc /> protected override void pointersCancelled(IList<Pointer> pointers) { gestureSampler.Begin(); base.pointersCancelled(pointers); var length = pointers.Count; if (pointerCancelledInvoker != null) { for (var i = 0; i < length; i++) pointerCancelledInvoker.InvokeHandleExceptions(this, new MetaGestureEventArgs(pointers[i])); } if (UseSendMessage && SendMessageTarget != null) { for (var i = 0; i < length; i++) SendMessageTarget.SendMessage(POINTER_CANCELLED_MESSAGE, pointers[i], SendMessageOptions.DontRequireReceiver); } gestureSampler.End(); } #endregion } /// <summary> /// EventArgs for MetaGesture events. /// </summary> public class MetaGestureEventArgs : EventArgs { /// <summary> /// Current pointer. /// </summary> public Pointer Pointer { get; private set; } /// <summary> /// Initializes a new instance of the <see cref="MetaGestureEventArgs"/> class. /// </summary> /// <param name="pointer"> Pointer the event is for. </param> public MetaGestureEventArgs(Pointer pointer) { Pointer = pointer; } } }
// 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; using System.Diagnostics; namespace System.Data.Common { internal sealed class NameValuePermission : IComparable { // reused as both key and value nodes // key nodes link to value nodes // value nodes link to key nodes private readonly string _value; // value node with (null != _restrictions) are allowed to match connection strings private DBConnectionString _entry; private NameValuePermission[] _tree; // with branches internal static readonly NameValuePermission Default = null; // = new NameValuePermission(String.Empty, new string[] { "File Name" }, KeyRestrictionBehavior.AllowOnly); internal NameValuePermission() { // root node } private NameValuePermission(string keyword) { _value = keyword; } private NameValuePermission(string value, DBConnectionString entry) { _value = value; _entry = entry; } private NameValuePermission(NameValuePermission permit) { // deep-copy _value = permit._value; _entry = permit._entry; _tree = permit._tree; if (null != _tree) { NameValuePermission[] tree = (_tree.Clone() as NameValuePermission[]); for (int i = 0; i < tree.Length; ++i) { if (null != tree[i]) { // WebData 98488 tree[i] = tree[i].CopyNameValue(); // deep copy } } _tree = tree; } } int IComparable.CompareTo(object a) { return StringComparer.Ordinal.Compare(_value, ((NameValuePermission)a)._value); } internal static void AddEntry(NameValuePermission kvtree, ArrayList entries, DBConnectionString entry) { Debug.Assert(null != entry, "null DBConnectionString"); if (null != entry.KeyChain) { for (NameValuePair keychain = entry.KeyChain; null != keychain; keychain = keychain.Next) { NameValuePermission kv; kv = kvtree.CheckKeyForValue(keychain.Name); if (null == kv) { kv = new NameValuePermission(keychain.Name); kvtree.Add(kv); // add directly into live tree } kvtree = kv; kv = kvtree.CheckKeyForValue(keychain.Value); if (null == kv) { DBConnectionString insertValue = ((null != keychain.Next) ? null : entry); kv = new NameValuePermission(keychain.Value, insertValue); kvtree.Add(kv); // add directly into live tree if (null != insertValue) { entries.Add(insertValue); } } else if (null == keychain.Next) { // shorter chain potential if (null != kv._entry) { Debug.Assert(entries.Contains(kv._entry), "entries doesn't contain entry"); entries.Remove(kv._entry); kv._entry = kv._entry.Intersect(entry); // union new restrictions into existing tree } else { kv._entry = entry; } entries.Add(kv._entry); } kvtree = kv; } } else { // global restrictions, MDAC 84443 DBConnectionString kentry = kvtree._entry; if (null != kentry) { Debug.Assert(entries.Contains(kentry), "entries doesn't contain entry"); entries.Remove(kentry); kvtree._entry = kentry.Intersect(entry); } else { kvtree._entry = entry; } entries.Add(kvtree._entry); } } internal void Intersect(ArrayList entries, NameValuePermission target) { if (null == target) { _tree = null; _entry = null; } else { if (null != _entry) { entries.Remove(_entry); _entry = _entry.Intersect(target._entry); entries.Add(_entry); } else if (null != target._entry) { _entry = target._entry.Intersect(null); entries.Add(_entry); } if (null != _tree) { int count = _tree.Length; for (int i = 0; i < _tree.Length; ++i) { NameValuePermission kvtree = target.CheckKeyForValue(_tree[i]._value); if (null != kvtree) { // does target tree contain our value _tree[i].Intersect(entries, kvtree); } else { _tree[i] = null; --count; } } if (0 == count) { _tree = null; } else if (count < _tree.Length) { NameValuePermission[] kvtree = new NameValuePermission[count]; for (int i = 0, j = 0; i < _tree.Length; ++i) { if (null != _tree[i]) { kvtree[j++] = _tree[i]; } } _tree = kvtree; } } } } private void Add(NameValuePermission permit) { NameValuePermission[] tree = _tree; int length = ((null != tree) ? tree.Length : 0); NameValuePermission[] newtree = new NameValuePermission[1 + length]; for (int i = 0; i < newtree.Length - 1; ++i) { newtree[i] = tree[i]; } newtree[length] = permit; Array.Sort(newtree); _tree = newtree; } internal bool CheckValueForKeyPermit(DBConnectionString parsetable) { if (null == parsetable) { return false; } bool hasMatch = false; NameValuePermission[] keytree = _tree; // _tree won't mutate but Add will replace it if (null != keytree) { hasMatch = parsetable.IsEmpty; // MDAC 86773 if (!hasMatch) { // which key do we follow the key-value chain on for (int i = 0; i < keytree.Length; ++i) { NameValuePermission permitKey = keytree[i]; if (null != permitKey) { string keyword = permitKey._value; #if DEBUG Debug.Assert(null == permitKey._entry, "key member has no restrictions"); #endif if (parsetable.ContainsKey(keyword)) { string valueInQuestion = (string)parsetable[keyword]; // keyword is restricted to certain values NameValuePermission permitValue = permitKey.CheckKeyForValue(valueInQuestion); if (null != permitValue) { //value does match - continue the chain down that branch if (permitValue.CheckValueForKeyPermit(parsetable)) { hasMatch = true; // adding a break statement is tempting, but wrong // user can safetly extend their restrictions for current rule to include missing keyword // i.e. Add("provider=sqloledb;integrated security=sspi", "data provider=", KeyRestrictionBehavior.AllowOnly); // i.e. Add("data provider=msdatashape;provider=sqloledb;integrated security=sspi", "", KeyRestrictionBehavior.AllowOnly); } else { // failed branch checking return false; } } else { // value doesn't match to expected values - fail here return false; } } } // else try next keyword } } // partial chain match, either leaf-node by shorter chain or fail mid-chain if (null == _restrictions) } DBConnectionString entry = _entry; if (null != entry) { // also checking !hasMatch is tempting, but wrong // user can safetly extend their restrictions for current rule to include missing keyword // i.e. Add("provider=sqloledb;integrated security=sspi", "data provider=", KeyRestrictionBehavior.AllowOnly); // i.e. Add("provider=sqloledb;", "integrated security=;", KeyRestrictionBehavior.AllowOnly); hasMatch = entry.IsSupersetOf(parsetable); } return hasMatch; // mid-chain failure } private NameValuePermission CheckKeyForValue(string keyInQuestion) { NameValuePermission[] valuetree = _tree; // _tree won't mutate but Add will replace it if (null != valuetree) { for (int i = 0; i < valuetree.Length; ++i) { NameValuePermission permitValue = valuetree[i]; if (string.Equals(keyInQuestion, permitValue._value, StringComparison.OrdinalIgnoreCase)) { return permitValue; } } } return null; } internal NameValuePermission CopyNameValue() { return new NameValuePermission(this); } } }
using System; using System.Linq; using System.Threading; using System.Threading.Tasks; using AutoFixture.NUnit3; using Moq; using NUnit.Framework; using ZptSharp.Expressions; namespace ZptSharp.Rendering { [TestFixture,Parallelizable] public class ExpressionContextIterativeProcessorTests { [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_process_the_specified_context([Frozen] IProcessesExpressionContext contextProcessor, ExpressionContext context, ExpressionContextIterativeProcessor sut) { await sut.IterateContextAndChildrenAsync(context); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(context, CancellationToken.None), Times.Once); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_process_child_contexts([Frozen] IProcessesExpressionContext contextProcessor, [Frozen] IGetsChildExpressionContexts childContextProvider, ExpressionContext context, ExpressionContext child1, ExpressionContext child2, ExpressionContextIterativeProcessor sut) { Mock.Get(childContextProvider) .Setup(x => x.GetChildContexts(context)) .Returns(new[] { child1, child2 }); await sut.IterateContextAndChildrenAsync(context); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(child1, CancellationToken.None), Times.Once, $"Processed {nameof(child1)}"); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(child2, CancellationToken.None), Times.Once, $"Processed {nameof(child2)}"); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_not_process_child_contexts_if_result_indicates_not_to([Frozen] IProcessesExpressionContext contextProcessor, [Frozen] IGetsChildExpressionContexts childContextProvider, ExpressionContext context, ExpressionContext child1, ExpressionContext child2, ExpressionContextIterativeProcessor sut) { Mock.Get(childContextProvider) .Setup(x => x.GetChildContexts(context)) .Returns(new[] { child1, child2 }); Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(context, CancellationToken.None)) .Returns(Task.FromResult(ExpressionContextProcessingResult.WithoutChildren)); await sut.IterateContextAndChildrenAsync(context); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(child1, CancellationToken.None), Times.Never, $"Does not process {nameof(child1)}"); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(child2, CancellationToken.None), Times.Never, $"Does not process {nameof(child2)}"); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_process_additional_contexts([Frozen] IProcessesExpressionContext contextProcessor, ExpressionContext context, ExpressionContext additional1, ExpressionContext additional2, ExpressionContextIterativeProcessor sut) { Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(context, CancellationToken.None)) .Returns(() => Task.FromResult(new ExpressionContextProcessingResult { AdditionalContexts = new[] { additional1, additional2 } })); await sut.IterateContextAndChildrenAsync(context); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(additional1, CancellationToken.None), Times.Once, $"Processed {nameof(additional1)}"); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(additional2, CancellationToken.None), Times.Once, $"Processed {nameof(additional2)}"); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_process_grandchild_contexts([Frozen] IProcessesExpressionContext contextProcessor, [Frozen] IGetsChildExpressionContexts childContextProvider, ExpressionContext context, ExpressionContext child, ExpressionContext grandchild1, ExpressionContext grandchild2, ExpressionContextIterativeProcessor sut) { Mock.Get(childContextProvider) .Setup(x => x.GetChildContexts(context)) .Returns(new[] { child }); Mock.Get(childContextProvider) .Setup(x => x.GetChildContexts(child)) .Returns(new[] { grandchild1, grandchild2 }); await sut.IterateContextAndChildrenAsync(context); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(grandchild1, CancellationToken.None), Times.Once, $"Processed {nameof(grandchild1)}"); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(grandchild2, CancellationToken.None), Times.Once, $"Processed {nameof(grandchild2)}"); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_process_additional_contexts_from_child_context([Frozen] IProcessesExpressionContext contextProcessor, [Frozen] IGetsChildExpressionContexts childContextProvider, ExpressionContext context, ExpressionContext child, ExpressionContext additional1, ExpressionContext additional2, ExpressionContextIterativeProcessor sut) { Mock.Get(childContextProvider) .Setup(x => x.GetChildContexts(context)) .Returns(new[] { child }); Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(child, CancellationToken.None)) .Returns(() => Task.FromResult(new ExpressionContextProcessingResult { AdditionalContexts = new[] { additional1, additional2 } })); await sut.IterateContextAndChildrenAsync(context); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(additional1, CancellationToken.None), Times.Once, $"Processed {nameof(additional1)}"); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(additional2, CancellationToken.None), Times.Once, $"Processed {nameof(additional2)}"); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_process_sibling_additional_contexts([Frozen] IProcessesExpressionContext contextProcessor, ExpressionContext context, ExpressionContext additional, ExpressionContext sibling1, ExpressionContext sibling2, ExpressionContextIterativeProcessor sut) { Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(context, CancellationToken.None)) .Returns(() => Task.FromResult(new ExpressionContextProcessingResult { AdditionalContexts = new[] { additional } })); Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(additional, CancellationToken.None)) .Returns(() => Task.FromResult(new ExpressionContextProcessingResult { AdditionalContexts = new[] { sibling1, sibling2 } })); await sut.IterateContextAndChildrenAsync(context); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(sibling1, CancellationToken.None), Times.Once, $"Processed {nameof(sibling1)}"); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(sibling2, CancellationToken.None), Times.Once, $"Processed {nameof(sibling2)}"); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_process_children_of_additional_context([Frozen] IProcessesExpressionContext contextProcessor, [Frozen] IGetsChildExpressionContexts childContextProvider, ExpressionContext context, ExpressionContext additional, ExpressionContext child1, ExpressionContext child2, ExpressionContextIterativeProcessor sut) { Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(context, CancellationToken.None)) .Returns(() => Task.FromResult(new ExpressionContextProcessingResult { AdditionalContexts = new[] { additional } })); Mock.Get(childContextProvider) .Setup(x => x.GetChildContexts(additional)) .Returns(new[] { child1, child2 }); await sut.IterateContextAndChildrenAsync(context); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(child1, CancellationToken.None), Times.Once, $"Processed {nameof(child1)}"); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(child2, CancellationToken.None), Times.Once, $"Processed {nameof(child1)}"); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_process_children_before_siblings(ExpressionContext context, ExpressionContext sibling1, ExpressionContext sibling2, ExpressionContext child1, ExpressionContext child2) { var contextProcessor = new Mock<IProcessesExpressionContext>(MockBehavior.Strict).Object; var childContextProvider = Mock.Of<IGetsChildExpressionContexts>(); var sut = new ExpressionContextIterativeProcessor(contextProcessor, childContextProvider); Mock.Get(childContextProvider) .Setup(x => x.GetChildContexts(context)) .Returns(new[] { sibling1, sibling2 }); Mock.Get(childContextProvider) .Setup(x => x.GetChildContexts(sibling1)) .Returns(new[] { child1, child2 }); var sequence = new MockSequence(); Mock.Get(contextProcessor) .InSequence(sequence) .Setup(x => x.ProcessContextAsync(context, CancellationToken.None)) .Returns(Task.FromResult(ExpressionContextProcessingResult.Noop)); Mock.Get(contextProcessor) .InSequence(sequence) .Setup(x => x.ProcessContextAsync(sibling1, CancellationToken.None)) .Returns(Task.FromResult(ExpressionContextProcessingResult.Noop)); Mock.Get(contextProcessor) .InSequence(sequence) .Setup(x => x.ProcessContextAsync(child1, CancellationToken.None)) .Returns(Task.FromResult(ExpressionContextProcessingResult.Noop)); Mock.Get(contextProcessor) .InSequence(sequence) .Setup(x => x.ProcessContextAsync(child2, CancellationToken.None)) .Returns(Task.FromResult(ExpressionContextProcessingResult.Noop)); Mock.Get(contextProcessor) .InSequence(sequence) .Setup(x => x.ProcessContextAsync(sibling2, CancellationToken.None)) .Returns(Task.FromResult(ExpressionContextProcessingResult.Noop)); await sut.IterateContextAndChildrenAsync(context); Mock.Get(contextProcessor) .Verify(x => x.ProcessContextAsync(sibling2, CancellationToken.None), Times.Once); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_add_processor_to_child_context_error_handler_stack_if_context_processor_is_error_handler(ExpressionContext context, ExpressionContext child1, ExpressionContext child2) { var contextProcessorMock = new Mock<IProcessesExpressionContext>(); contextProcessorMock.As<IHandlesProcessingError>(); var contextProcessor = contextProcessorMock.Object; var childContextProvider = Mock.Of<IGetsChildExpressionContexts>(); var sut = new ExpressionContextIterativeProcessor(contextProcessor, childContextProvider); child1.ErrorHandlers.Clear(); child2.ErrorHandlers.Clear(); Mock.Get(childContextProvider) .Setup(x => x.GetChildContexts(context)) .Returns(new[] { child1, child2 }); Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(It.IsAny<ExpressionContext>(), CancellationToken.None)) .Returns(Task.FromResult(ExpressionContextProcessingResult.Noop)); await sut.IterateContextAndChildrenAsync(context); Assert.That(child1.ErrorHandlers, Has.One.Matches<ErrorHandlingContext>(c => c.Handler == contextProcessor), "First child context has context processor added"); Assert.That(child2.ErrorHandlers, Has.One.Matches<ErrorHandlingContext>(c => c.Handler == contextProcessor), "Second child context has context processor added"); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_should_not_add_processor_to_child_context_error_handler_stack_if_not_an_error_handler(ExpressionContext context, ExpressionContext child1, ExpressionContext child2) { var contextProcessorMock = new Mock<IProcessesExpressionContext>(); var contextProcessor = contextProcessorMock.Object; var childContextProvider = Mock.Of<IGetsChildExpressionContexts>(); var sut = new ExpressionContextIterativeProcessor(contextProcessor, childContextProvider); child1.ErrorHandlers.Clear(); child2.ErrorHandlers.Clear(); Mock.Get(childContextProvider) .Setup(x => x.GetChildContexts(context)) .Returns(new[] { child1, child2 }); Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(It.IsAny<ExpressionContext>(), CancellationToken.None)) .Returns(Task.FromResult(ExpressionContextProcessingResult.Noop)); await sut.IterateContextAndChildrenAsync(context); Assert.That(child1.ErrorHandlers, Has.None.SameAs(contextProcessor), "First child context does not have context processor added"); Assert.That(child2.ErrorHandlers, Has.None.SameAs(contextProcessor), "Second child context does not have context processor added"); } [Test, AutoMoqData] public async Task IterateContextAndChildrenAsync_uses_error_handler_from_stack_to_handle_processing_error([Frozen] IProcessesExpressionContext contextProcessor, [Frozen] IGetsChildExpressionContexts childContextProvider, ExpressionContextIterativeProcessor sut, ExpressionContext context, [Frozen] IHandlesProcessingError handler, [Frozen] ExpressionContext handlerContext, ErrorHandlingContext errorHandler) { var exception = new Exception("Sample exception"); context.ErrorHandlers.Push(errorHandler); Mock.Get(handler) .Setup(x => x.HandleErrorAsync(exception, handlerContext, CancellationToken.None)) .Returns(() => Task.FromResult(ErrorHandlingResult.Success(ExpressionContextProcessingResult.Noop))); Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(context, CancellationToken.None)) .Throws(exception); await sut.IterateContextAndChildrenAsync(context); Mock.Get(handler) .Verify(x => x.HandleErrorAsync(exception, handlerContext, CancellationToken.None), Times.Once); } [Test, AutoMoqData] public void IterateContextAndChildrenAsync_throws_if_error_handler_from_stack_cannot_handle_processing_error([Frozen] IProcessesExpressionContext contextProcessor, [Frozen] IGetsChildExpressionContexts childContextProvider, ExpressionContextIterativeProcessor sut, ExpressionContext context, [Frozen] IHandlesProcessingError handler, [Frozen] ExpressionContext handlerContext, ErrorHandlingContext errorHandler) { var exception = new Exception("Sample exception"); context.ErrorHandlers.Push(errorHandler); Mock.Get(handler) .Setup(x => x.HandleErrorAsync(exception, handlerContext, CancellationToken.None)) .Returns(() => Task.FromResult(ErrorHandlingResult.Failure)); Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(context, CancellationToken.None)) .Throws(exception); Assert.That(async () => await sut.IterateContextAndChildrenAsync(context), Throws.Exception.Message.EqualTo("Sample exception")); } [Test, AutoMoqData] public void IterateContextAndChildrenAsync_throws_if_no_error_handlers_in_stack([Frozen] IProcessesExpressionContext contextProcessor, [Frozen] IGetsChildExpressionContexts childContextProvider, ExpressionContextIterativeProcessor sut, ExpressionContext context) { var exception = new Exception("Sample exception"); context.ErrorHandlers.Clear(); Mock.Get(contextProcessor) .Setup(x => x.ProcessContextAsync(context, CancellationToken.None)) .Throws(exception); Assert.That(async () => await sut.IterateContextAndChildrenAsync(context), Throws.Exception.Message.EqualTo("Sample exception")); } } }
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Runtime.InteropServices; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Formatting; using Microsoft.CodeAnalysis.Simplification; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Collections; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.InternalElements; using Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.Interop; using Microsoft.VisualStudio.LanguageServices.Implementation.ProjectSystem; using Microsoft.VisualStudio.LanguageServices.Implementation.Utilities; using Roslyn.Utilities; namespace Microsoft.VisualStudio.LanguageServices.Implementation.CodeModel { /// <summary> /// Implementations of EnvDTE.FileCodeModel for both languages. /// </summary> public sealed partial class FileCodeModel : AbstractCodeModelObject, EnvDTE.FileCodeModel, EnvDTE80.FileCodeModel2, ICodeElementContainer<AbstractCodeElement>, IVBFileCodeModelEvents, ICSCodeModelRefactoring { internal static ComHandle<EnvDTE80.FileCodeModel2, FileCodeModel> Create( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) { return new FileCodeModel(state, parent, documentId, textManagerAdapter).GetComHandle<EnvDTE80.FileCodeModel2, FileCodeModel>(); } private readonly ComHandle<object, object> _parentHandle; /// <summary> /// Don't use directly. Instead, call <see cref="GetDocumentId()"/>. /// </summary> private DocumentId _documentId; // Note: these are only valid when the underlying file is being renamed. Do not use. private ProjectId _incomingProjectId; private string _incomingFilePath; private Document _previousDocument; private readonly ITextManagerAdapter _textManagerAdapter; private readonly ElementTable _elementTable; // These are used during batching. private bool _batchMode; private List<AbstractKeyedCodeElement> _batchElements; private Document _batchDocument; // track state to make sure we open editor only once private int _editCount; private IInvisibleEditor _invisibleEditor; private SyntaxTree _lastSyntaxTree; private FileCodeModel( CodeModelState state, object parent, DocumentId documentId, ITextManagerAdapter textManagerAdapter) : base(state) { Debug.Assert(documentId != null); Debug.Assert(textManagerAdapter != null); _parentHandle = new ComHandle<object, object>(parent); _documentId = documentId; _textManagerAdapter = textManagerAdapter; _elementTable = new ElementTable(); _batchMode = false; _batchDocument = null; _lastSyntaxTree = GetSyntaxTree(); } internal ITextManagerAdapter TextManagerAdapter { get { return _textManagerAdapter; } } /// <summary> /// Internally, we store the DocumentId for the document that the FileCodeModel represents. If the underlying file /// is renamed, the DocumentId will become invalid because the Roslyn VS workspace treats file renames as a remove/add pair. /// To work around this, the FileCodeModel is notified when a file rename is about to occur. At that point, the /// <see cref="_documentId"/> field is null'd out and <see cref="_incomingFilePath"/> is set to the name of the new file. /// The next time that a FileCodeModel operation occurs that requires the DocumentId, it will be retrieved from the workspace /// using the <see cref="_incomingFilePath"/>. /// </summary> internal void OnRename(string newFilePath) { Debug.Assert(_editCount == 0, "FileCodeModel have an open edit and the underlying file is being renamed. This is a bug."); if (_documentId != null) { _previousDocument = Workspace.CurrentSolution.GetDocument(_documentId); } _incomingFilePath = newFilePath; _incomingProjectId = _documentId.ProjectId; _documentId = null; } internal override void Shutdown() { if (_invisibleEditor != null) { // we are shutting down, so do not worry about editCount. If the editor is still alive, dispose it. CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); _invisibleEditor.Dispose(); _invisibleEditor = null; } base.Shutdown(); } private bool TryGetDocumentId(out DocumentId documentId) { if (_documentId != null) { documentId = _documentId; return true; } documentId = null; // We don't have DocumentId, so try to retrieve it from the workspace. if (_incomingProjectId == null || _incomingFilePath == null) { return false; } var project = ((VisualStudioWorkspaceImpl)this.State.Workspace).ProjectTracker.GetProject(_incomingProjectId); if (project == null) { return false; } var hostDocument = project.GetCurrentDocumentFromPath(_incomingFilePath); if (hostDocument == null) { return false; } _documentId = hostDocument.Id; _incomingProjectId = null; _incomingFilePath = null; _previousDocument = null; documentId = _documentId; return true; } internal DocumentId GetDocumentId() { if (_documentId != null) { return _documentId; } DocumentId documentId; if (TryGetDocumentId(out documentId)) { return documentId; } throw Exceptions.ThrowEUnexpected(); } private void AddElement(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element) { _elementTable.Add(nodeKey, element); } private void RemoveElement(SyntaxNodeKey nodeKey) { _elementTable.Remove(nodeKey); } /// <summary> /// This function re-adds a code element to the table, taking care not to duplicate /// an element (i.e., making sure that no two elements with the same key-ordinal /// appear in the same element chain in the table). To resolve any conflict, each /// node with the given key is examined positionally, and the existing order is /// maintained as closely as possible -- but it is still possible the code element /// references to duplicate elements can get "bumped" by odd edits -- nothing we /// can do about this. /// </summary> internal void ResetElementNodeKey(AbstractKeyedCodeElement element, SyntaxNodeKey nodeKey) { EnvDTE.CodeElement elementInTable; _elementTable.Remove(element.NodeKey, out elementInTable); var abstractElementInTable = ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(elementInTable); if (!object.Equals(abstractElementInTable, element)) { Debug.Fail("Found a different element with the same key!"); throw new InvalidOperationException(); } abstractElementInTable.NodeKey = nodeKey; _elementTable.Add(nodeKey, elementInTable); } internal void OnElementCreated(SyntaxNodeKey nodeKey, EnvDTE.CodeElement element) { AddElement(nodeKey, element); } internal T CreateCodeElement<T>(SyntaxNode node) { var nodeKey = CodeModelService.TryGetNodeKey(node); if (!nodeKey.IsEmpty) { // Check if the node exists in the parse tree. // Note that in designer spew the nodes don't get created right away so we skip this check. if (!IsBatchOpen && CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) == null) { throw Exceptions.ThrowEFail(); } // See if the element exists. var previousElement = _elementTable.TryGetValue(nodeKey); // Here's our element... possibly. It must be valid -- if it isn't, // we need to remove it. if (previousElement != null) { var previousElementImpl = ComAggregate.TryGetManagedObject<AbstractCodeElement>(previousElement); if (previousElementImpl.IsValidNode()) { if (previousElement is T) { return (T)previousElement; } else { Debug.Fail("Called asked for the wrong type!"); throw new InvalidOperationException(); } } else { // This guy is no longer valid, so yank it out. No sense // continuing to look for a match, either. RemoveElement(nodeKey); } } } return (T)CodeModelService.CreateInternalCodeElement(this.State, this, node); } private void InitializeEditor() { _editCount++; if (_editCount == 1) { Debug.Assert(_invisibleEditor == null); _invisibleEditor = Workspace.OpenInvisibleEditor(GetDocumentId()); CodeModelService.AttachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); } } private void ReleaseEditor() { Debug.Assert(_editCount >= 1); _editCount--; if (_editCount == 0) { Debug.Assert(_invisibleEditor != null); CodeModelService.DetachFormatTrackingToBuffer(_invisibleEditor.TextBuffer); _invisibleEditor.Dispose(); _invisibleEditor = null; } } internal void EnsureEditor(Action action) { InitializeEditor(); try { action(); } finally { ReleaseEditor(); } } internal T EnsureEditor<T>(Func<T> action) { InitializeEditor(); try { return action(); } finally { ReleaseEditor(); } } internal void PerformEdit(Func<Document, Document> action) { EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); var formatted = Formatter.FormatAsync(result, Formatter.Annotation).WaitAndGetResult(CancellationToken.None); formatted = Formatter.FormatAsync(formatted, SyntaxAnnotation.ElasticAnnotation).WaitAndGetResult(CancellationToken.None); ApplyChanges(workspace, formatted); }); } internal T PerformEdit<T>(Func<Document, Tuple<T, Document>> action) where T : SyntaxNode { return EnsureEditor(() => { Debug.Assert(_invisibleEditor != null); var document = GetDocument(); var workspace = document.Project.Solution.Workspace; var result = action(document); ApplyChanges(workspace, result.Item2); return result.Item1; }); } private void ApplyChanges(Workspace workspace, Document document) { if (IsBatchOpen) { _batchDocument = document; } else { workspace.TryApplyChanges(document.Project.Solution); } } internal Document GetDocument() { Document document; if (!TryGetDocument(out document)) { throw Exceptions.ThrowEFail(); } return document; } internal bool TryGetDocument(out Document document) { if (IsBatchOpen && _batchDocument != null) { document = _batchDocument; return true; } DocumentId documentId; if (!TryGetDocumentId(out documentId) && _previousDocument != null) { document = _previousDocument; } else { document = Workspace.CurrentSolution.GetDocument(GetDocumentId()); } return document != null; } internal SyntaxTree GetSyntaxTree() { return GetDocument() .GetSyntaxTreeAsync(CancellationToken.None) .WaitAndGetResult(CancellationToken.None); } internal SyntaxNode GetSyntaxRoot() { return GetDocument() .GetSyntaxRootAsync(CancellationToken.None) .WaitAndGetResult(CancellationToken.None); } internal SemanticModel GetSemanticModel() { return GetDocument() .GetSemanticModelAsync(CancellationToken.None) .WaitAndGetResult(CancellationToken.None); } internal Compilation GetCompilation() { return GetDocument().Project .GetCompilationAsync(CancellationToken.None) .WaitAndGetResult(CancellationToken.None); } internal ProjectId GetProjectId() { return GetDocumentId().ProjectId; } internal AbstractProject GetAbstractProject() { return ((VisualStudioWorkspaceImpl)Workspace).ProjectTracker.GetProject(GetProjectId()); } internal SyntaxNode LookupNode(SyntaxNodeKey nodeKey) { return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()); } internal TSyntaxNode LookupNode<TSyntaxNode>(SyntaxNodeKey nodeKey) where TSyntaxNode : SyntaxNode { return CodeModelService.LookupNode(nodeKey, GetSyntaxTree()) as TSyntaxNode; } public EnvDTE.CodeAttribute AddAttribute(string name, string value, object position) { return EnsureEditor(() => { return AddAttribute(GetSyntaxRoot(), name, value, position, target: CodeModelService.AssemblyAttributeString); }); } public EnvDTE.CodeClass AddClass(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddClass(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeDelegate AddDelegate(string name, object type, object position, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddDelegate(GetSyntaxRoot(), name, type, position, access); }); } public EnvDTE.CodeEnum AddEnum(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddEnum(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeFunction AddFunction(string name, EnvDTE.vsCMFunction kind, object type, object position, EnvDTE.vsCMAccess access) { throw Exceptions.ThrowEFail(); } public EnvDTE80.CodeImport AddImport(string name, object position, string alias) { return EnsureEditor(() => { return AddImport(GetSyntaxRoot(), name, position, alias); }); } public EnvDTE.CodeInterface AddInterface(string name, object position, object bases, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddInterface(GetSyntaxRoot(), name, position, bases, access); }); } public EnvDTE.CodeNamespace AddNamespace(string name, object position) { return EnsureEditor(() => { return AddNamespace(GetSyntaxRoot(), name, position); }); } public EnvDTE.CodeStruct AddStruct(string name, object position, object bases, object implementedInterfaces, EnvDTE.vsCMAccess access) { return EnsureEditor(() => { return AddStruct(GetSyntaxRoot(), name, position, bases, implementedInterfaces, access); }); } public EnvDTE.CodeVariable AddVariable(string name, object type, object position, EnvDTE.vsCMAccess access) { throw Exceptions.ThrowEFail(); } public EnvDTE.CodeElement CodeElementFromPoint(EnvDTE.TextPoint point, EnvDTE.vsCMElement scope) { // Can't use point.AbsoluteCharOffset because it's calculated by the native // implementation in GetAbsoluteOffset (in env\msenv\textmgr\autoutil.cpp) // to only count each newline as a single character. We need to ask for line and // column and calculate the right offset ourselves. See DevDiv2 530496 for details. var position = GetPositionFromTextPoint(point); var result = CodeElementFromPosition(position, scope); if (result == null) { throw Exceptions.ThrowEFail(); } return result; } private int GetPositionFromTextPoint(EnvDTE.TextPoint point) { var lineNumber = point.Line - 1; var column = point.LineCharOffset - 1; var line = GetDocument().GetTextAsync(CancellationToken.None).WaitAndGetResult(CancellationToken.None).Lines[lineNumber]; var position = line.Start + column; return position; } internal EnvDTE.CodeElement CodeElementFromPosition(int position, EnvDTE.vsCMElement scope) { var root = GetSyntaxRoot(); var leftToken = SyntaxFactsService.FindTokenOnLeftOfPosition(root, position); var rightToken = SyntaxFactsService.FindTokenOnRightOfPosition(root, position); // We apply a set of heuristics to determine which member we pick to start searching. var token = leftToken; if (leftToken != rightToken) { if (leftToken.Span.End == position && rightToken.SpanStart == position) { // If both tokens are touching, we prefer identifiers and keywords to // separators. Note that the language doesn't allow both tokens to be a // keyword or identifier. if (SyntaxFactsService.IsKeyword(rightToken) || SyntaxFactsService.IsIdentifier(rightToken)) { token = rightToken; } } else if (leftToken.Span.End < position && rightToken.SpanStart <= position) { // If only the right token is touching, we have to use it. token = rightToken; } } // If we ended up using the left token but the position is after that token, // walk up to the first node who's last token is not the leftToken. By doing this, we // ensure that we don't find members when the position is actually between them. // In that case, we should find the enclosing type or namespace. var parent = token.Parent; if (token == leftToken && position > token.Span.End) { while (parent != null) { if (parent.GetLastToken() == token) { parent = parent.Parent; } else { break; } } } var node = parent != null ? parent.AncestorsAndSelf().FirstOrDefault(n => CodeModelService.MatchesScope(n, scope)) : null; if (node == null) { return null; } if (scope == EnvDTE.vsCMElement.vsCMElementAttribute || scope == EnvDTE.vsCMElement.vsCMElementImportStmt || scope == EnvDTE.vsCMElement.vsCMElementParameter || scope == EnvDTE.vsCMElement.vsCMElementOptionStmt || scope == EnvDTE.vsCMElement.vsCMElementInheritsStmt || scope == EnvDTE.vsCMElement.vsCMElementImplementsStmt || (scope == EnvDTE.vsCMElement.vsCMElementFunction && CodeModelService.IsAccessorNode(node))) { // Attributes, imports, parameters, Option, Inherits and Implements // don't have node keys of their own and won't be included in our // collection of elements. Delegate to the service to create these. return CodeModelService.CreateInternalCodeElement(State, this, node); } return CreateCodeElement<EnvDTE.CodeElement>(node); } public EnvDTE.CodeElements CodeElements { get { return NamespaceCollection.Create(this.State, this, this, SyntaxNodeKey.Empty); } } public EnvDTE.ProjectItem Parent { get { return _parentHandle.Object as EnvDTE.ProjectItem; } } public void Remove(object element) { var codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(element); if (codeElement == null) { codeElement = ComAggregate.TryGetManagedObject<AbstractCodeElement>(this.CodeElements.Item(element)); } if (codeElement == null) { throw new ArgumentException(ServicesVSResources.ElementIsNotValid, "element"); } codeElement.Delete(); } int IVBFileCodeModelEvents.StartEdit() { try { InitializeEditor(); if (_editCount == 1) { _batchMode = true; _batchElements = new List<AbstractKeyedCodeElement>(); } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } } int IVBFileCodeModelEvents.EndEdit() { try { if (_editCount == 1) { List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>> elementAndPathes = null; if (_batchElements.Count > 0) { foreach (var element in _batchElements) { var node = element.LookupNode(); if (node != null) { elementAndPathes = elementAndPathes ?? new List<ValueTuple<AbstractKeyedCodeElement, SyntaxPath>>(); elementAndPathes.Add(ValueTuple.Create(element, new SyntaxPath(node))); } } } if (_batchDocument != null) { // perform expensive operations at once var newDocument = Simplifier.ReduceAsync(_batchDocument, Simplifier.Annotation, cancellationToken: CancellationToken.None).WaitAndGetResult(CancellationToken.None); _batchDocument.Project.Solution.Workspace.TryApplyChanges(newDocument.Project.Solution); // done using batch document _batchDocument = null; } // Ensure the file is prettylisted, even if we didn't make any edits CodeModelService.EnsureBufferFormatted(_invisibleEditor.TextBuffer); if (elementAndPathes != null) { foreach (var elementAndPath in elementAndPathes) { // make sure the element is there. var existingElement = _elementTable.TryGetValue(elementAndPath.Item1.NodeKey); if (existingElement != null) { elementAndPath.Item1.ReacquireNodeKey(elementAndPath.Item2, CancellationToken.None); } // make sure existing element doesn't go away (weak reference) in the middle of // updating the node key GC.KeepAlive(existingElement); } } _batchMode = false; _batchElements = null; } return VSConstants.S_OK; } catch (Exception ex) { return Marshal.GetHRForException(ex); } finally { ReleaseEditor(); } } public void BeginBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.StartEdit()); } public void EndBatch() { IVBFileCodeModelEvents temp = this; ErrorHandler.ThrowOnFailure(temp.EndEdit()); } public bool IsBatchOpen { get { return _batchMode && _editCount > 0; } } public EnvDTE.CodeElement ElementFromID(string id) { throw new NotImplementedException(); } public EnvDTE80.vsCMParseStatus ParseStatus { get { var syntaxTree = GetSyntaxTree(); return syntaxTree.GetDiagnostics().Any(d => d.Severity == DiagnosticSeverity.Error) ? EnvDTE80.vsCMParseStatus.vsCMParseStatusError : EnvDTE80.vsCMParseStatus.vsCMParseStatusComplete; } } public void Synchronize() { FireEvents(); } EnvDTE.CodeElements ICodeElementContainer<AbstractCodeElement>.GetCollection() { return CodeElements; } internal List<GlobalNodeKey> GetCurrentNodeKeys() { var currentNodeKeys = new List<GlobalNodeKey>(); foreach (var element in _elementTable) { var keyedElement = ComAggregate.TryGetManagedObject<AbstractKeyedCodeElement>(element); if (keyedElement == null) { continue; } SyntaxNode node; if (keyedElement.TryLookupNode(out node)) { var nodeKey = keyedElement.NodeKey; currentNodeKeys.Add(new GlobalNodeKey(nodeKey, new Roslyn.Utilities.SyntaxPath(node))); } } return currentNodeKeys; } internal void ResetElementKeys(List<GlobalNodeKey> globalNodeKeys) { foreach (var globalNodeKey in globalNodeKeys) { ResetElementKey(globalNodeKey); } } private void ResetElementKey(GlobalNodeKey globalNodeKey) { var element = _elementTable.TryGetValue(globalNodeKey.NodeKey); // Failure to find the element is not an error -- it just means the code // element didn't exist... if (element != null) { ComAggregate.GetManagedObject<AbstractKeyedCodeElement>(element).ReacquireNodeKey(globalNodeKey.Path, default(CancellationToken)); } } } }
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. /*============================================================ ** ** Purpose: Resource annotation rules. ** ===========================================================*/ using System; using System.Diagnostics; using System.Globalization; using System.Runtime.CompilerServices; using System.Text; using Microsoft.Win32; using System.Diagnostics.Contracts; namespace System.Runtime.Versioning { [AttributeUsage(AttributeTargets.Method | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)] [Conditional("RESOURCE_ANNOTATION_WORK")] public sealed class ResourceConsumptionAttribute : Attribute { private ResourceScope _consumptionScope; private ResourceScope _resourceScope; public ResourceConsumptionAttribute(ResourceScope resourceScope) { _resourceScope = resourceScope; _consumptionScope = _resourceScope; } public ResourceConsumptionAttribute(ResourceScope resourceScope, ResourceScope consumptionScope) { _resourceScope = resourceScope; _consumptionScope = consumptionScope; } public ResourceScope ResourceScope { get { return _resourceScope; } } public ResourceScope ConsumptionScope { get { return _consumptionScope; } } } [AttributeUsage(AttributeTargets.Method | AttributeTargets.Field | AttributeTargets.Property | AttributeTargets.Constructor, Inherited = false)] [Conditional("RESOURCE_ANNOTATION_WORK")] public sealed class ResourceExposureAttribute : Attribute { private ResourceScope _resourceExposureLevel; public ResourceExposureAttribute(ResourceScope exposureLevel) { _resourceExposureLevel = exposureLevel; } public ResourceScope ResourceExposureLevel { get { return _resourceExposureLevel; } } } // Default visibility is Public, which isn't specified in this enum. // Public == the lack of Private or Assembly // Does this actually work? Need to investigate that. [Flags] public enum ResourceScope { None = 0, // Resource type Machine = 0x1, Process = 0x2, AppDomain = 0x4, Library = 0x8, // Visibility Private = 0x10, // Private to this one class. Assembly = 0x20, // Assembly-level, like C#'s "internal" } [Flags] internal enum SxSRequirements { None = 0, AppDomainID = 0x1, ProcessID = 0x2, CLRInstanceID = 0x4, // for multiple CLR's within the process AssemblyName = 0x8, TypeName = 0x10 } public static class VersioningHelper { // These depend on the exact values given to members of the ResourceScope enum. private const ResourceScope ResTypeMask = ResourceScope.Machine | ResourceScope.Process | ResourceScope.AppDomain | ResourceScope.Library; private const ResourceScope VisibilityMask = ResourceScope.Private | ResourceScope.Assembly; [System.Security.SecuritySafeCritical] [MethodImpl(MethodImplOptions.InternalCall)] private static extern int GetRuntimeId(); public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to) { return MakeVersionSafeName(name, from, to, null); } [System.Security.SecuritySafeCritical] // auto-generated public static String MakeVersionSafeName(String name, ResourceScope from, ResourceScope to, Type type) { ResourceScope fromResType = from & ResTypeMask; ResourceScope toResType = to & ResTypeMask; if (fromResType > toResType) throw new ArgumentException(Environment.GetResourceString("Argument_ResourceScopeWrongDirection", fromResType, toResType), "from"); SxSRequirements requires = GetRequirements(to, from); if ((requires & (SxSRequirements.AssemblyName | SxSRequirements.TypeName)) != 0 && type == null) throw new ArgumentNullException("type", Environment.GetResourceString("ArgumentNull_TypeRequiredByResourceScope")); // Add in process ID, CLR base address, and appdomain ID's. Also, use a character identifier // to ensure that these can never accidentally overlap (ie, you create enough appdomains and your // appdomain ID might equal your process ID). StringBuilder safeName = new StringBuilder(name); char separator = '_'; if ((requires & SxSRequirements.ProcessID) != 0) { safeName.Append(separator); safeName.Append('p'); safeName.Append(Win32Native.GetCurrentProcessId()); } if ((requires & SxSRequirements.CLRInstanceID) != 0) { String clrID = GetCLRInstanceString(); safeName.Append(separator); safeName.Append('r'); safeName.Append(clrID); } if ((requires & SxSRequirements.AppDomainID) != 0) { safeName.Append(separator); safeName.Append("ad"); safeName.Append(AppDomain.CurrentDomain.Id); } if ((requires & SxSRequirements.TypeName) != 0) { safeName.Append(separator); safeName.Append(type.Name); } if ((requires & SxSRequirements.AssemblyName) != 0) { safeName.Append(separator); safeName.Append(type.Assembly.FullName); } return safeName.ToString(); } private static String GetCLRInstanceString() { int id = GetRuntimeId(); return id.ToString(CultureInfo.InvariantCulture); } private static SxSRequirements GetRequirements(ResourceScope consumeAsScope, ResourceScope calleeScope) { SxSRequirements requires = SxSRequirements.None; switch(calleeScope & ResTypeMask) { case ResourceScope.Machine: switch(consumeAsScope & ResTypeMask) { case ResourceScope.Machine: // No work break; case ResourceScope.Process: requires |= SxSRequirements.ProcessID; break; case ResourceScope.AppDomain: requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID | SxSRequirements.ProcessID; break; default: throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", consumeAsScope), "consumeAsScope"); } break; case ResourceScope.Process: if ((consumeAsScope & ResourceScope.AppDomain) != 0) requires |= SxSRequirements.AppDomainID | SxSRequirements.CLRInstanceID; break; case ResourceScope.AppDomain: // No work break; default: throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeTypeBits", calleeScope), "calleeScope"); } switch(calleeScope & VisibilityMask) { case ResourceScope.None: // Public - implied switch(consumeAsScope & VisibilityMask) { case ResourceScope.None: // Public - implied // No work break; case ResourceScope.Assembly: requires |= SxSRequirements.AssemblyName; break; case ResourceScope.Private: requires |= SxSRequirements.TypeName | SxSRequirements.AssemblyName; break; default: throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", consumeAsScope), "consumeAsScope"); } break; case ResourceScope.Assembly: if ((consumeAsScope & ResourceScope.Private) != 0) requires |= SxSRequirements.TypeName; break; case ResourceScope.Private: // No work break; default: throw new ArgumentException(Environment.GetResourceString("Argument_BadResourceScopeVisibilityBits", calleeScope), "calleeScope"); } if (consumeAsScope == calleeScope) { Contract.Assert(requires == SxSRequirements.None, "Computed a strange set of required resource scoping. It's probably wrong."); } return requires; } } }
using System; using System.Collections.Generic; using Newtonsoft.Json; using QBankApi.Model; using QBankApi.Serializers; using RestSharp; using RestSharp.Authenticators; using System.IO; namespace QBankApi.Controller { public class MediaController : ControllerAbstract { public MediaController(CachePolicy cachePolicy, string apiAddress, IAuthenticator authenticator) : base( cachePolicy, apiAddress, authenticator) { } public MediaController(CachePolicy cachePolicy, RestClient client) : base(cachePolicy, client) { } /// <summary> /// Fetches a specific Media. /// <param name="id">The Media identifier.</param> /// </summary> public MediaResponse RetrieveMedia( int id, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}", Method.GET); request.Parameters.Clear(); return Execute<MediaResponse>(request, cachePolicy); } /// <summary> /// Gets the raw file data of a Media. /// /// You may append an optional template parameter to the query. Omitting the template parameter will return the medium thumbnail. /// /// Existing templates are: /// <b>original</b> - The original file /// <b>preview</b> - A preview image, sized 1000px on the long side /// <b>thumb_small</b> - A thumbnail image, sized 100px on the long side /// <b>thumb_medium</b> - A thumbnail image, sized 200px on the long side /// <b>thumb_large</b> - A thumbnail image, sized 300px on the long side /// <b>videopreview</b> - A preview video, sized 360p and maximum 2min /// <b>{integer}</b> - An image template identifier (NOTE: You can only request templates that are available on the server, eg. a media that have been published using COPY or SYMLINK-protocols) /// <param name="writer">Stream to write file to</param> /// <param name="id">The Media identifier..</param> /// <param name="template">Optional template of Media..</param> /// </summary> public void RetrieveFileData( Stream writer, int id, string template = null, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}/asset"); request.AddParameter("template", template, ParameterType.QueryString); request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer); Client.DownloadData(request); } /// <summary> /// Fetches all DeployedFiles a Media has. /// <param name="id">The Media identifier..</param> /// <param name="media">[DEPRECATED] Internal use only.</param> /// </summary> public List<DeploymentFile> ListDeployedFiles( int id, Media media = null, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}/deployment/files", Method.GET); request.Parameters.Clear(); request.AddParameter("media", media, ParameterType.QueryString); return Execute<List<DeploymentFile>>(request, cachePolicy); } /// <summary> /// Fetches all DeploymentSites a Media is deployed to. /// <param name="id">The Media identifier..</param> /// </summary> public List<DeploymentSiteResponse> ListDeploymentSites( int id, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}/deployment/sites", Method.GET); request.Parameters.Clear(); return Execute<List<DeploymentSiteResponse>>(request, cachePolicy); } /// <summary> /// Downloads a specific Media. /// /// You may append an optional template parameter to the query. Omitting the template parameter will return the original file. /// <param name="writer">Stream to write file to</param> /// <param name="id">The Media identifier.</param> /// <param name="template">Optional template to download the media in (NOTE: This should not be used for fetching images often, use very sparingly and consider using publish-sites and templates instead).</param> /// <param name="templateType">Indicates type of template, valid values are; image, video.</param> /// </summary> public void Download( Stream writer, int id, string template = null, string templateType = "image", CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}/download"); request.AddParameter("template", template, ParameterType.QueryString); request.AddParameter("templateType", templateType, ParameterType.QueryString); request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer); Client.DownloadData(request); } /// <summary> /// Fetches all Folders a Media resides in. /// <param name="id">The Media identifier..</param> /// <param name="depth">The depth for which to include existing subfolders. Use zero to exclude them all toghether..</param> /// </summary> public List<FolderResponse> ListFolders( int id, int depth = 0, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}/folders", Method.GET); request.Parameters.Clear(); request.AddParameter("depth", depth, ParameterType.QueryString); return Execute<List<FolderResponse>>(request, cachePolicy); } /// <summary> /// Fetches all Moodboards a Media is a member of. /// <param name="id">The Media identifier..</param> /// </summary> public List<MoodboardResponse> ListMoodboards( int id, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}/moodboards", Method.GET); request.Parameters.Clear(); return Execute<List<MoodboardResponse>>(request, cachePolicy); } /// <summary> /// Fetches all links to SocialMedia that a Media has. /// /// Fetches all DeployedFiles a Media has. /// <param name="id">The Media identifier..</param> /// </summary> public List<DeploymentFile> ListSocialMediaFiles( int id, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}/socialmedia/files", Method.GET); request.Parameters.Clear(); return Execute<List<DeploymentFile>>(request, cachePolicy); } /// <summary> /// Fetches all SocialMedia sites a Media is published to. /// <param name="id">The Media identifier..</param> /// </summary> public List<SocialMedia> ListSocialMedia( int id, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}/socialmedia/sites", Method.GET); request.Parameters.Clear(); return Execute<List<SocialMedia>>(request, cachePolicy); } /// <summary> /// Fetches all External Usages for a Media. /// <param name="id">The Media identifier..</param> /// </summary> public List<MediaUsageResponse> ListUsages( int id, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}/usages", Method.GET); request.Parameters.Clear(); return Execute<List<MediaUsageResponse>>(request, cachePolicy); } /// <summary> /// Fetches the version list of a media. /// /// The id may be of any media version in the list; first, somewhere in between or last. /// <param name="id">The Media identifier..</param> /// </summary> public List<MediaVersion> ListVersions( int id, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{id}/versions", Method.GET); request.Parameters.Clear(); return Execute<List<MediaVersion>>(request, cachePolicy); } /// <summary> /// Fetches eventual comments made on this media /// <param name="mediaId">The Media identifier..</param> /// </summary> public List<CommentResponse> ListComments( int mediaId, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/{mediaId}/comments", Method.GET); request.Parameters.Clear(); return Execute<List<CommentResponse>>(request, cachePolicy); } /// <summary> /// Downloads an archive of several Media /// /// . You may append an optional template parameter to the query. Omitting the template parameter will return the original files. /// <param name="writer">Stream to write file to</param> /// <param name="ids">Array of Media ID:s to download.</param> /// <param name="template">Optional template to download all Media in..</param> /// </summary> public void DownloadArchive( Stream writer, List<int> ids, string template = null, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/download"); request.AddParameter("ids", ids, ParameterType.QueryString); request.AddParameter("template", template, ParameterType.QueryString); request.ResponseWriter = (responseStream) => responseStream.CopyTo(writer); Client.DownloadData(request); } /// <summary> /// Publishes an archive of several Media. /// /// Publishes an archive of several Media to a deploymentssite by supplying either a list of mediaIds or objectIds and a deployment site id. /// <param name="idType">Type of ID, Object or Media, sending ObjectId will automatically use the latest version of a Object..</param> /// <param name="ids">A comma-separated list of IDs to zip and publish.</param> /// <param name="deploymentSiteId">The site to publish the archive to.</param> /// <param name="filename">Optional filename for the zip-archive, a filename will automatically be generated if omitted..</param> /// </summary> public object PublishArchive( string idType, string ids, int deploymentSiteId, string filename = null, CachePolicy cachePolicy = null) { var request = new RestRequest($"v1/media/publishArchive", Method.GET); request.Parameters.Clear(); request.AddParameter("idType", idType, ParameterType.QueryString); request.AddParameter("ids", ids, ParameterType.QueryString); request.AddParameter("deploymentSiteId", deploymentSiteId, ParameterType.QueryString); request.AddParameter("filename", filename, ParameterType.QueryString); return Execute<object>(request, cachePolicy); } /// <summary> /// Upload a new media to QBank /// /// This upload endpoint has been specifically tailored to fit chunked uploading (works well with Plupload2 for example). Max chunk size is about 10mb, if your files are larger than this, split it up and set correct chunk and chunks argument in the call. /// For example a 26mb file might be split in 3 chunks, so the following 3 calls should be made /// POST /media.json?chunks=3&chunk=0&filename=largefile.txt&categoryId=1 (file data is sent in body) /// POST /media.json?chunks=3&chunk=1&filename=largefile.txt&categoryId=1&fileId=<fileId from first call> (file data is sent in body) /// POST /media.json?chunks=3&chunk=2&filename=largefile.txt&categoryId=1&fileId=<fileId from first call> (file data is sent in body) /// /// <param name="name">Filename of the file being uploaded</param> /// <param name="chunk">The chunk we are currently uploading, starts at 0</param> /// <param name="chunks">Number of chunks you will be uploading, when (chunk - 1) == chunks the file will be considered uploaded</param> /// <param name="fileId">A unique fileId that will be used for this upload, if none is given one will be given to you</param> /// <param name="categoryId">The category to place the file in</param> /// </summary> public Dictionary<string, object> UploadFileChunked( string name, int chunk, int chunks, string fileId, int categoryId) { var request = new RestRequest($"v1/media", Method.POST); request.Parameters.Clear(); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(name), ParameterType.RequestBody); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(chunk), ParameterType.RequestBody); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(chunks), ParameterType.RequestBody); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(fileId), ParameterType.RequestBody); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(categoryId), ParameterType.RequestBody); return Execute<Dictionary<string, object>>(request); } /// <summary> /// Update a specific Media. /// /// Note that type_id cannot be set directly, but must be decided by the category. The properties parameter of the media /// <param name="id">The Media identifier.</param> /// <param name="media">A JSON encoded Media representing the updates</param> /// </summary> public MediaResponse UpdateMedia( int id, Media media) { var request = new RestRequest($"v1/media/{id}", Method.POST); request.Parameters.Clear(); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(media), ParameterType.RequestBody); return Execute<MediaResponse>(request); } /// <summary> /// Groups one "main" Media with one or more "child" Media. /// /// The main medium will by default be the only medium shown when searching, child media can be fetched by issuing a search with parentId set to the main medium id. /// <param name="id">The Media identifier.</param> /// <param name="children">An array of int values.</param> /// </summary> public object Group( int id, List<int> children) { var request = new RestRequest($"v1/media/{id}/group", Method.POST); request.Parameters.Clear(); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(children), ParameterType.RequestBody); return Execute<object>(request); } /// <summary> /// Restore a deleted Media. /// /// Can not restore a Media that has been hard deleted! /// <param name="id">The Media identifier.</param> /// </summary> public MediaResponse RestoreMedia( int id) { var request = new RestRequest($"v1/media/{id}/restore", Method.POST); request.Parameters.Clear(); return Execute<MediaResponse>(request); } /// <summary> /// Change status of a Media. /// /// This is used to move media from the uploaded tab into the library. /// Possible statuses are: <ul> <li>approved</li> </ul> /// /// <param name="id">The Media identifier.</param> /// <param name="status">The new status of the media</param> /// </summary> public Dictionary<string, object> SetStatus( int id, string status) { var request = new RestRequest($"v1/media/{id}/status", Method.POST); request.Parameters.Clear(); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(status), ParameterType.RequestBody); return Execute<Dictionary<string, object>>(request); } /// <summary> /// Upload a new preview for a media. /// /// Replaces the current preview thumbnails for a media with the supplied one. Recommended image size is minimum 1000px on the longest side. If a PDF is uploaded it will be added as a preview document. This enables users to browse documents directly from within QBank. The maximum recommended file size is 10MB. /// <param name="id"></param> /// </summary> public object UploadPreview( int id) { var request = new RestRequest($"v1/media/{id}/uploadpreview", Method.POST); request.Parameters.Clear(); return Execute<object>(request); } /// <summary> /// Upload a new version of a media /// /// This upload endpoint has been specifically tailored to fit chunked uploading (works well with Plupload2 for example). Max chunk size is about 10mb, if your files are larger than this, split it up and set correct chunk and chunks argument in the call. /// For example a 26mb file might be split in 3 chunks, so the following 3 calls should be made /// POST /media.json?chunks=3&chunk=0&filename=largefile.txt&categoryId=1 (file data is sent in body) /// POST /media.json?chunks=3&chunk=1&filename=largefile.txt&categoryId=1&fileId=<fileId from first call> (file data is sent in body) /// POST /media.json?chunks=3&chunk=2&filename=largefile.txt&categoryId=1&fileId=<fileId from first call> (file data is sent in body) /// /// <param name="id">The Media identifier.</param> /// <param name="revisionComment">The revision comment</param> /// <param name="name">Filename of the file being uploaded</param> /// <param name="chunk">The chunk we are currently uploading, starts at 0</param> /// <param name="chunks">Number of chunks you will be uploading, when (chunk - 1) == chunks the file will be considered uploaded</param> /// <param name="fileId">A unique fileId that will be used for this upload, if none is given one will be given to you</param> /// </summary> public Dictionary<string, object> UploadNewVersionChunked( int id, string revisionComment, string name, int chunk, int chunks, string fileId) { var request = new RestRequest($"v1/media/{id}/version", Method.POST); request.Parameters.Clear(); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(revisionComment), ParameterType.RequestBody); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(name), ParameterType.RequestBody); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(chunk), ParameterType.RequestBody); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(chunks), ParameterType.RequestBody); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(fileId), ParameterType.RequestBody); return Execute<Dictionary<string, object>>(request); } /// <summary> /// Post a comment on a media /// /// , leave username and useremail empty to post as the user that is logged on to the API. /// <param name="mediaId">the media to post the comment on.</param> /// <param name="comment">The comment to post</param> /// </summary> public CommentResponse CreateComment( int mediaId, Comment comment) { var request = new RestRequest($"v1/media/{mediaId}/comments", Method.POST); request.Parameters.Clear(); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(comment), ParameterType.RequestBody); return Execute<CommentResponse>(request); } /// <summary> /// Combines slides /// /// Combines several slides into one presentation. /// <param name="structure">An array of QBNK\QBank\Api\v1\Model\Slides\SlideStructure values.</param> /// </summary> public object CombineSlides( List<SlideStructure> structure) { var request = new RestRequest($"v1/media/slides/combine", Method.POST); request.Parameters.Clear(); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(structure), ParameterType.RequestBody); return Execute<object>(request); } /// <summary> /// Update some properties for a Media. /// /// Update the provided properties for the specified Media. Will not update any other properties then those provided. It is preferable to use this method over updating a whole media to change a few properties as the side effects are fewer. /// <param name="id">The Media identifier.</param> /// <param name="properties">An array of QBNK\QBank\Api\v1\Model\Property values.</param> /// </summary> public Dictionary<string, object> UpdateProperties( int id, List<Property> properties) { var request = new RestRequest($"v1/media/{id}/properties", Method.PUT); request.Parameters.Clear(); request.AddParameter("application/json", new RestSharpJsonNetSerializer().Serialize(properties), ParameterType.RequestBody); return Execute<Dictionary<string, object>>(request); } /// <summary> /// Delete a Media. /// /// Deleting a Media will set it's status to removed but will retain all data and enable restoration of the Media, much like the trash bin of your operating system. To permanetly remove a Media, use the "hardDelete" flag. /// <param name="id">The Media identifier.</param> /// <param name="hardDelete">Prevent restoration of the Media..</param> /// </summary> public MediaResponse RemoveMedia( int id, bool hardDelete = false) { var request = new RestRequest($"v1/media/{id}", Method.DELETE); request.Parameters.Clear(); request.AddParameter("hardDelete", hardDelete, ParameterType.QueryString); return Execute<MediaResponse>(request); } /// <summary> /// Delete a comment /// /// on a media /// <param name="mediaId">the media to delete the comment from.</param> /// <param name="commentId">the comment to delete.</param> /// </summary> public Comment RemoveComment( int mediaId, int commentId) { var request = new RestRequest($"v1/media/{mediaId}/comments/{commentId}", Method.DELETE); request.Parameters.Clear(); return Execute<Comment>(request); } } }
/* Copyright (c) 2005-2006 Tomas Matousek. The use and distribution terms for this software are contained in the file named License.txt, which can be found in the root of the Phalanger distribution. By using this software in any fashion, you are agreeing to be bound by the terms of this license. You must not remove this notice from this software. */ using System; using System.IO; using PHP.Core; using PHP.Core.Parsers; namespace PHP.Library { using CoreTokens = PHP.Core.Parsers.Tokens; /// <summary> /// Provides functions and constant related to PHP tokenizer. /// </summary> [ImplementsExtension(LibraryDescriptor.ExtTokenizer)] public static class PhpTokenizer { #region Tokens /// <exclude/> public enum Tokens { [ImplementsConstant("T_REQUIRE_ONCE")] T_REQUIRE_ONCE = CoreTokens.T_REQUIRE_ONCE, [ImplementsConstant("T_REQUIRE")] T_REQUIRE = CoreTokens.T_REQUIRE, [ImplementsConstant("T_EVAL")] T_EVAL = CoreTokens.T_EVAL, [ImplementsConstant("T_INCLUDE_ONCE")] T_INCLUDE_ONCE = CoreTokens.T_INCLUDE_ONCE, [ImplementsConstant("T_INCLUDE")] T_INCLUDE = CoreTokens.T_INCLUDE, [ImplementsConstant("T_LOGICAL_OR")] T_LOGICAL_OR = CoreTokens.T_LOGICAL_OR, [ImplementsConstant("T_LOGICAL_XOR")] T_LOGICAL_XOR = CoreTokens.T_LOGICAL_XOR, [ImplementsConstant("T_LOGICAL_AND")] T_LOGICAL_AND = CoreTokens.T_LOGICAL_AND, [ImplementsConstant("T_PRINT")] T_PRINT = CoreTokens.T_PRINT, [ImplementsConstant("T_SR_EQUAL")] T_SR_EQUAL = CoreTokens.T_SR_EQUAL, [ImplementsConstant("T_SL_EQUAL")] T_SL_EQUAL = CoreTokens.T_SL_EQUAL, [ImplementsConstant("T_XOR_EQUAL")] T_XOR_EQUAL = CoreTokens.T_XOR_EQUAL, [ImplementsConstant("T_OR_EQUAL")] T_OR_EQUAL = CoreTokens.T_OR_EQUAL, [ImplementsConstant("T_AND_EQUAL")] T_AND_EQUAL = CoreTokens.T_AND_EQUAL, [ImplementsConstant("T_MOD_EQUAL")] T_MOD_EQUAL = CoreTokens.T_MOD_EQUAL, [ImplementsConstant("T_CONCAT_EQUAL")] T_CONCAT_EQUAL = CoreTokens.T_CONCAT_EQUAL, [ImplementsConstant("T_DIV_EQUAL")] T_DIV_EQUAL = CoreTokens.T_DIV_EQUAL, [ImplementsConstant("T_MUL_EQUAL")] T_MUL_EQUAL = CoreTokens.T_MUL_EQUAL, [ImplementsConstant("T_MINUS_EQUAL")] T_MINUS_EQUAL = CoreTokens.T_MINUS_EQUAL, [ImplementsConstant("T_PLUS_EQUAL")] T_PLUS_EQUAL = CoreTokens.T_PLUS_EQUAL, [ImplementsConstant("T_BOOLEAN_OR")] T_BOOLEAN_OR = CoreTokens.T_BOOLEAN_OR, [ImplementsConstant("T_BOOLEAN_AND")] T_BOOLEAN_AND = CoreTokens.T_BOOLEAN_AND, [ImplementsConstant("T_IS_NOT_IDENTICAL")] T_IS_NOT_IDENTICAL = CoreTokens.T_IS_NOT_IDENTICAL, [ImplementsConstant("T_IS_IDENTICAL")] T_IS_IDENTICAL = CoreTokens.T_IS_IDENTICAL, [ImplementsConstant("T_IS_NOT_EQUAL")] T_IS_NOT_EQUAL = CoreTokens.T_IS_NOT_EQUAL, [ImplementsConstant("T_IS_EQUAL")] T_IS_EQUAL = CoreTokens.T_IS_EQUAL, [ImplementsConstant("T_IS_GREATER_OR_EQUAL")] T_IS_GREATER_OR_EQUAL = CoreTokens.T_IS_GREATER_OR_EQUAL, [ImplementsConstant("T_IS_SMALLER_OR_EQUAL")] T_IS_SMALLER_OR_EQUAL = CoreTokens.T_IS_SMALLER_OR_EQUAL, [ImplementsConstant("T_SR")] T_SR = CoreTokens.T_SR, [ImplementsConstant("T_SL")] T_SL = CoreTokens.T_SL, [ImplementsConstant("T_INSTANCEOF")] T_INSTANCEOF = CoreTokens.T_INSTANCEOF, [ImplementsConstant("T_UNSET_CAST")] T_UNSET_CAST = CoreTokens.T_UNSET_CAST, [ImplementsConstant("T_BOOL_CAST")] T_BOOL_CAST = CoreTokens.T_BOOL_CAST, [ImplementsConstant("T_OBJECT_CAST")] T_OBJECT_CAST = CoreTokens.T_OBJECT_CAST, [ImplementsConstant("T_ARRAY_CAST")] T_ARRAY_CAST = CoreTokens.T_ARRAY_CAST, [ImplementsConstant("T_STRING_CAST")] T_STRING_CAST = CoreTokens.T_STRING_CAST, [ImplementsConstant("T_DOUBLE_CAST")] T_DOUBLE_CAST = CoreTokens.T_DOUBLE_CAST, [ImplementsConstant("T_INT_CAST")] T_INT_CAST = CoreTokens.T_INT_CAST, [ImplementsConstant("T_DEC")] T_DEC = CoreTokens.T_DEC, [ImplementsConstant("T_INC")] T_INC = CoreTokens.T_INC, [ImplementsConstant("T_CLONE")] T_CLONE = CoreTokens.T_CLONE, [ImplementsConstant("T_NEW")] T_NEW = CoreTokens.T_NEW, [ImplementsConstant("T_EXIT")] T_EXIT = CoreTokens.T_EXIT, [ImplementsConstant("T_IF")] T_IF = CoreTokens.T_IF, [ImplementsConstant("T_ELSEIF")] T_ELSEIF = CoreTokens.T_ELSEIF, [ImplementsConstant("T_ELSE")] T_ELSE = CoreTokens.T_ELSE, [ImplementsConstant("T_ENDIF")] T_ENDIF = CoreTokens.T_ENDIF, [ImplementsConstant("T_LNUMBER")] T_LNUMBER = CoreTokens.T_LNUMBER, [ImplementsConstant("T_DNUMBER")] T_DNUMBER = CoreTokens.T_DNUMBER, [ImplementsConstant("T_STRING")] T_STRING = CoreTokens.T_STRING, [ImplementsConstant("T_STRING_VARNAME")] T_STRING_VARNAME = CoreTokens.T_STRING_VARNAME, [ImplementsConstant("T_VARIABLE")] T_VARIABLE = CoreTokens.T_VARIABLE, [ImplementsConstant("T_NUM_STRING")] T_NUM_STRING = CoreTokens.T_NUM_STRING, [ImplementsConstant("T_INLINE_HTML")] T_INLINE_HTML = CoreTokens.T_INLINE_HTML, [ImplementsConstant("T_CHARACTER")] T_CHARACTER = CoreTokens.T_CHARACTER, [ImplementsConstant("T_BAD_CHARACTER")] T_BAD_CHARACTER = CoreTokens.T_BAD_CHARACTER, [ImplementsConstant("T_ENCAPSED_AND_WHITESPACE")] T_ENCAPSED_AND_WHITESPACE = CoreTokens.T_ENCAPSED_AND_WHITESPACE, [ImplementsConstant("T_CONSTANT_ENCAPSED_STRING")] T_CONSTANT_ENCAPSED_STRING = CoreTokens.T_CONSTANT_ENCAPSED_STRING, [ImplementsConstant("T_ECHO")] T_ECHO = CoreTokens.T_ECHO, [ImplementsConstant("T_DO")] T_DO = CoreTokens.T_DO, [ImplementsConstant("T_WHILE")] T_WHILE = CoreTokens.T_WHILE, [ImplementsConstant("T_ENDWHILE")] T_ENDWHILE = CoreTokens.T_ENDWHILE, [ImplementsConstant("T_FOR")] T_FOR = CoreTokens.T_FOR, [ImplementsConstant("T_ENDFOR")] T_ENDFOR = CoreTokens.T_ENDFOR, [ImplementsConstant("T_FOREACH")] T_FOREACH = CoreTokens.T_FOREACH, [ImplementsConstant("T_ENDFOREACH")] T_ENDFOREACH = CoreTokens.T_ENDFOREACH, // [ImplementsConstant("T_DECLARE")] T_DECLARE = CoreTokens.T_DECLARE, // [ImplementsConstant("T_ENDDECLARE")] T_ENDDECLARE = CoreTokens.T_ENDDECLARE, [ImplementsConstant("T_AS")] T_AS = CoreTokens.T_AS, [ImplementsConstant("T_SWITCH")] T_SWITCH = CoreTokens.T_SWITCH, [ImplementsConstant("T_ENDSWITCH")] T_ENDSWITCH = CoreTokens.T_ENDSWITCH, [ImplementsConstant("T_CASE")] T_CASE = CoreTokens.T_CASE, [ImplementsConstant("T_DEFAULT")] T_DEFAULT = CoreTokens.T_DEFAULT, [ImplementsConstant("T_BREAK")] T_BREAK = CoreTokens.T_BREAK, [ImplementsConstant("T_CONTINUE")] T_CONTINUE = CoreTokens.T_CONTINUE, [ImplementsConstant("T_FUNCTION")] T_FUNCTION = CoreTokens.T_FUNCTION, [ImplementsConstant("T_CONST")] T_CONST = CoreTokens.T_CONST, [ImplementsConstant("T_RETURN")] T_RETURN = CoreTokens.T_RETURN, [ImplementsConstant("T_YIELD")] T_YIELD = CoreTokens.T_YIELD, [ImplementsConstant("T_TRY")] T_TRY = CoreTokens.T_TRY, [ImplementsConstant("T_CATCH")] T_CATCH = CoreTokens.T_CATCH, [ImplementsConstant("T_FINALLY")] T_FINALLY = CoreTokens.T_FINALLY, [ImplementsConstant("T_THROW")] T_THROW = CoreTokens.T_THROW, // [ImplementsConstant("T_USE")] T_USE = CoreTokens.T_USE, [ImplementsConstant("T_GLOBAL")] T_GLOBAL = CoreTokens.T_GLOBAL, [ImplementsConstant("T_PUBLIC")] T_PUBLIC = CoreTokens.T_PUBLIC, [ImplementsConstant("T_PROTECTED")] T_PROTECTED = CoreTokens.T_PROTECTED, [ImplementsConstant("T_PRIVATE")] T_PRIVATE = CoreTokens.T_PRIVATE, [ImplementsConstant("T_FINAL")] T_FINAL = CoreTokens.T_FINAL, [ImplementsConstant("T_ABSTRACT")] T_ABSTRACT = CoreTokens.T_ABSTRACT, [ImplementsConstant("T_STATIC")] T_STATIC = CoreTokens.T_STATIC, [ImplementsConstant("T_VAR")] T_VAR = CoreTokens.T_VAR, [ImplementsConstant("T_UNSET")] T_UNSET = CoreTokens.T_UNSET, [ImplementsConstant("T_ISSET")] T_ISSET = CoreTokens.T_ISSET, [ImplementsConstant("T_EMPTY")] T_EMPTY = CoreTokens.T_EMPTY, [ImplementsConstant("T_HALT_COMPILER")] T_HALT_COMPILER = 351, // Unused [ImplementsConstant("T_CLASS")] T_CLASS = CoreTokens.T_CLASS, [ImplementsConstant("T_INTERFACE")] T_INTERFACE = CoreTokens.T_INTERFACE, [ImplementsConstant("T_EXTENDS")] T_EXTENDS = CoreTokens.T_EXTENDS, [ImplementsConstant("T_IMPLEMENTS")] T_IMPLEMENTS = CoreTokens.T_IMPLEMENTS, [ImplementsConstant("T_OBJECT_OPERATOR")] T_OBJECT_OPERATOR = CoreTokens.T_OBJECT_OPERATOR, [ImplementsConstant("T_DOUBLE_ARROW")] T_DOUBLE_ARROW = CoreTokens.T_DOUBLE_ARROW, [ImplementsConstant("T_LIST")] T_LIST = CoreTokens.T_LIST, [ImplementsConstant("T_ARRAY")] T_ARRAY = CoreTokens.T_ARRAY, [ImplementsConstant("T_CLASS_C")] T_CLASS_C = CoreTokens.T_CLASS_C, [ImplementsConstant("T_METHOD_C")] T_METHOD_C = CoreTokens.T_METHOD_C, [ImplementsConstant("T_FUNC_C")] T_FUNC_C = CoreTokens.T_FUNC_C, [ImplementsConstant("T_LINE")] T_LINE = CoreTokens.T_LINE, [ImplementsConstant("T_FILE")] T_FILE = CoreTokens.T_FILE, [ImplementsConstant("T_COMMENT")] T_COMMENT = CoreTokens.T_COMMENT, [ImplementsConstant("T_DOC_COMMENT")] T_DOC_COMMENT = CoreTokens.T_DOC_COMMENT, [ImplementsConstant("T_OPEN_TAG")] T_OPEN_TAG = CoreTokens.T_OPEN_TAG, [ImplementsConstant("T_OPEN_TAG_WITH_ECHO")] T_OPEN_TAG_WITH_ECHO = CoreTokens.T_OPEN_TAG_WITH_ECHO, [ImplementsConstant("T_CLOSE_TAG")] T_CLOSE_TAG = CoreTokens.T_CLOSE_TAG, [ImplementsConstant("T_WHITESPACE")] T_WHITESPACE = CoreTokens.T_WHITESPACE, [ImplementsConstant("T_START_HEREDOC")] T_START_HEREDOC = CoreTokens.T_START_HEREDOC, [ImplementsConstant("T_END_HEREDOC")] T_END_HEREDOC = CoreTokens.T_END_HEREDOC, [ImplementsConstant("T_DOLLAR_OPEN_CURLY_BRACES")] T_DOLLAR_OPEN_CURLY_BRACES = CoreTokens.T_DOLLAR_OPEN_CURLY_BRACES, [ImplementsConstant("T_CURLY_OPEN")] T_CURLY_OPEN = CoreTokens.T_CURLY_OPEN, [ImplementsConstant("T_DOUBLE_COLON")] T_DOUBLE_COLON = CoreTokens.T_DOUBLE_COLON, [ImplementsConstant("T_PAAMAYIM_NEKUDOTAYIM")] T_PAAMAYIM_NEKUDOTAYIM = CoreTokens.T_DOUBLE_COLON, // Duplicate [ImplementsConstant("T_DIR")] T_DIR = CoreTokens.T_DIR, [ImplementsConstant("T_GOTO")] T_GOTO = CoreTokens.T_GOTO, } #endregion #region token_get_all, token_name /// <summary> /// Tokenize a source source and returns a list of tokens. /// </summary> /// <returns> /// Array of items that are either token string values of for unnamed tokens /// or arrays comprising of token id and token string value. /// </returns> [ImplementsFunction("token_get_all")] public static PhpArray GetAllTokens(string sourceCode) { PhpArray result = new PhpArray(); Tokenizer tokenizer = new Tokenizer(new StringReader(sourceCode)); for (; ; ) { CoreTokens token = tokenizer.GetNextToken(); if (token == CoreTokens.ERROR) { token = CoreTokens.T_STRING; } if (token == CoreTokens.EOF) break; if (Tokenizer.IsCharToken(token)) { result.Add(tokenizer.TokenText); } else { PhpArray item = new PhpArray(); item.Add((int)token); item.Add(tokenizer.TokenText); result.Add(item); } } return result; } /// <summary> /// Gets the name of the PHP grammar token. /// </summary> /// <param name="token">The token id.</param> /// <returns>The token name.</returns> [ImplementsFunction("token_name")] public static string GetTokenName(Tokens token) { return token.ToString(); } #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; namespace System.Xml.Xsl.Qil { /// <summary> /// Pattern visitor base internal class /// </summary> internal abstract class QilPatternVisitor : QilReplaceVisitor { /// <summary> /// Constructor. /// </summary> public QilPatternVisitor(QilPatterns patterns, QilFactory f) : base(f) { Patterns = patterns; } public QilPatterns Patterns { get; set; } public int Threshold { get; set; } = int.MaxValue; public int ReplacementCount { get; private set; } public int LastReplacement { get; private set; } public bool Matching { get { return ReplacementCount < Threshold; } } /// <summary> /// Called when a pattern has matched, but before the replacement code is executed. If this /// method returns false, then the replacement code is skipped. /// </summary> protected virtual bool AllowReplace(int pattern, QilNode original) { // If still matching patterns, if (Matching) { // Increment the replacement count ReplacementCount++; // Save the id of this pattern in case it's the last LastReplacement = pattern; return true; } return false; } /// <summary> /// Called when a pattern has matched and after replacement code is executed. /// </summary> protected virtual QilNode Replace(int pattern, QilNode original, QilNode replacement) { replacement.SourceLine = original.SourceLine; return replacement; } /// <summary> /// Called when all replacements have already been made and all annotations are complete. /// </summary> protected virtual QilNode NoReplace(QilNode node) { return node; } //----------------------------------------------- // QilVisitor overrides //----------------------------------------------- /// <summary> /// Visit children of this node first, then pattern match on the node itself. /// </summary> protected override QilNode Visit(QilNode node) { if (node == null) return VisitNull(); node = VisitChildren(node); return base.Visit(node); } // Do not edit this region #region AUTOGENERATED #region meta protected override QilNode VisitQilExpression(QilExpression n) { return NoReplace(n); } protected override QilNode VisitFunctionList(QilList n) { return NoReplace(n); } protected override QilNode VisitGlobalVariableList(QilList n) { return NoReplace(n); } protected override QilNode VisitGlobalParameterList(QilList n) { return NoReplace(n); } protected override QilNode VisitActualParameterList(QilList n) { return NoReplace(n); } protected override QilNode VisitFormalParameterList(QilList n) { return NoReplace(n); } protected override QilNode VisitSortKeyList(QilList n) { return NoReplace(n); } protected override QilNode VisitBranchList(QilList n) { return NoReplace(n); } protected override QilNode VisitOptimizeBarrier(QilUnary n) { return NoReplace(n); } protected override QilNode VisitUnknown(QilNode n) { return NoReplace(n); } #endregion #region specials protected override QilNode VisitDataSource(QilDataSource n) { return NoReplace(n); } protected override QilNode VisitNop(QilUnary n) { return NoReplace(n); } protected override QilNode VisitError(QilUnary n) { return NoReplace(n); } protected override QilNode VisitWarning(QilUnary n) { return NoReplace(n); } #endregion #region variables protected override QilNode VisitFor(QilIterator n) { return NoReplace(n); } protected override QilNode VisitForReference(QilIterator n) { return NoReplace(n); } protected override QilNode VisitLet(QilIterator n) { return NoReplace(n); } protected override QilNode VisitLetReference(QilIterator n) { return NoReplace(n); } protected override QilNode VisitParameter(QilParameter n) { return NoReplace(n); } protected override QilNode VisitParameterReference(QilParameter n) { return NoReplace(n); } protected override QilNode VisitPositionOf(QilUnary n) { return NoReplace(n); } #endregion #region literals protected override QilNode VisitTrue(QilNode n) { return NoReplace(n); } protected override QilNode VisitFalse(QilNode n) { return NoReplace(n); } protected override QilNode VisitLiteralString(QilLiteral n) { return NoReplace(n); } protected override QilNode VisitLiteralInt32(QilLiteral n) { return NoReplace(n); } protected override QilNode VisitLiteralInt64(QilLiteral n) { return NoReplace(n); } protected override QilNode VisitLiteralDouble(QilLiteral n) { return NoReplace(n); } protected override QilNode VisitLiteralDecimal(QilLiteral n) { return NoReplace(n); } protected override QilNode VisitLiteralQName(QilName n) { return NoReplace(n); } protected override QilNode VisitLiteralType(QilLiteral n) { return NoReplace(n); } protected override QilNode VisitLiteralObject(QilLiteral n) { return NoReplace(n); } #endregion #region boolean operators protected override QilNode VisitAnd(QilBinary n) { return NoReplace(n); } protected override QilNode VisitOr(QilBinary n) { return NoReplace(n); } protected override QilNode VisitNot(QilUnary n) { return NoReplace(n); } #endregion #region choice protected override QilNode VisitConditional(QilTernary n) { return NoReplace(n); } protected override QilNode VisitChoice(QilChoice n) { return NoReplace(n); } #endregion #region collection operators protected override QilNode VisitLength(QilUnary n) { return NoReplace(n); } protected override QilNode VisitSequence(QilList n) { return NoReplace(n); } protected override QilNode VisitUnion(QilBinary n) { return NoReplace(n); } protected override QilNode VisitIntersection(QilBinary n) { return NoReplace(n); } protected override QilNode VisitDifference(QilBinary n) { return NoReplace(n); } protected override QilNode VisitAverage(QilUnary n) { return NoReplace(n); } protected override QilNode VisitSum(QilUnary n) { return NoReplace(n); } protected override QilNode VisitMinimum(QilUnary n) { return NoReplace(n); } protected override QilNode VisitMaximum(QilUnary n) { return NoReplace(n); } #endregion #region arithmetic operators protected override QilNode VisitNegate(QilUnary n) { return NoReplace(n); } protected override QilNode VisitAdd(QilBinary n) { return NoReplace(n); } protected override QilNode VisitSubtract(QilBinary n) { return NoReplace(n); } protected override QilNode VisitMultiply(QilBinary n) { return NoReplace(n); } protected override QilNode VisitDivide(QilBinary n) { return NoReplace(n); } protected override QilNode VisitModulo(QilBinary n) { return NoReplace(n); } #endregion #region string operators protected override QilNode VisitStrLength(QilUnary n) { return NoReplace(n); } protected override QilNode VisitStrConcat(QilStrConcat n) { return NoReplace(n); } protected override QilNode VisitStrParseQName(QilBinary n) { return NoReplace(n); } #endregion #region value comparison operators protected override QilNode VisitNe(QilBinary n) { return NoReplace(n); } protected override QilNode VisitEq(QilBinary n) { return NoReplace(n); } protected override QilNode VisitGt(QilBinary n) { return NoReplace(n); } protected override QilNode VisitGe(QilBinary n) { return NoReplace(n); } protected override QilNode VisitLt(QilBinary n) { return NoReplace(n); } protected override QilNode VisitLe(QilBinary n) { return NoReplace(n); } #endregion #region node comparison operators protected override QilNode VisitIs(QilBinary n) { return NoReplace(n); } protected override QilNode VisitAfter(QilBinary n) { return NoReplace(n); } protected override QilNode VisitBefore(QilBinary n) { return NoReplace(n); } #endregion #region loops protected override QilNode VisitLoop(QilLoop n) { return NoReplace(n); } protected override QilNode VisitFilter(QilLoop n) { return NoReplace(n); } #endregion #region sorting protected override QilNode VisitSort(QilLoop n) { return NoReplace(n); } protected override QilNode VisitSortKey(QilSortKey n) { return NoReplace(n); } protected override QilNode VisitDocOrderDistinct(QilUnary n) { return NoReplace(n); } #endregion #region function definition and invocation protected override QilNode VisitFunction(QilFunction n) { return NoReplace(n); } protected override QilNode VisitFunctionReference(QilFunction n) { return NoReplace(n); } protected override QilNode VisitInvoke(QilInvoke n) { return NoReplace(n); } #endregion #region XML navigation protected override QilNode VisitContent(QilUnary n) { return NoReplace(n); } protected override QilNode VisitAttribute(QilBinary n) { return NoReplace(n); } protected override QilNode VisitParent(QilUnary n) { return NoReplace(n); } protected override QilNode VisitRoot(QilUnary n) { return NoReplace(n); } protected override QilNode VisitXmlContext(QilNode n) { return NoReplace(n); } protected override QilNode VisitDescendant(QilUnary n) { return NoReplace(n); } protected override QilNode VisitDescendantOrSelf(QilUnary n) { return NoReplace(n); } protected override QilNode VisitAncestor(QilUnary n) { return NoReplace(n); } protected override QilNode VisitAncestorOrSelf(QilUnary n) { return NoReplace(n); } protected override QilNode VisitPreceding(QilUnary n) { return NoReplace(n); } protected override QilNode VisitFollowingSibling(QilUnary n) { return NoReplace(n); } protected override QilNode VisitPrecedingSibling(QilUnary n) { return NoReplace(n); } protected override QilNode VisitNodeRange(QilBinary n) { return NoReplace(n); } protected override QilNode VisitDeref(QilBinary n) { return NoReplace(n); } #endregion #region XML construction protected override QilNode VisitElementCtor(QilBinary n) { return NoReplace(n); } protected override QilNode VisitAttributeCtor(QilBinary n) { return NoReplace(n); } protected override QilNode VisitCommentCtor(QilUnary n) { return NoReplace(n); } protected override QilNode VisitPICtor(QilBinary n) { return NoReplace(n); } protected override QilNode VisitTextCtor(QilUnary n) { return NoReplace(n); } protected override QilNode VisitRawTextCtor(QilUnary n) { return NoReplace(n); } protected override QilNode VisitDocumentCtor(QilUnary n) { return NoReplace(n); } protected override QilNode VisitNamespaceDecl(QilBinary n) { return NoReplace(n); } protected override QilNode VisitRtfCtor(QilBinary n) { return NoReplace(n); } #endregion #region Node properties protected override QilNode VisitNameOf(QilUnary n) { return NoReplace(n); } protected override QilNode VisitLocalNameOf(QilUnary n) { return NoReplace(n); } protected override QilNode VisitNamespaceUriOf(QilUnary n) { return NoReplace(n); } protected override QilNode VisitPrefixOf(QilUnary n) { return NoReplace(n); } #endregion #region Type operators protected override QilNode VisitTypeAssert(QilTargetType n) { return NoReplace(n); } protected override QilNode VisitIsType(QilTargetType n) { return NoReplace(n); } protected override QilNode VisitIsEmpty(QilUnary n) { return NoReplace(n); } #endregion #region XPath operators protected override QilNode VisitXPathNodeValue(QilUnary n) { return NoReplace(n); } protected override QilNode VisitXPathFollowing(QilUnary n) { return NoReplace(n); } protected override QilNode VisitXPathPreceding(QilUnary n) { return NoReplace(n); } protected override QilNode VisitXPathNamespace(QilUnary n) { return NoReplace(n); } #endregion #region XSLT protected override QilNode VisitXsltGenerateId(QilUnary n) { return NoReplace(n); } protected override QilNode VisitXsltInvokeLateBound(QilInvokeLateBound n) { return NoReplace(n); } protected override QilNode VisitXsltInvokeEarlyBound(QilInvokeEarlyBound n) { return NoReplace(n); } protected override QilNode VisitXsltCopy(QilBinary n) { return NoReplace(n); } protected override QilNode VisitXsltCopyOf(QilUnary n) { return NoReplace(n); } protected override QilNode VisitXsltConvert(QilTargetType n) { return NoReplace(n); } #endregion #endregion //----------------------------------------------- // Helper methods //----------------------------------------------- /// <summary> /// A bit vector holding a set of rewrites. /// </summary> sealed internal class QilPatterns { private BitArray _bits; public QilPatterns(int szBits, bool allSet) { _bits = new BitArray(szBits, allSet); } public void Add(int i) { _bits.Set(i, true); } public bool IsSet(int i) { return _bits[i]; } } } }
namespace Owin.Scim.v2.Validation { using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Net; using Configuration; using ErrorHandling; using Extensions; using FluentValidation; using Model; using Repository; using Scim.Model; using Scim.Model.Users; using Scim.Validation; using Security; public class ScimUser2Validator : ResourceValidatorBase<ScimUser2> { private readonly IUserRepository _UserRepository; private readonly IManagePasswords _PasswordManager; public ScimUser2Validator( ScimServerConfiguration serverConfiguration, ResourceExtensionValidators extensionValidators, IUserRepository userRepository, IManagePasswords passwordManager) : base(serverConfiguration, extensionValidators) { _UserRepository = userRepository; _PasswordManager = passwordManager; } protected override void ConfigureDefaultRuleSet() { RuleFor(u => u.UserName) .NotEmpty() .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, ScimErrorDetail.AttributeRequired("userName"))); When(user => !string.IsNullOrWhiteSpace(user.PreferredLanguage), () => { RuleFor(user => user.PreferredLanguage) .Must(ValidatePreferredLanguage) .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, "The attribute 'preferredLanguage' is formatted the same " + "as the HTTP Accept-Language header field. (e.g., da, en-gb;q=0.8, en;q=0.7)")); }); When(user => user.ProfileUrl != null, () => { RuleFor(user => user.ProfileUrl) .Must(uri => uri.IsAbsoluteUri) .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, "The attribute 'profileUrl' must be a valid absolute URI.")); }); When(user => !string.IsNullOrWhiteSpace(user.Locale), () => { RuleFor(user => user.Locale) .Must(locale => { try { CultureInfo.GetCultureInfo(locale); return true; } catch (Exception) { } return false; }) .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, "The attribute 'locale' MUST be a valid language tag as defined in [RFC5646].")); }); When(user => user.Emails != null && user.Emails.Any(), () => { RuleFor(user => user.Emails) .SetCollectionValidator( new GenericExpressionValidator<Email> { { email => email.Value, config => config .NotEmpty() .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, ScimErrorDetail.AttributeRequired("email.value"))) .EmailAddress() .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, "The attribute 'email.value' must be a valid email as defined in [RFC5321].")) } }); }); When(user => user.Ims != null && user.Ims.Any(), () => { RuleFor(user => user.Ims) .SetCollectionValidator( new GenericExpressionValidator<InstantMessagingAddress> { { im => im.Value, config => config .NotEmpty() .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, ScimErrorDetail.AttributeRequired("im.value"))) } }); }); When(user => user.PhoneNumbers != null && user.PhoneNumbers.Any(), () => { // The value SHOULD be specified according to the format defined // in [RFC3966], e.g., 'tel:+1-201-555-0123'. RuleFor(user => user.PhoneNumbers) .SetCollectionValidator( new GenericExpressionValidator<PhoneNumber> { { pn => pn.Value, config => config .NotEmpty() .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, ScimErrorDetail.AttributeRequired("phoneNumber.value"))) .Must(PhoneNumbers.PhoneNumberUtil.IsViablePhoneNumber) .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, "The attribute 'phoneNumber.value' must be a valid phone number as defined in [RFC3966].")) } }); }); When(user => user.Photos != null && user.Photos.Any(), () => { RuleFor(user => user.Photos) .SetCollectionValidator( new GenericExpressionValidator<Photo> { { photo => photo.Value, config => config .NotEmpty() .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, ScimErrorDetail.AttributeRequired("photo.value"))) .Must(uri => uri.IsAbsoluteUri) .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, "The attribute 'photo.value' must be a valid absolute URI.")) } }); }); When(user => user.Addresses != null && user.Addresses.Any(), () => { RuleFor(user => user.Addresses) .SetCollectionValidator( new GenericExpressionValidator<MailingAddress> { v => v.When(a => !string.IsNullOrWhiteSpace(a.Country), () => { v.RuleFor(a => a.Country) .Must(countryCode => { try { new RegionInfo(countryCode); return true; } catch { } return false; }) .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, "The attribute 'address.country' must be a valid country code as defined by [ISO3166-1 alpha-2].")); }) }); }); When(user => user.Entitlements != null && user.Entitlements.Any(), () => { RuleFor(user => user.Entitlements) .SetCollectionValidator( new GenericExpressionValidator<Entitlement> { { entitlement => entitlement.Value, config => config .NotEmpty() .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, ScimErrorDetail.AttributeRequired("entitlement.value"))) } }); }); When(user => user.Roles != null && user.Roles.Any(), () => { RuleFor(user => user.Roles) .SetCollectionValidator( new GenericExpressionValidator<Role> { { role => role.Value, config => config .NotEmpty() .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, ScimErrorDetail.AttributeRequired("role.value"))) } }); }); } protected override void ConfigureCreateRuleSet() { When(user => !string.IsNullOrWhiteSpace(user.UserName), () => { RuleFor(user => user.UserName) .MustAsync(async (userName, token) => await _UserRepository.IsUserNameAvailable(userName)) .WithState(u => new ScimError( HttpStatusCode.Conflict, ScimErrorType.Uniqueness, ScimErrorDetail.AttributeUnique("userName"))); }); When(user => user.Password != null, () => { RuleFor(user => user.Password) .MustAsync(async (password, token) => await _PasswordManager.MeetsRequirements(password)) .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, "The attribute 'password' does not meet the security requirements set by the provider.")); }); } protected override void ConfigureUpdateRuleSet() { RuleFor(user => user.Id) .Immutable(() => ExistingRecord.Id, StringComparer.OrdinalIgnoreCase) .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.Mutability, ScimErrorDetail.AttributeImmutable("id"))); // Updating a username validation When(user => user.UserName != null && !user.UserName.Equals(ExistingRecord.UserName, StringComparison.OrdinalIgnoreCase), () => { RuleFor(user => user.UserName) .MustAsync(async (user, userName, token) => await _UserRepository.IsUserNameAvailable(userName)) .WithState(user => new ScimError( HttpStatusCode.Conflict, ScimErrorType.Uniqueness, ScimErrorDetail.AttributeUnique("userName"))); }); // Updating a user password When(user => user.Password != null && _PasswordManager.PasswordIsDifferent(user.Password, ExistingRecord.Password), () => { RuleFor(user => user.Password) .MustAsync(async (password, token) => await _PasswordManager.MeetsRequirements(password)) .WithState(u => new ScimError( HttpStatusCode.BadRequest, ScimErrorType.InvalidValue, "The attribute 'password' does not meet the security requirements set by the provider.")); }); } /// <summary> /// The value indicates the set of natural languages that are preferred. /// The format of the value is the same as the HTTP Accept-Language header /// field (not including "Accept-Language:") and is specified in Section /// 5.3.5 of[RFC7231]. The intent of this value is to enable cloud /// applications to perform matching of language tags [RFC4647] /// </summary> /// <param name="preferredLanguage"></param> /// <returns></returns> private bool ValidatePreferredLanguage(string preferredLanguage) { IEnumerable<Tuple<string, decimal>> stringsWithQuality; if (TryParseWeightedValues(preferredLanguage, out stringsWithQuality)) { if (stringsWithQuality.Any( langWithQuality => { try { CultureInfo.GetCultureInfo(langWithQuality.Item1); return true; } catch (CultureNotFoundException) { } return false; })) { return true; } } return false; } private bool TryParseWeightedValues(string multipleValueStringWithQuality, out IEnumerable<Tuple<string, decimal>> stringsWithQuality) { stringsWithQuality = null; if (String.IsNullOrWhiteSpace(multipleValueStringWithQuality)) return false; var values = multipleValueStringWithQuality.Split(new[] { ',' }, StringSplitOptions.RemoveEmptyEntries) .Select(x => x.Trim()) .ToList(); if (!values.Any()) return false; var parsed = values.Select(x => { var sections = x.Split(new[] { ";" }, StringSplitOptions.RemoveEmptyEntries); var mediaRange = sections[0].Trim(); var quality = 1m; for (var index = 1; index < sections.Length; index++) { var trimmedValue = sections[index].Trim(); if (trimmedValue.StartsWith("q=", StringComparison.OrdinalIgnoreCase)) { decimal temp; var stringValue = trimmedValue.Substring(2); if (Decimal.TryParse(stringValue, NumberStyles.Number, CultureInfo.InvariantCulture, out temp)) { quality = temp; } } else { mediaRange += ";" + trimmedValue; } } return new Tuple<string, decimal>(mediaRange, quality); }); if (!parsed.Any()) return false; stringsWithQuality = parsed.OrderByDescending(x => x.Item2).ToArray(); return true; } } }
/****************************************************************************** * The MIT License * Copyright (c) 2003 Novell Inc. www.novell.com * * Permission is hereby granted, free of charge, to any person obtaining a copy * of this software and associated documentation files (the Software), to deal * in the Software without restriction, including without limitation the rights * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell * copies of the Software, and to permit persons to whom the Software is * furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED AS IS, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE * SOFTWARE. *******************************************************************************/ // // Novell.Directory.Ldap.LdapDN.cs // // Author: // Sunil Kumar (Sunilk@novell.com) // // (C) 2003 Novell, Inc (http://www.novell.com) // using System; using Novell.Directory.LDAP.VQ.Utilclass; namespace Novell.Directory.LDAP.VQ { /// <summary> A utility class to facilitate composition and deomposition /// of distinguished names DNs. /// /// Specifies methods for manipulating a distinguished name DN /// and a relative distinguished name RDN. /// </summary> public class LdapDN { /// <summary> Compares the two strings per the distinguishedNameMatch equality matching /// (using case-ignore matching). IllegalArgumentException is thrown if one /// or both DNs are invalid. UnsupportedOpersationException is thrown if the /// API implementation is not able to detemine if the DNs match or not. /// /// </summary> /// <param name="dn1"> String form of the first DN to compare. /// /// </param> /// <param name="dn2"> String form of the second DN to compare. /// /// </param> /// <returns> Returns true if the two strings correspond to the same DN; false /// if the DNs are different. /// </returns> [CLSCompliant(false)] public static bool equals(string dn1, string dn2) { DN dnA = new DN(dn1); DN dnB = new DN(dn2); return dnA.Equals(dnB); } /// <summary> Returns the RDN after escaping the characters requiring escaping. /// /// For example, for the rdn "cn=Acme, Inc", the escapeRDN method /// returns "cn=Acme\, Inc". /// /// escapeRDN escapes the AttributeValue by inserting '\' before the /// following chars: * ',' '+' '"' '\' 'LESSTHAN' 'GREATERTHAN' ';' /// '#' if it comes at the beginning of the string, and /// ' ' (space) if it comes at the beginning or the end of a string. /// Note that single-valued attributes can be used because of ambiguity. See /// RFC 2253 /// /// </summary> /// <param name="rdn"> The RDN to escape. /// /// </param> /// <returns> The RDN with escaping characters. /// </returns> public static string escapeRDN(string rdn) { System.Text.StringBuilder escapedS = new System.Text.StringBuilder(rdn); int i = 0; while (i < escapedS.Length && escapedS[i] != '=') { i++; //advance until we find the separator = } if (i == escapedS.Length) { throw new ArgumentException("Could not parse RDN: Attribute " + "type and name must be separated by an equal symbol, '='"); } i++; //check for a space or # at the beginning of a string. if ((escapedS[i] == ' ') || (escapedS[i] == '#')) { escapedS.Insert(i++, '\\'); } //loop from second char to the second to last for (; i < escapedS.Length; i++) { if ((escapedS[i] == ',') || (escapedS[i] == '+') || (escapedS[i] == '"') || (escapedS[i] == '\\') || (escapedS[i] == '<') || (escapedS[i] == '>') || (escapedS[i] == ';')) { escapedS.Insert(i++, '\\'); } } //check last char for a space if (escapedS[escapedS.Length - 1] == ' ') { escapedS.Insert(escapedS.Length - 1, '\\'); } return escapedS.ToString(); } /// <summary> Returns the individual components of a distinguished name (DN). /// /// </summary> /// <param name="dn"> The distinguished name, for example, "cn=Babs /// Jensen,ou=Accounting,o=Acme,c=US" /// /// </param> /// <param name="noTypes"> If true, returns only the values of the /// components and not the names. For example, "Babs /// Jensen", "Accounting", "Acme", "US" instead of /// "cn=Babs Jensen", "ou=Accounting", "o=Acme", and /// "c=US". /// /// </param> /// <returns> An array of strings representing the individual components /// of a DN, or null if the DN is not valid. /// </returns> public static string[] explodeDN(string dn, bool noTypes) { DN dnToExplode = new DN(dn); return dnToExplode.explodeDN(noTypes); } /// <summary> Returns the individual components of a relative distinguished name /// (RDN), normalized. /// /// </summary> /// <param name="rdn"> The relative distinguished name, or in other words, /// the left-most component of a distinguished name. /// /// </param> /// <param name="noTypes"> If true, returns only the values of the /// components, and not the names of the component, for /// example "Babs Jensen" instead of "cn=Babs Jensen". /// /// </param> /// <returns> An array of strings representing the individual components /// of an RDN, or null if the RDN is not a valid RDN. /// </returns> public static string[] explodeRDN(string rdn, bool noTypes) { RDN rdnToExplode = new RDN(rdn); return rdnToExplode.explodeRDN(noTypes); } /// <summary> Returns true if the string conforms to distinguished name syntax.</summary> /// <param name="dn"> String to evaluate fo distinguished name syntax. /// </param> /// <returns> true if the dn is valid. /// </returns> public static bool isValid(string dn) { try { new DN(dn); } catch (ArgumentException iae) { return false; } return true; } /// <summary> Returns the DN normalized by removal of non-significant space characters /// as per RFC 2253, section4. /// /// </summary> /// <returns> a normalized string /// </returns> public static string normalize(string dn) { DN testDN = new DN(dn); return testDN.ToString(); } /// <summary> Returns the RDN after unescaping the characters requiring escaping. /// /// For example, for the rdn "cn=Acme\, Inc", the unescapeRDN method /// returns "cn=Acme, Inc". /// unescapeRDN unescapes the AttributeValue by /// removing the '\' when the next character fits the following: /// ',' '+' '"' '\' 'LESSTHAN' 'GREATERTHAN' ';' /// '#' if it comes at the beginning of the Attribute Name /// (without the '\'). /// ' ' (space) if it comes at the beginning or the end of the Attribute Name /// /// </summary> /// <param name="rdn"> The RDN to unescape. /// /// </param> /// <returns> The RDN with the escaping characters removed. /// </returns> public static string unescapeRDN(string rdn) { System.Text.StringBuilder unescaped = new System.Text.StringBuilder(); int i = 0; while (i < rdn.Length && rdn[i] != '=') { i++; //advance until we find the separator = } if (i == rdn.Length) { throw new ArgumentException("Could not parse rdn: Attribute " + "type and name must be separated by an equal symbol, '='"); } i++; //check if the first two chars are "\ " (slash space) or "\#" if ((rdn[i] == '\\') && (i + 1 < rdn.Length - 1) && ((rdn[i + 1] == ' ') || (rdn[i + 1] == '#'))) { i++; } for (; i < rdn.Length; i++) { //if the current char is a slash, not the end char, and is followed // by a special char then... if ((rdn[i] == '\\') && (i != rdn.Length - 1)) { if ((rdn[i + 1] == ',') || (rdn[i + 1] == '+') || (rdn[i + 1] == '"') || (rdn[i + 1] == '\\') || (rdn[i + 1] == '<') || (rdn[i + 1] == '>') || (rdn[i + 1] == ';')) { //I'm not sure if I have to check for these special chars continue; } //check if the last two chars are "\ " if ((rdn[i + 1] == ' ') && (i + 2 == rdn.Length)) { //if the last char is a space continue; } } unescaped.Append(rdn[i]); } return unescaped.ToString(); } } //end class LdapDN }
using System; using System.CodeDom.Compiler; using System.Collections.Generic; using System.Data; using System.Data.SqlClient; using System.Globalization; using System.Linq; using System.Text; namespace EduHub.Data.Entities { /// <summary> /// BPAY Receipts for Sundry Debtors Data Set /// </summary> [GeneratedCode("EduHub Data", "0.9")] public sealed partial class DRBDataSet : EduHubDataSet<DRB> { /// <inheritdoc /> public override string Name { get { return "DRB"; } } /// <inheritdoc /> public override bool SupportsEntityLastModified { get { return true; } } internal DRBDataSet(EduHubContext Context) : base(Context) { Index_DR_CODE = new Lazy<Dictionary<string, IReadOnlyList<DRB>>>(() => this.ToGroupedDictionary(i => i.DR_CODE)); Index_REFERENCE_NO = new Lazy<NullDictionary<string, IReadOnlyList<DRB>>>(() => this.ToGroupedNullDictionary(i => i.REFERENCE_NO)); Index_TID = new Lazy<Dictionary<int, DRB>>(() => this.ToDictionary(i => i.TID)); } /// <summary> /// Matches CSV file headers to actions, used to deserialize <see cref="DRB" /> /// </summary> /// <param name="Headers">The CSV column headers</param> /// <returns>An array of actions which deserialize <see cref="DRB" /> fields for each CSV column header</returns> internal override Action<DRB, string>[] BuildMapper(IReadOnlyList<string> Headers) { var mapper = new Action<DRB, string>[Headers.Count]; for (var i = 0; i < Headers.Count; i++) { switch (Headers[i]) { case "TID": mapper[i] = (e, v) => e.TID = int.Parse(v); break; case "DR_CODE": mapper[i] = (e, v) => e.DR_CODE = v; break; case "REFERENCE_NO": mapper[i] = (e, v) => e.REFERENCE_NO = v; break; case "CUST_REFERENCE": mapper[i] = (e, v) => e.CUST_REFERENCE = v; break; case "RECORD_TYPE": mapper[i] = (e, v) => e.RECORD_TYPE = v; break; case "BILLER_CODE": mapper[i] = (e, v) => e.BILLER_CODE = v; break; case "PAYMENT_TYPE": mapper[i] = (e, v) => e.PAYMENT_TYPE = v; break; case "AMOUNT": mapper[i] = (e, v) => e.AMOUNT = v == null ? (decimal?)null : decimal.Parse(v); break; case "PAYMENT_DATE": mapper[i] = (e, v) => e.PAYMENT_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "DELETE_FLAG": mapper[i] = (e, v) => e.DELETE_FLAG = v; break; case "INVOICE_TID": mapper[i] = (e, v) => e.INVOICE_TID = v == null ? (int?)null : int.Parse(v); break; case "LW_DATE": mapper[i] = (e, v) => e.LW_DATE = v == null ? (DateTime?)null : DateTime.ParseExact(v, "d/MM/yyyy h:mm:ss tt", CultureInfo.InvariantCulture); break; case "LW_TIME": mapper[i] = (e, v) => e.LW_TIME = v == null ? (short?)null : short.Parse(v); break; case "LW_USER": mapper[i] = (e, v) => e.LW_USER = v; break; default: mapper[i] = MapperNoOp; break; } } return mapper; } /// <summary> /// Merges <see cref="DRB" /> delta entities /// </summary> /// <param name="Entities">Iterator for base <see cref="DRB" /> entities</param> /// <param name="DeltaEntities">List of delta <see cref="DRB" /> entities</param> /// <returns>A merged <see cref="IEnumerable{DRB}"/> of entities</returns> internal override IEnumerable<DRB> ApplyDeltaEntities(IEnumerable<DRB> Entities, List<DRB> DeltaEntities) { HashSet<int> Index_TID = new HashSet<int>(DeltaEntities.Select(i => i.TID)); using (var deltaIterator = DeltaEntities.GetEnumerator()) { using (var entityIterator = Entities.GetEnumerator()) { while (deltaIterator.MoveNext()) { var deltaClusteredKey = deltaIterator.Current.DR_CODE; bool yieldEntity = false; while (entityIterator.MoveNext()) { var entity = entityIterator.Current; bool overwritten = Index_TID.Remove(entity.TID); if (entity.DR_CODE.CompareTo(deltaClusteredKey) <= 0) { if (!overwritten) { yield return entity; } } else { yieldEntity = !overwritten; break; } } yield return deltaIterator.Current; if (yieldEntity) { yield return entityIterator.Current; } } while (entityIterator.MoveNext()) { yield return entityIterator.Current; } } } } #region Index Fields private Lazy<Dictionary<string, IReadOnlyList<DRB>>> Index_DR_CODE; private Lazy<NullDictionary<string, IReadOnlyList<DRB>>> Index_REFERENCE_NO; private Lazy<Dictionary<int, DRB>> Index_TID; #endregion #region Index Methods /// <summary> /// Find DRB by DR_CODE field /// </summary> /// <param name="DR_CODE">DR_CODE value used to find DRB</param> /// <returns>List of related DRB entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<DRB> FindByDR_CODE(string DR_CODE) { return Index_DR_CODE.Value[DR_CODE]; } /// <summary> /// Attempt to find DRB by DR_CODE field /// </summary> /// <param name="DR_CODE">DR_CODE value used to find DRB</param> /// <param name="Value">List of related DRB entities</param> /// <returns>True if the list of related DRB entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByDR_CODE(string DR_CODE, out IReadOnlyList<DRB> Value) { return Index_DR_CODE.Value.TryGetValue(DR_CODE, out Value); } /// <summary> /// Attempt to find DRB by DR_CODE field /// </summary> /// <param name="DR_CODE">DR_CODE value used to find DRB</param> /// <returns>List of related DRB entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<DRB> TryFindByDR_CODE(string DR_CODE) { IReadOnlyList<DRB> value; if (Index_DR_CODE.Value.TryGetValue(DR_CODE, out value)) { return value; } else { return null; } } /// <summary> /// Find DRB by REFERENCE_NO field /// </summary> /// <param name="REFERENCE_NO">REFERENCE_NO value used to find DRB</param> /// <returns>List of related DRB entities</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<DRB> FindByREFERENCE_NO(string REFERENCE_NO) { return Index_REFERENCE_NO.Value[REFERENCE_NO]; } /// <summary> /// Attempt to find DRB by REFERENCE_NO field /// </summary> /// <param name="REFERENCE_NO">REFERENCE_NO value used to find DRB</param> /// <param name="Value">List of related DRB entities</param> /// <returns>True if the list of related DRB entities is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByREFERENCE_NO(string REFERENCE_NO, out IReadOnlyList<DRB> Value) { return Index_REFERENCE_NO.Value.TryGetValue(REFERENCE_NO, out Value); } /// <summary> /// Attempt to find DRB by REFERENCE_NO field /// </summary> /// <param name="REFERENCE_NO">REFERENCE_NO value used to find DRB</param> /// <returns>List of related DRB entities, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public IReadOnlyList<DRB> TryFindByREFERENCE_NO(string REFERENCE_NO) { IReadOnlyList<DRB> value; if (Index_REFERENCE_NO.Value.TryGetValue(REFERENCE_NO, out value)) { return value; } else { return null; } } /// <summary> /// Find DRB by TID field /// </summary> /// <param name="TID">TID value used to find DRB</param> /// <returns>Related DRB entity</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public DRB FindByTID(int TID) { return Index_TID.Value[TID]; } /// <summary> /// Attempt to find DRB by TID field /// </summary> /// <param name="TID">TID value used to find DRB</param> /// <param name="Value">Related DRB entity</param> /// <returns>True if the related DRB entity is found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public bool TryFindByTID(int TID, out DRB Value) { return Index_TID.Value.TryGetValue(TID, out Value); } /// <summary> /// Attempt to find DRB by TID field /// </summary> /// <param name="TID">TID value used to find DRB</param> /// <returns>Related DRB entity, or null if not found</returns> /// <exception cref="ArgumentOutOfRangeException">No match was found</exception> public DRB TryFindByTID(int TID) { DRB value; if (Index_TID.Value.TryGetValue(TID, out value)) { return value; } else { return null; } } #endregion #region SQL Integration /// <summary> /// Returns a <see cref="SqlCommand"/> which checks for the existence of a DRB table, and if not found, creates the table and associated indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> public override SqlCommand GetSqlCreateTableCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF NOT EXISTS (SELECT * FROM dbo.sysobjects WHERE id = OBJECT_ID(N'[dbo].[DRB]') AND OBJECTPROPERTY(id, N'IsUserTable') = 1) BEGIN CREATE TABLE [dbo].[DRB]( [TID] int IDENTITY NOT NULL, [DR_CODE] varchar(10) NOT NULL, [REFERENCE_NO] varchar(21) NULL, [CUST_REFERENCE] varchar(20) NULL, [RECORD_TYPE] varchar(2) NULL, [BILLER_CODE] varchar(10) NULL, [PAYMENT_TYPE] varchar(2) NULL, [AMOUNT] money NULL, [PAYMENT_DATE] datetime NULL, [DELETE_FLAG] varchar(1) NULL, [INVOICE_TID] int NULL, [LW_DATE] datetime NULL, [LW_TIME] smallint NULL, [LW_USER] varchar(128) NULL, CONSTRAINT [DRB_Index_TID] PRIMARY KEY NONCLUSTERED ( [TID] ASC ) ); CREATE CLUSTERED INDEX [DRB_Index_DR_CODE] ON [dbo].[DRB] ( [DR_CODE] ASC ); CREATE NONCLUSTERED INDEX [DRB_Index_REFERENCE_NO] ON [dbo].[DRB] ( [REFERENCE_NO] ASC ); END"); } /// <summary> /// Returns a <see cref="SqlCommand"/> which disables all non-clustered table indexes. /// Typically called before <see cref="SqlBulkCopy"/> to improve performance. /// <see cref="GetSqlRebuildIndexesCommand(SqlConnection)"/> should be called to rebuild and enable indexes after performance sensitive work is completed. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will disable all non-clustered table indexes</returns> public override SqlCommand GetSqlDisableIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[DRB]') AND name = N'DRB_Index_REFERENCE_NO') ALTER INDEX [DRB_Index_REFERENCE_NO] ON [dbo].[DRB] DISABLE; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[DRB]') AND name = N'DRB_Index_TID') ALTER INDEX [DRB_Index_TID] ON [dbo].[DRB] DISABLE; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which rebuilds and enables all non-clustered table indexes. /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <returns>A <see cref="SqlCommand"/> which (when executed) will rebuild and enable all non-clustered table indexes</returns> public override SqlCommand GetSqlRebuildIndexesCommand(SqlConnection SqlConnection) { return new SqlCommand( connection: SqlConnection, cmdText: @"IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[DRB]') AND name = N'DRB_Index_REFERENCE_NO') ALTER INDEX [DRB_Index_REFERENCE_NO] ON [dbo].[DRB] REBUILD PARTITION = ALL; IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = OBJECT_ID(N'[dbo].[DRB]') AND name = N'DRB_Index_TID') ALTER INDEX [DRB_Index_TID] ON [dbo].[DRB] REBUILD PARTITION = ALL; "); } /// <summary> /// Returns a <see cref="SqlCommand"/> which deletes the <see cref="DRB"/> entities passed /// </summary> /// <param name="SqlConnection">The <see cref="SqlConnection"/> to be associated with the <see cref="SqlCommand"/></param> /// <param name="Entities">The <see cref="DRB"/> entities to be deleted</param> public override SqlCommand GetSqlDeleteCommand(SqlConnection SqlConnection, IEnumerable<DRB> Entities) { SqlCommand command = new SqlCommand(); int parameterIndex = 0; StringBuilder builder = new StringBuilder(); List<int> Index_TID = new List<int>(); foreach (var entity in Entities) { Index_TID.Add(entity.TID); } builder.AppendLine("DELETE [dbo].[DRB] WHERE"); // Index_TID builder.Append("[TID] IN ("); for (int index = 0; index < Index_TID.Count; index++) { if (index != 0) builder.Append(", "); // TID var parameterTID = $"@p{parameterIndex++}"; builder.Append(parameterTID); command.Parameters.Add(parameterTID, SqlDbType.Int).Value = Index_TID[index]; } builder.Append(");"); command.Connection = SqlConnection; command.CommandText = builder.ToString(); return command; } /// <summary> /// Provides a <see cref="IDataReader"/> for the DRB data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the DRB data set</returns> public override EduHubDataSetDataReader<DRB> GetDataSetDataReader() { return new DRBDataReader(Load()); } /// <summary> /// Provides a <see cref="IDataReader"/> for the DRB data set /// </summary> /// <returns>A <see cref="IDataReader"/> for the DRB data set</returns> public override EduHubDataSetDataReader<DRB> GetDataSetDataReader(List<DRB> Entities) { return new DRBDataReader(new EduHubDataSetLoadedReader<DRB>(this, Entities)); } // Modest implementation to primarily support SqlBulkCopy private class DRBDataReader : EduHubDataSetDataReader<DRB> { public DRBDataReader(IEduHubDataSetReader<DRB> Reader) : base (Reader) { } public override int FieldCount { get { return 14; } } public override object GetValue(int i) { switch (i) { case 0: // TID return Current.TID; case 1: // DR_CODE return Current.DR_CODE; case 2: // REFERENCE_NO return Current.REFERENCE_NO; case 3: // CUST_REFERENCE return Current.CUST_REFERENCE; case 4: // RECORD_TYPE return Current.RECORD_TYPE; case 5: // BILLER_CODE return Current.BILLER_CODE; case 6: // PAYMENT_TYPE return Current.PAYMENT_TYPE; case 7: // AMOUNT return Current.AMOUNT; case 8: // PAYMENT_DATE return Current.PAYMENT_DATE; case 9: // DELETE_FLAG return Current.DELETE_FLAG; case 10: // INVOICE_TID return Current.INVOICE_TID; case 11: // LW_DATE return Current.LW_DATE; case 12: // LW_TIME return Current.LW_TIME; case 13: // LW_USER return Current.LW_USER; default: throw new ArgumentOutOfRangeException(nameof(i)); } } public override bool IsDBNull(int i) { switch (i) { case 2: // REFERENCE_NO return Current.REFERENCE_NO == null; case 3: // CUST_REFERENCE return Current.CUST_REFERENCE == null; case 4: // RECORD_TYPE return Current.RECORD_TYPE == null; case 5: // BILLER_CODE return Current.BILLER_CODE == null; case 6: // PAYMENT_TYPE return Current.PAYMENT_TYPE == null; case 7: // AMOUNT return Current.AMOUNT == null; case 8: // PAYMENT_DATE return Current.PAYMENT_DATE == null; case 9: // DELETE_FLAG return Current.DELETE_FLAG == null; case 10: // INVOICE_TID return Current.INVOICE_TID == null; case 11: // LW_DATE return Current.LW_DATE == null; case 12: // LW_TIME return Current.LW_TIME == null; case 13: // LW_USER return Current.LW_USER == null; default: return false; } } public override string GetName(int ordinal) { switch (ordinal) { case 0: // TID return "TID"; case 1: // DR_CODE return "DR_CODE"; case 2: // REFERENCE_NO return "REFERENCE_NO"; case 3: // CUST_REFERENCE return "CUST_REFERENCE"; case 4: // RECORD_TYPE return "RECORD_TYPE"; case 5: // BILLER_CODE return "BILLER_CODE"; case 6: // PAYMENT_TYPE return "PAYMENT_TYPE"; case 7: // AMOUNT return "AMOUNT"; case 8: // PAYMENT_DATE return "PAYMENT_DATE"; case 9: // DELETE_FLAG return "DELETE_FLAG"; case 10: // INVOICE_TID return "INVOICE_TID"; case 11: // LW_DATE return "LW_DATE"; case 12: // LW_TIME return "LW_TIME"; case 13: // LW_USER return "LW_USER"; default: throw new ArgumentOutOfRangeException(nameof(ordinal)); } } public override int GetOrdinal(string name) { switch (name) { case "TID": return 0; case "DR_CODE": return 1; case "REFERENCE_NO": return 2; case "CUST_REFERENCE": return 3; case "RECORD_TYPE": return 4; case "BILLER_CODE": return 5; case "PAYMENT_TYPE": return 6; case "AMOUNT": return 7; case "PAYMENT_DATE": return 8; case "DELETE_FLAG": return 9; case "INVOICE_TID": return 10; case "LW_DATE": return 11; case "LW_TIME": return 12; case "LW_USER": return 13; default: throw new ArgumentOutOfRangeException(nameof(name)); } } } #endregion } }
// 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.Build.Engine { using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text.RegularExpressions; using Microsoft.DocAsCode.Common; using Microsoft.DocAsCode.Build.Engine; using Microsoft.DocAsCode.Utility; public sealed class ArchiveResourceCollection : ResourceCollection { private ZipArchive _zipped; private bool disposed = false; public override string Name { get; } public override IEnumerable<string> Names { get; } public override bool IsEmpty { get; } public ArchiveResourceCollection(Stream stream, string name) { if (stream == null) throw new ArgumentNullException(nameof(stream)); _zipped = new ZipArchive(stream); Name = name; // When Name is empty, entry is folder, ignore Names = _zipped.Entries.Where(s => !string.IsNullOrEmpty(s.Name)).Select(s => s.FullName); IsEmpty = !Names.Any(); } /// <summary> /// TODO: This is not thread safe, only expose GetResource in interface /// </summary> /// <param name="name"></param> /// <returns></returns> public override Stream GetResourceStream(string name) { if (IsEmpty) return null; // zip entry is case sensitive // incase relative path is combined by backslash \ return _zipped.GetEntry(name.Trim().ToNormalizedPath())?.Open(); } protected override void Dispose(bool disposing) { if (disposed) return; _zipped?.Dispose(); _zipped = null; disposed = true; base.Dispose(disposing); } } public sealed class FileResourceCollection : ResourceCollection { private const int MaxSearchLevel = 5; // keep comparer to be case sensitive as to be consistent with zip entries private static StringComparer ResourceComparer = StringComparer.Ordinal; private string _directory = null; private readonly int _maxDepth; public override string Name { get; } public override IEnumerable<string> Names { get; } public override bool IsEmpty { get; } public FileResourceCollection(string directory, int maxSearchLevel = MaxSearchLevel) { if (string.IsNullOrEmpty(directory)) _directory = Environment.CurrentDirectory; else _directory = directory; Name = _directory; _maxDepth = maxSearchLevel; var includedFiles = GetFiles(_directory, "*", maxSearchLevel); Names = includedFiles.Select(s => PathUtility.MakeRelativePath(_directory, s)).Where(s => s != null); IsEmpty = !Names.Any(); } public override Stream GetResourceStream(string name) { if (IsEmpty) return null; // incase relative path is combined by backslash \ if (!Names.Contains(name.Trim().ToNormalizedPath(), ResourceComparer)) return null; var filePath = Path.Combine(_directory, name); return new FileStream(filePath, FileMode.Open, FileAccess.Read); } private IEnumerable<string> GetFiles(string directory, string searchPattern, int searchLevel) { if (searchLevel < 1) { return Enumerable.Empty<string>(); } var files = Directory.GetFiles(directory, searchPattern, SearchOption.TopDirectoryOnly); var dirs = Directory.GetDirectories(directory); if (searchLevel == 1) { foreach (var dir in dirs) { var remainingFiles = Directory.GetFiles(dir, searchPattern, SearchOption.AllDirectories); if (remainingFiles.Length > 0) { throw new ResourceFileExceedsMaxDepthException(_maxDepth, PathUtility.MakeRelativePath(_directory, remainingFiles[0]), Name); } } return files; } List<string> allFiles = new List<string>(files); foreach(var dir in dirs) { allFiles.AddRange(GetFiles(dir, searchPattern, searchLevel - 1)); } return allFiles; } } public sealed class CompositeResourceCollectionWithOverridden : ResourceCollection { private ResourceCollection[] _collectionsInOverriddenOrder = null; private bool disposed = false; public override string Name => "Composite"; public override IEnumerable<string> Names { get; } public override bool IsEmpty { get; } public CompositeResourceCollectionWithOverridden(IEnumerable<ResourceCollection> collectionsInOverriddenOrder) { if (collectionsInOverriddenOrder == null || !collectionsInOverriddenOrder.Any()) { IsEmpty = true; } else { _collectionsInOverriddenOrder = collectionsInOverriddenOrder.ToArray(); Names = _collectionsInOverriddenOrder.SelectMany(s => s.Names).Distinct(); } } public override Stream GetResourceStream(string name) { if (IsEmpty) return null; for (int i = _collectionsInOverriddenOrder.Length - 1; i > -1; i--) { var stream = _collectionsInOverriddenOrder[i].GetResourceStream(name); if (stream != null) { Logger.LogVerbose($"Resource \"{name}\" is found from \"{_collectionsInOverriddenOrder[i].Name}\""); return stream; } } return null; } protected override void Dispose(bool disposing) { if (disposed) return; if (_collectionsInOverriddenOrder != null) { for (int i = 0; i < _collectionsInOverriddenOrder.Length; i++) { _collectionsInOverriddenOrder[i].Dispose(); _collectionsInOverriddenOrder[i] = null; } _collectionsInOverriddenOrder = null; } base.Dispose(disposing); } } public sealed class EmptyResourceCollection : ResourceCollection { private static readonly IEnumerable<string> Empty = new string[0]; public override bool IsEmpty => true; public override string Name => "Empty"; public override IEnumerable<string> Names => Empty; public override Stream GetResourceStream(string name) { return Stream.Null; } } public abstract class ResourceCollection : IDisposable { public abstract string Name { get; } public abstract bool IsEmpty { get; } public abstract IEnumerable<string> Names { get; } public string GetResource(string name) { using (var stream = GetResourceStream(name)) return GetString(stream); } public IEnumerable<KeyValuePair<string, string>> GetResources(string selector = null) { foreach(var pair in GetResourceStreams(selector)) { using (pair.Value) { yield return new KeyValuePair<string, string>(pair.Key, GetString(pair.Value)); } } } public IEnumerable<KeyValuePair<string, Stream>> GetResourceStreams(string selector = null) { Func<string, bool> filter = s => { if (selector != null) { var regex = new Regex(selector, RegexOptions.IgnoreCase); return regex.IsMatch(s); } else { return true; } }; foreach (var name in Names) { if (filter(name)) { yield return new KeyValuePair<string, Stream>(name, GetResourceStream(name)); } } } public abstract Stream GetResourceStream(string name); public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { } /// <summary> /// Override Object.Finalize by defining a destructor /// </summary> ~ResourceCollection() { Dispose(false); } private static string GetString(Stream stream) { if (stream == null) return null; using (var reader = new StreamReader(stream)) { return reader.ReadToEnd(); } } } }
#region License // Copyright (c) 2007-2009, Sean Chambers <schambers80@gmail.com> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.IO; using System.Text; using FluentMigrator.Console; using NUnit.Framework; using NUnit.Should; namespace FluentMigrator.Tests.Unit.Runners { [TestFixture] public class MigratorConsoleTests { private string database = "Sqlite"; private string connection = "Data Source=:memory:;Version=3;New=True;"; private string target = "FluentMigrator.Tests.dll"; [Test] [Category("NotWorkingOnMono")] public void CanInitMigratorConsoleWithValidArguments() { var console = new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/namespace", "FluentMigrator.Tests.Integration.Migrations", "/nested", "/task", "migrate:up", "/version", "1"); console.Connection.ShouldBe(connection); console.Namespace.ShouldBe("FluentMigrator.Tests.Integration.Migrations"); console.NestedNamespaces.ShouldBeTrue(); console.Task.ShouldBe("migrate:up"); console.Version.ShouldBe(1); } [Test] [Category("NotWorkingOnMono")] public void ConsoleAnnouncerHasMoreOutputWhenVerbose() { var sbNonVerbose = new StringBuilder(); var stringWriterNonVerbose = new StringWriter(sbNonVerbose); System.Console.SetOut(stringWriterNonVerbose); new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/namespace", "FluentMigrator.Tests.Integration.Migrations", "/task", "migrate:up", "/version", "1"); var sbVerbose = new StringBuilder(); var stringWriterVerbose = new StringWriter(sbVerbose); System.Console.SetOut(stringWriterVerbose); new MigratorConsole( "/db", database, "/connection", connection, "/verbose", "1", "/target", target, "/namespace", "FluentMigrator.Tests.Integration.Migrations", "/task", "migrate:up", "/version", "1"); Assert.Greater(sbVerbose.ToString().Length, sbNonVerbose.ToString().Length); } [Test] public void ConsoleAnnouncerHasOutput() { var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); System.Console.SetOut(stringWriter); new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations", "/task", "migrate:up", "/version", "0"); var output = sb.ToString(); Assert.AreNotEqual(0, output.Length); } [Test] [Category("NotWorkingOnMono")] public void ConsoleAnnouncerHasOutputEvenIfMarkedAsPreviewOnly() { var sb = new StringBuilder(); var stringWriter = new StringWriter(sb); System.Console.SetOut(stringWriter); new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations", "/verbose", "/task", "migrate:up", "/preview"); var output = sb.ToString(); Assert.That(output.Contains("PREVIEW-ONLY MODE")); Assert.AreNotEqual(0, output.Length); } [Test] public void FileAnnouncerHasOutputToDefaultOutputFile() { var outputFileName = target + ".sql"; if (File.Exists(outputFileName)) File.Delete(outputFileName); Assert.IsFalse(File.Exists(outputFileName)); new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/output", "/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations", "/task", "migrate:up", "/version", "0"); Assert.IsTrue(File.Exists(outputFileName)); File.Delete(outputFileName); } [Test] public void FileAnnouncerHasOutputToSpecifiedOutputFile() { var outputFileName = "output.sql"; if (File.Exists(outputFileName)) File.Delete(outputFileName); Assert.IsFalse(File.Exists(outputFileName)); new MigratorConsole( "/db", database, "/connection", connection, "/target", target, "/output", "/outputFilename", outputFileName, "/namespace", "FluentMigrator.Tests.Unit.Runners.Migrations", "/task", "migrate:up", "/version", "0"); Assert.IsTrue(File.Exists(outputFileName)); File.Delete(outputFileName); } [Test] public void MustInitializeConsoleWithConnectionArgument() { new MigratorConsole("/db", database); Assert.That(Environment.ExitCode == 1); } [Test] public void MustInitializeConsoleWithDatabaseArgument() { new MigratorConsole("/connection", connection); Assert.That(Environment.ExitCode == 1); } [Test, Ignore("implement this test")] public void OrderOfConsoleArgumentsShouldNotMatter() { } [Test] public void TagsPassedToRunnerContextOnExecuteMigrations() { var migratorConsole = new MigratorConsole( "/db", database, "/connection", connection, "/verbose", "1", "/target", target, "/namespace", "FluentMigrator.Tests.Integration.Migrations", "/task", "migrate:up", "/version", "1", "/tag", "uk", "/tag", "production"); var expectedTags = new string[] { "uk", "production" }; CollectionAssert.AreEquivalent(expectedTags, migratorConsole.RunnerContext.Tags); } } }
/******************************************************************************* INTEL CORPORATION PROPRIETARY INFORMATION This software is supplied under the terms of a license agreement or nondisclosure agreement with Intel Corporation and may not be copied or disclosed except in accordance with the terms of that agreement Copyright(c) 2012-2014 Intel Corporation. All Rights Reserved. *******************************************************************************/ using UnityEngine; using System.Collections; namespace RSUnityToolkit { /// <summary> /// Face tracking rule - Process Track triggers /// </summary> [TrackTrigger.TrackTriggerAtt] [AddComponentMenu("")] public class FaceTrackingRule : BaseRule { #region Public Fields /// <summary> /// The landmark to track. (in the group) /// </summary> public PXCMFaceData.LandmarkType LandmarkToTrack = PXCMFaceData.LandmarkType.LANDMARK_NOSE_TIP; /// <summary> /// The real world box center. In centimiters. /// </summary> public Vector3 RealWorldBoxCenter = new Vector3(0, 0, 50); /// <summary> /// The real world box dimensions. In Centimiters. /// </summary> public Vector3 RealWorldBoxDimensions = new Vector3(100, 100, 100); /// <summary> /// The index of the face. /// </summary> public int FaceIndex = 0; #endregion #region Private Fields #endregion #region C'tors public FaceTrackingRule(): base() { FriendlyName = "Face Tracking"; } #endregion #region Public Methods override public string GetIconPath() { return @"RulesIcons/face-tracking"; } protected override bool OnRuleEnabled() { SenseToolkitManager.Instance.SetSenseOption(SenseOption.SenseOptionID.Face); return true; } protected override void OnRuleDisabled() { SenseToolkitManager.Instance.UnsetSenseOption(SenseOption.SenseOptionID.Face); } override public string GetRuleDescription() { return "Tracks face landmark's position and orientation"; } public override bool Process(Trigger trigger) { trigger.ErrorDetected = false; if (!SenseToolkitManager.Instance.IsSenseOptionSet(SenseOption.SenseOptionID.Face)) { trigger.ErrorDetected = true; return false; } if (!(trigger is TrackTrigger)) { trigger.ErrorDetected = true; return false; } bool success = false; // make sure we have valid values if (RealWorldBoxDimensions.x <= 0) { RealWorldBoxDimensions.x = 1; } if (RealWorldBoxDimensions.y <= 0) { RealWorldBoxDimensions.y = 1; } if (RealWorldBoxDimensions.z <= 0) { RealWorldBoxDimensions.z = 1; } if (SenseToolkitManager.Instance.Initialized && SenseToolkitManager.Instance.FaceModuleOutput != null) { if (SenseToolkitManager.Instance.FaceModuleOutput.QueryNumberOfDetectedFaces() == 0) { return false; } PXCMFaceData.Face singleFaceOutput = null; singleFaceOutput = SenseToolkitManager.Instance.FaceModuleOutput.QueryFaceByIndex(FaceIndex); if (singleFaceOutput != null && singleFaceOutput.QueryUserID() >= 0) { // Process Tracking if (trigger is TrackTrigger) { TrackTrigger specificTrigger = (TrackTrigger)trigger; var landmarksData = singleFaceOutput.QueryLandmarks(); if (landmarksData == null) { return false; } int landmarkId = landmarksData.QueryPointIndex(LandmarkToTrack); PXCMFaceData.LandmarkPoint point = null; landmarksData.QueryPoint(landmarkId, out point); // Translation if (point != null) { Vector3 vec = new Vector3(); vec.x = point.world.x * 100; vec.y = point.world.y * 100; vec.z = point.world.z * 100; if ( vec.x + vec.y + vec.z == 0) { return false; } // Clamp and normalize to the Real World Box TrackingUtilityClass.ClampToRealWorldInputBox(ref vec, RealWorldBoxCenter, RealWorldBoxDimensions); TrackingUtilityClass.Normalize(ref vec, RealWorldBoxCenter, RealWorldBoxDimensions); if (!float.IsNaN(vec.x) && !float.IsNaN(vec.y) && !float.IsNaN(vec.z)) { specificTrigger.Position = vec; success = true; } } //Rotation PXCMFaceData.PoseData poseData = singleFaceOutput.QueryPose(); if (poseData != null) { PXCMFaceData.PoseEulerAngles angles; if (poseData.QueryPoseAngles(out angles)) { if (!float.IsNaN(angles.pitch) && !float.IsNaN(angles.yaw) && !float.IsNaN(angles.roll)) { Quaternion q = Quaternion.Euler(-angles.pitch, angles.yaw, -angles.roll); specificTrigger.RotationQuaternion = q; success = true; } } } } } return success; } return success; } #endregion } }
//TODO: //"The first index of a file must start at 00:00:00" - if this isnt the case, we'll be doing nonsense for sure. so catch it //Recover the idea of TOCPoints maybe, as it's a more flexible way of generating the structure. //TODO //check for flags changing after a PREGAP is processed. the PREGAP can't correctly run if the flags aren't set //IN GENERAL: validate more pedantically (but that code gets in the way majorly) // - perhaps isolate validation checks into a different pass distinct from a Burn pass //NEW IDEA: //a cue file is a compressed representation of a more verbose format which is easier to understand //most fundamentally, it is organized with TRACK and INDEX commands alternating. //these should be flattened into individual records with CURRTRACK and CURRINDEX fields. //more generally, it's organized with 'register' settings and INDEX commands alternating. //whenever an INDEX command is received from the cue file, individual flattened records are written with the current 'register' settings //and an incrementing timestamp until the INDEX command appears (or the EOF happens) //PREGAP commands are special : at the moment it is received, emit flat records with a different pregap structure //POSTGAP commands are special : TBD using System; using System.Linq; using System.Text; using System.IO; using System.Collections.Generic; namespace BizHawk.Emulation.DiscSystem.CUE { /// <summary> /// Loads a cue file into a Disc. /// For this job, virtually all nonsense input is treated as errors, but the process will try to recover as best it can. /// The user should still reject any jobs which generated errors /// </summary> internal class LoadCueJob : DiscJob { /// <summary> /// The results of the compile job, a prerequisite for this /// </summary> public CompileCueJob IN_CompileJob; /// <summary> /// The resulting disc /// </summary> public Disc OUT_Disc; private enum BurnType { Normal, Pregap, Postgap } class BlobInfo { public IBlob Blob; public long Length; } //not sure if we need this... class TrackInfo { public int Length; public CompiledCueTrack CompiledCueTrack; } List<BlobInfo> BlobInfos; List<TrackInfo> TrackInfos = new List<TrackInfo>(); void MountBlobs() { IBlob file_blob = null; BlobInfos = new List<BlobInfo>(); foreach (var ccf in IN_CompileJob.OUT_CompiledCueFiles) { var bi = new BlobInfo(); BlobInfos.Add(bi); switch (ccf.Type) { case CompiledCueFileType.BIN: case CompiledCueFileType.Unknown: { //raw files: var blob = new Disc.Blob_RawFile { PhysicalPath = ccf.FullPath }; OUT_Disc.DisposableResources.Add(file_blob = blob); bi.Length = blob.Length; break; } case CompiledCueFileType.ECM: { var blob = new Disc.Blob_ECM(); OUT_Disc.DisposableResources.Add(file_blob = blob); blob.Load(ccf.FullPath); bi.Length = blob.Length; break; } case CompiledCueFileType.WAVE: { var blob = new Disc.Blob_WaveFile(); OUT_Disc.DisposableResources.Add(file_blob = blob); blob.Load(ccf.FullPath); bi.Length = blob.Length; break; } case CompiledCueFileType.DecodeAudio: { FFMpeg ffmpeg = new FFMpeg(); if (!ffmpeg.QueryServiceAvailable()) { throw new DiscReferenceException(ccf.FullPath, "No decoding service was available (make sure ffmpeg.exe is available. even though this may be a wav, ffmpeg is used to load oddly formatted wave files. If you object to this, please send us a note and we'll see what we can do. It shouldn't be too hard.)"); } AudioDecoder dec = new AudioDecoder(); byte[] buf = dec.AcquireWaveData(ccf.FullPath); var blob = new Disc.Blob_WaveFile(); OUT_Disc.DisposableResources.Add(file_blob = blob); blob.Load(new MemoryStream(buf)); bi.Length = buf.Length; break; } default: throw new InvalidOperationException(); } //switch(file type) //wrap all the blobs with zero padding bi.Blob = new Disc.Blob_ZeroPadAdapter(file_blob, bi.Length); } } void AnalyzeTracks() { var compiledTracks = IN_CompileJob.OUT_CompiledCueTracks; for(int t=0;t<compiledTracks.Count;t++) { var cct = compiledTracks[t]; var ti = new TrackInfo() { CompiledCueTrack = cct }; TrackInfos.Add(ti); //OH NO! CANT DO THIS! //need to read sectors from file to reliably know its ending size. //could determine it from file mode. //do we really need this? //if (cct.IsFinalInFile) //{ // //length is determined from length of file //} } } void EmitRawTOCEntry(CompiledCueTrack cct) { SubchannelQ toc_sq = new SubchannelQ(); //absent some kind of policy for how to set it, this is a safe assumption: byte toc_ADR = 1; toc_sq.SetStatus(toc_ADR, (EControlQ)(int)cct.Flags); toc_sq.q_tno.BCDValue = 0; //kind of a little weird here.. the track number becomes the 'point' and put in the index instead. 0 is the track number here. toc_sq.q_index = BCD2.FromDecimal(cct.Number); //not too sure about these yet toc_sq.min = BCD2.FromDecimal(0); toc_sq.sec = BCD2.FromDecimal(0); toc_sq.frame = BCD2.FromDecimal(0); toc_sq.AP_Timestamp = OUT_Disc._Sectors.Count; OUT_Disc.RawTOCEntries.Add(new RawTOCEntry { QData = toc_sq }); } public void Run() { //params var compiled = IN_CompileJob; var context = compiled.IN_CueContext; OUT_Disc = new Disc(); //generation state int curr_index; int curr_blobIndex = -1; int curr_blobMSF = -1; BlobInfo curr_blobInfo = null; long curr_blobOffset = -1; //mount all input files MountBlobs(); //unhappily, we cannot determine the length of all the tracks without knowing the length of the files //now that the files are mounted, we can figure the track lengths AnalyzeTracks(); //loop from track 1 to 99 //(track 0 isnt handled yet, that's way distant work) for (int t = 1; t < TrackInfos.Count; t++) { TrackInfo ti = TrackInfos[t]; CompiledCueTrack cct = ti.CompiledCueTrack; //--------------------------------- //setup track pregap processing //per "Example 05" on digitalx.org, pregap can come from index specification and pregap command int specifiedPregapLength = cct.PregapLength.Sector; int impliedPregapLength = cct.Indexes[1].FileMSF.Sector - cct.Indexes[0].FileMSF.Sector; int totalPregapLength = specifiedPregapLength + impliedPregapLength; //from now on we'll track relative timestamp and increment it continually int relMSF = -totalPregapLength; //read more at policies declaration //if (!context.DiscMountPolicy.CUE_PauseContradictionModeA) // relMSF += 1; //--------------------------------- //--------------------------------- //generate sectors for this track. //advance to the next file if needed if (curr_blobIndex != cct.BlobIndex) { curr_blobIndex = cct.BlobIndex; curr_blobOffset = 0; curr_blobMSF = 0; curr_blobInfo = BlobInfos[curr_blobIndex]; } //work until the next track is reached, or the end of the current file is reached, depending on the track type curr_index = 0; for (; ; ) { bool trackDone = false; bool generateGap = false; if (specifiedPregapLength > 0) { //if burning through a specified pregap, count it down generateGap = true; specifiedPregapLength--; } else { //if burning through the file, select the appropriate index by inspecting the next index and seeing if we've reached it for (; ; ) { if (curr_index == cct.Indexes.Count - 1) break; if (curr_blobMSF >= cct.Indexes[curr_index + 1].FileMSF.Sector) { curr_index++; if (curr_index == 1) { //WE ARE NOW AT INDEX 1: generate the RawTOCEntry for this track EmitRawTOCEntry(cct); } } else break; } } //select the track type for the subQ //it's obviously the same as the main track type usually, but during a pregap it can be different TrackInfo qTrack = ti; int qRelMSF = relMSF; if (curr_index == 0) { //tweak relMSF due to ambiguity/contradiction in yellowbook docs if (!context.DiscMountPolicy.CUE_PregapContradictionModeA) qRelMSF++; //[IEC10149] says there's two "intervals" of a pregap. //mednafen's pseudocode interpretation of this: //if this is a data track and the previous track was not data, the last 150 sectors of the pregap match this track and the earlier sectors (at least 75) math the previous track //I agree, so let's do it that way if (t != 1 && cct.TrackType != CueTrackType.Audio && TrackInfos[t - 1].CompiledCueTrack.TrackType == CueTrackType.Audio) { if (relMSF < -150) { qTrack = TrackInfos[t - 1]; } } } //generate the right kind of sector synth for this track SS_Base ss = null; if (generateGap) { var ss_gap = new SS_Gap(); ss_gap.TrackType = qTrack.CompiledCueTrack.TrackType; ss = ss_gap; } else { int sectorSize = int.MaxValue; switch (qTrack.CompiledCueTrack.TrackType) { case CueTrackType.Audio: case CueTrackType.CDI_2352: case CueTrackType.Mode1_2352: case CueTrackType.Mode2_2352: ss = new SS_2352(); sectorSize = 2352; break; case CueTrackType.Mode1_2048: ss = new SS_Mode1_2048(); sectorSize = 2048; break; default: case CueTrackType.Mode2_2336: throw new InvalidOperationException("Not supported: " + cct.TrackType); } ss.Blob = curr_blobInfo.Blob; ss.BlobOffset = curr_blobOffset; curr_blobOffset += sectorSize; curr_blobMSF++; } ss.Policy = context.DiscMountPolicy; //setup subQ byte ADR = 1; //absent some kind of policy for how to set it, this is a safe assumption: ss.sq.SetStatus(ADR, (EControlQ)(int)qTrack.CompiledCueTrack.Flags); ss.sq.q_tno = BCD2.FromDecimal(cct.Number); ss.sq.q_index = BCD2.FromDecimal(curr_index); ss.sq.AP_Timestamp = OUT_Disc._Sectors.Count; ss.sq.Timestamp = qRelMSF; //setup subP if (curr_index == 0) ss.Pause = true; OUT_Disc._Sectors.Add(ss); relMSF++; if (cct.IsFinalInFile) { //sometimes, break when the file is exhausted if (curr_blobOffset >= curr_blobInfo.Length) trackDone = true; } else { //other times, break when the track is done //(this check is safe because it's not the final track overall if it's not the final track in a file) if (curr_blobMSF >= TrackInfos[t + 1].CompiledCueTrack.Indexes[0].FileMSF.Sector) trackDone = true; } if (trackDone) break; } //--------------------------------- //gen postgap sectors int specifiedPostgapLength = cct.PostgapLength.Sector; for (int s = 0; s < specifiedPostgapLength; s++) { var ss = new SS_Gap(); ss.TrackType = cct.TrackType; //TODO - old track type in some < -150 cases? //-subq- byte ADR = 1; ss.sq.SetStatus(ADR, (EControlQ)(int)cct.Flags); ss.sq.q_tno = BCD2.FromDecimal(cct.Number); ss.sq.q_index = BCD2.FromDecimal(curr_index); ss.sq.AP_Timestamp = OUT_Disc._Sectors.Count; ss.sq.Timestamp = relMSF; //-subP- //always paused--is this good enough? ss.Pause = true; OUT_Disc._Sectors.Add(ss); relMSF++; } } //end track loop //add RawTOCEntries A0 A1 A2 to round out the TOC var TOCMiscInfo = new Synthesize_A0A1A2_Job { IN_FirstRecordedTrackNumber = IN_CompileJob.OUT_CompiledDiscInfo.FirstRecordedTrackNumber, IN_LastRecordedTrackNumber = IN_CompileJob.OUT_CompiledDiscInfo.LastRecordedTrackNumber, IN_Session1Format = IN_CompileJob.OUT_CompiledDiscInfo.SessionFormat, IN_LeadoutTimestamp = OUT_Disc._Sectors.Count }; TOCMiscInfo.Run(OUT_Disc.RawTOCEntries); //TODO - generate leadout, or delegates at least //blech, old crap, maybe //OUT_Disc.Structure.Synthesize_TOCPointsFromSessions(); //FinishLog(); } //Run() } //class LoadCueJob } //namespace BizHawk.Emulation.DiscSystem
// // Copyright (c) 2004-2011 Jaroslaw Kowalski <jaak@jkowalski.net> // // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions // are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of Jaroslaw Kowalski nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE // ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE // LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR // CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF // SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS // INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN // CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) // ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF // THE POSSIBILITY OF SUCH DAMAGE. // using JetBrains.Annotations; #if !SILVERLIGHT namespace NLog.Targets { using System; using System.Collections.Generic; using System.ComponentModel; using System.Net; using System.Net.Mail; using System.Text; using System.IO; using NLog.Common; using NLog.Config; using NLog.Internal; using NLog.Layouts; /// <summary> /// Sends log messages by email using SMTP protocol. /// </summary> /// <seealso href="https://github.com/nlog/nlog/wiki/Mail-target">Documentation on NLog Wiki</seealso> /// <example> /// <p> /// To set up the target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Mail/Simple/NLog.config" /> /// <p> /// This assumes just one target and a single rule. More configuration /// options are described <a href="config.html">here</a>. /// </p> /// <p> /// To set up the log target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Mail/Simple/Example.cs" /> /// <p> /// Mail target works best when used with BufferingWrapper target /// which lets you send multiple log messages in single mail /// </p> /// <p> /// To set up the buffered mail target in the <a href="config.html">configuration file</a>, /// use the following syntax: /// </p> /// <code lang="XML" source="examples/targets/Configuration File/Mail/Buffered/NLog.config" /> /// <p> /// To set up the buffered mail target programmatically use code like this: /// </p> /// <code lang="C#" source="examples/targets/Configuration API/Mail/Buffered/Example.cs" /> /// </example> [Target("Mail")] public class MailTarget : TargetWithLayoutHeaderAndFooter { private const string RequiredPropertyIsEmptyFormat = "After the processing of the MailTarget's '{0}' property it appears to be empty. The email message will not be sent."; /// <summary> /// Initializes a new instance of the <see cref="MailTarget" /> class. /// </summary> /// <remarks> /// The default value of the layout is: <code>${longdate}|${level:uppercase=true}|${logger}|${message}</code> /// </remarks> [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA2214:DoNotCallOverridableMethodsInConstructors", Justification = "This one is safe.")] public MailTarget() { this.Body = "${message}${newline}"; this.Subject = "Message from NLog on ${machinename}"; this.Encoding = Encoding.UTF8; this.SmtpPort = 25; this.SmtpAuthentication = SmtpAuthenticationMode.None; this.Timeout = 10000; } /// <summary> /// Gets or sets sender's email address (e.g. joe@domain.com). /// </summary> /// <docgen category='Message Options' order='10' /> [RequiredParameter] public Layout From { get; set; } /// <summary> /// Gets or sets recipients' email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). /// </summary> /// <docgen category='Message Options' order='11' /> [RequiredParameter] public Layout To { get; set; } /// <summary> /// Gets or sets CC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). /// </summary> /// <docgen category='Message Options' order='12' /> public Layout CC { get; set; } /// <summary> /// Gets or sets BCC email addresses separated by semicolons (e.g. john@domain.com;jane@domain.com). /// </summary> /// <docgen category='Message Options' order='13' /> public Layout Bcc { get; set; } /// <summary> /// Gets or sets a value indicating whether to add new lines between log entries. /// </summary> /// <value>A value of <c>true</c> if new lines should be added; otherwise, <c>false</c>.</value> /// <docgen category='Layout Options' order='99' /> public bool AddNewLines { get; set; } /// <summary> /// Gets or sets the mail subject. /// </summary> /// <docgen category='Message Options' order='5' /> [DefaultValue("Message from NLog on ${machinename}")] [RequiredParameter] public Layout Subject { get; set; } /// <summary> /// Gets or sets mail message body (repeated for each log message send in one mail). /// </summary> /// <remarks>Alias for the <c>Layout</c> property.</remarks> /// <docgen category='Message Options' order='6' /> [DefaultValue("${message}${newline}")] public Layout Body { get { return this.Layout; } set { this.Layout = value; } } /// <summary> /// Gets or sets encoding to be used for sending e-mail. /// </summary> /// <docgen category='Layout Options' order='20' /> [DefaultValue("UTF8")] public Encoding Encoding { get; set; } /// <summary> /// Gets or sets a value indicating whether to send message as HTML instead of plain text. /// </summary> /// <docgen category='Layout Options' order='11' /> [DefaultValue(false)] public bool Html { get; set; } /// <summary> /// Gets or sets SMTP Server to be used for sending. /// </summary> /// <docgen category='SMTP Options' order='10' /> public Layout SmtpServer { get; set; } /// <summary> /// Gets or sets SMTP Authentication mode. /// </summary> /// <docgen category='SMTP Options' order='11' /> [DefaultValue("None")] public SmtpAuthenticationMode SmtpAuthentication { get; set; } /// <summary> /// Gets or sets the username used to connect to SMTP server (used when SmtpAuthentication is set to "basic"). /// </summary> /// <docgen category='SMTP Options' order='12' /> public Layout SmtpUserName { get; set; } /// <summary> /// Gets or sets the password used to authenticate against SMTP server (used when SmtpAuthentication is set to "basic"). /// </summary> /// <docgen category='SMTP Options' order='13' /> public Layout SmtpPassword { get; set; } /// <summary> /// Gets or sets a value indicating whether SSL (secure sockets layer) should be used when communicating with SMTP server. /// </summary> /// <docgen category='SMTP Options' order='14' />. [DefaultValue(false)] public bool EnableSsl { get; set; } /// <summary> /// Gets or sets the port number that SMTP Server is listening on. /// </summary> /// <docgen category='SMTP Options' order='15' /> [DefaultValue(25)] public int SmtpPort { get; set; } /// <summary> /// Gets or sets a value indicating whether the default Settings from System.Net.MailSettings should be used. /// </summary> /// <docgen category='SMTP Options' order='16' /> [DefaultValue(false)] public bool UseSystemNetMailSettings { get; set; } /// <summary> /// Specifies how outgoing email messages will be handled. /// </summary> /// <docgen category='SMTP Options' order='18' /> [DefaultValue(SmtpDeliveryMethod.Network)] public SmtpDeliveryMethod DeliveryMethod { get; set; } /// <summary> /// Gets or sets the folder where applications save mail messages to be processed by the local SMTP server. /// </summary> /// <docgen category='SMTP Options' order='17' /> [DefaultValue(null)] public string PickupDirectoryLocation { get; set; } /// <summary> /// Gets or sets the priority used for sending mails. /// </summary> public Layout Priority { get; set; } /// <summary> /// Gets or sets a value indicating whether NewLine characters in the body should be replaced with <br/> tags. /// </summary> /// <remarks>Only happens when <see cref="Html"/> is set to true.</remarks> [DefaultValue(false)] public bool ReplaceNewlineWithBrTagInHtml { get; set; } /// <summary> /// Gets or sets a value indicating the SMTP client timeout. /// </summary> /// <remarks>Warning: zero is not infinit waiting</remarks> [DefaultValue(10000)] public int Timeout { get; set; } [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2000:Dispose objects before losing scope", Justification = "This is a factory method.")] internal virtual ISmtpClient CreateSmtpClient() { return new MySmtpClient(); } /// <summary> /// Renders the logging event message and adds it to the internal ArrayList of log messages. /// </summary> /// <param name="logEvent">The logging event.</param> protected override void Write(AsyncLogEventInfo logEvent) { this.Write(new[] { logEvent }); } /// <summary> /// Renders an array logging events. /// </summary> /// <param name="logEvents">Array of logging events.</param> protected override void Write(AsyncLogEventInfo[] logEvents) { foreach (var bucket in logEvents.BucketSort(c => this.GetSmtpSettingsKey(c.LogEvent))) { var eventInfos = bucket.Value; this.ProcessSingleMailMessage(eventInfos); } } /// <summary> /// Initializes the target. Can be used by inheriting classes /// to initialize logging. /// </summary> protected override void InitializeTarget() { CheckRequiredParameters(); base.InitializeTarget(); } /// <summary> /// Create mail and send with SMTP /// </summary> /// <param name="events">event printed in the body of the event</param> private void ProcessSingleMailMessage([NotNull] List<AsyncLogEventInfo> events) { try { if (events.Count == 0) { throw new NLogRuntimeException("We need at least one event."); } LogEventInfo firstEvent = events[0].LogEvent; LogEventInfo lastEvent = events[events.Count - 1].LogEvent; // unbuffered case, create a local buffer, append header, body and footer var bodyBuffer = CreateBodyBuffer(events, firstEvent, lastEvent); using (var msg = CreateMailMessage(lastEvent, bodyBuffer.ToString())) { using (ISmtpClient client = this.CreateSmtpClient()) { if (!UseSystemNetMailSettings) ConfigureMailClient(lastEvent, client); InternalLogger.Debug("Sending mail to {0} using {1}:{2} (ssl={3})", msg.To, client.Host, client.Port, client.EnableSsl); InternalLogger.Trace(" Subject: '{0}'", msg.Subject); InternalLogger.Trace(" From: '{0}'", msg.From.ToString()); client.Send(msg); foreach (var ev in events) { ev.Continuation(null); } } } } catch (Exception exception) { //always log InternalLogger.Error(exception, "Error sending mail."); if (exception.MustBeRethrown()) { throw; } foreach (var ev in events) { ev.Continuation(exception); } } } /// <summary> /// Create buffer for body /// </summary> /// <param name="events">all events</param> /// <param name="firstEvent">first event for header</param> /// <param name="lastEvent">last event for footer</param> /// <returns></returns> private StringBuilder CreateBodyBuffer(IEnumerable<AsyncLogEventInfo> events, LogEventInfo firstEvent, LogEventInfo lastEvent) { var bodyBuffer = new StringBuilder(); if (this.Header != null) { bodyBuffer.Append(this.Header.Render(firstEvent)); if (this.AddNewLines) { bodyBuffer.Append("\n"); } } foreach (AsyncLogEventInfo eventInfo in events) { bodyBuffer.Append(this.Layout.Render(eventInfo.LogEvent)); if (this.AddNewLines) { bodyBuffer.Append("\n"); } } if (this.Footer != null) { bodyBuffer.Append(this.Footer.Render(lastEvent)); if (this.AddNewLines) { bodyBuffer.Append("\n"); } } return bodyBuffer; } /// <summary> /// Set properties of <paramref name="client"/> /// </summary> /// <param name="lastEvent">last event for username/password</param> /// <param name="client">client to set properties on</param> internal void ConfigureMailClient(LogEventInfo lastEvent, ISmtpClient client) { CheckRequiredParameters(); if (this.SmtpServer == null && string.IsNullOrEmpty(this.PickupDirectoryLocation)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer/PickupDirectoryLocation")); } if (this.DeliveryMethod == SmtpDeliveryMethod.Network && this.SmtpServer == null) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer")); } if (this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory && string.IsNullOrEmpty(this.PickupDirectoryLocation)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "PickupDirectoryLocation")); } if (this.SmtpServer != null && this.DeliveryMethod == SmtpDeliveryMethod.Network) { var renderedSmtpServer = this.SmtpServer.Render(lastEvent); if (string.IsNullOrEmpty(renderedSmtpServer)) { throw new NLogRuntimeException(string.Format(RequiredPropertyIsEmptyFormat, "SmtpServer" )); } client.Host = renderedSmtpServer; client.Port = this.SmtpPort; client.EnableSsl = this.EnableSsl; if (this.SmtpAuthentication == SmtpAuthenticationMode.Ntlm) { InternalLogger.Trace(" Using NTLM authentication."); client.Credentials = CredentialCache.DefaultNetworkCredentials; } else if (this.SmtpAuthentication == SmtpAuthenticationMode.Basic) { string username = this.SmtpUserName.Render(lastEvent); string password = this.SmtpPassword.Render(lastEvent); InternalLogger.Trace(" Using basic authentication: Username='{0}' Password='{1}'", username, new string('*', password.Length)); client.Credentials = new NetworkCredential(username, password); } } if (!string.IsNullOrEmpty(this.PickupDirectoryLocation) && this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { client.PickupDirectoryLocation = ConvertDirectoryLocation(PickupDirectoryLocation); } // In case DeliveryMethod = PickupDirectoryFromIis we will not require Host nor PickupDirectoryLocation client.DeliveryMethod = this.DeliveryMethod; client.Timeout = this.Timeout; } /// <summary> /// Handle <paramref name="pickupDirectoryLocation"/> if it is a virtual directory. /// </summary> /// <param name="pickupDirectoryLocation"></param> /// <returns></returns> internal static string ConvertDirectoryLocation(string pickupDirectoryLocation) { const string virtualPathPrefix = "~/"; if (!pickupDirectoryLocation.StartsWith(virtualPathPrefix)) { return pickupDirectoryLocation; } // Support for Virtual Paths var root = AppDomain.CurrentDomain.BaseDirectory; var directory = pickupDirectoryLocation.Substring(virtualPathPrefix.Length).Replace('/', Path.DirectorySeparatorChar); var pickupRoot = Path.Combine(root, directory); return pickupRoot; } private void CheckRequiredParameters() { if (!this.UseSystemNetMailSettings && this.SmtpServer == null && this.DeliveryMethod == SmtpDeliveryMethod.Network) { throw new NLogConfigurationException( string.Format("The MailTarget's '{0}' properties are not set - but needed because useSystemNetMailSettings=false and DeliveryMethod=Network. The email message will not be sent.", "SmtpServer")); } if (!this.UseSystemNetMailSettings && string.IsNullOrEmpty(this.PickupDirectoryLocation) && this.DeliveryMethod == SmtpDeliveryMethod.SpecifiedPickupDirectory) { throw new NLogConfigurationException( string.Format("The MailTarget's '{0}' properties are not set - but needed because useSystemNetMailSettings=false and DeliveryMethod=SpecifiedPickupDirectory. The email message will not be sent.", "PickupDirectoryLocation")); } } /// <summary> /// Create key for grouping. Needed for multiple events in one mailmessage /// </summary> /// <param name="logEvent">event for rendering layouts </param> ///<returns>string to group on</returns> private string GetSmtpSettingsKey(LogEventInfo logEvent) { var sb = new StringBuilder(); AppendLayout(sb, logEvent, this.From); AppendLayout(sb, logEvent, this.To); AppendLayout(sb, logEvent, this.CC); AppendLayout(sb, logEvent, this.Bcc); AppendLayout(sb, logEvent, this.SmtpServer); AppendLayout(sb, logEvent, this.SmtpPassword); AppendLayout(sb, logEvent, this.SmtpUserName); return sb.ToString(); } /// <summary> /// Append rendered layout to the stringbuilder /// </summary> /// <param name="sb">append to this</param> /// <param name="logEvent">event for rendering <paramref name="layout"/></param> /// <param name="layout">append if not <c>null</c></param> private static void AppendLayout(StringBuilder sb, LogEventInfo logEvent, Layout layout) { sb.Append("|"); if (layout != null) sb.Append(layout.Render(logEvent)); } /// <summary> /// Create the mailmessage with the addresses, properties and body. /// </summary> private MailMessage CreateMailMessage(LogEventInfo lastEvent, string body) { var msg = new MailMessage(); var renderedFrom = this.From == null ? null : this.From.Render(lastEvent); if (string.IsNullOrEmpty(renderedFrom)) { throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "From"); } msg.From = new MailAddress(renderedFrom); var addedTo = AddAddresses(msg.To, this.To, lastEvent); var addedCc = AddAddresses(msg.CC, this.CC, lastEvent); var addedBcc = AddAddresses(msg.Bcc, this.Bcc, lastEvent); if (!addedTo && !addedCc && !addedBcc) { throw new NLogRuntimeException(RequiredPropertyIsEmptyFormat, "To/Cc/Bcc"); } msg.Subject = this.Subject == null ? string.Empty : this.Subject.Render(lastEvent).Trim(); msg.BodyEncoding = this.Encoding; msg.IsBodyHtml = this.Html; if (this.Priority != null) { var renderedPriority = this.Priority.Render(lastEvent); try { msg.Priority = (MailPriority)Enum.Parse(typeof(MailPriority), renderedPriority, true); } catch { InternalLogger.Warn("Could not convert '{0}' to MailPriority, valid values are Low, Normal and High. Using normal priority as fallback."); msg.Priority = MailPriority.Normal; } } msg.Body = body; if (msg.IsBodyHtml && ReplaceNewlineWithBrTagInHtml && msg.Body != null) msg.Body = msg.Body.Replace(EnvironmentHelper.NewLine, "<br/>"); return msg; } /// <summary> /// Render <paramref name="layout"/> and add the addresses to <paramref name="mailAddressCollection"/> /// </summary> /// <param name="mailAddressCollection">Addresses appended to this list</param> /// <param name="layout">layout with addresses, ; separated</param> /// <param name="logEvent">event for rendering the <paramref name="layout"/></param> /// <returns>added a address?</returns> private static bool AddAddresses(MailAddressCollection mailAddressCollection, Layout layout, LogEventInfo logEvent) { var added = false; if (layout != null) { foreach (string mail in layout.Render(logEvent).Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries)) { mailAddressCollection.Add(mail); added = true; } } return added; } } } #endif