context
stringlengths 2.52k
185k
| gt
stringclasses 1
value |
---|---|
// 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;
using Microsoft.CodeAnalysis.Testing;
using Xunit;
using VerifyCS = Test.Utilities.CSharpCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.DoNotUseReferenceEqualsWithValueTypesAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicCodeFixVerifier<
Microsoft.NetCore.Analyzers.Runtime.DoNotUseReferenceEqualsWithValueTypesAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetCore.Analyzers.Runtime.UnitTests
{
public class DoNotUseReferenceEqualsWithValueTypesTests
{
[Fact]
public async Task ReferenceTypesAreOK()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return ReferenceEquals(test, string.Empty);
}
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return ReferenceEquals(string.Empty, test)
End Function
End Class
End Namespace");
}
[Fact]
public async Task LeftArgumentFailsForValueType()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return ReferenceEquals(IntPtr.Zero, test);
}
}
}",
GetCSharpMethodResultAt(10, 36, "System.IntPtr"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return ReferenceEquals(IntPtr.Zero, test)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 36, "System.IntPtr"));
}
[Fact]
public async Task RightArgumentFailsForValueType()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return object.ReferenceEquals(test, 4);
}
}
}",
GetCSharpMethodResultAt(10, 49, "int"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return Object.ReferenceEquals(test, 4)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 49, "Integer"));
}
[Fact]
public async Task NoErrorForUnconstrainedGeneric()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
{
return ReferenceEquals(test, other);
}
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T)(test as T, other as Object)
Return ReferenceEquals(test, other)
End Function
End Class
End Namespace");
}
[Fact]
public async Task NoErrorForInterfaceConstrainedGeneric()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
where T : IDisposable
{
return ReferenceEquals(test, other);
}
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T As IDisposable)(test as T, other as Object)
Return ReferenceEquals(test, other)
End Function
End Class
End Namespace");
}
[Fact]
public async Task ErrorForValueTypeConstrainedGeneric()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
where T : struct
{
return ReferenceEquals(test, other);
}
}
}",
GetCSharpMethodResultAt(11, 36, "T"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T As Structure)(test as T, other as Object)
Return ReferenceEquals(test, other)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 36, "T"));
}
[Fact]
public async Task TwoValueTypesProducesTwoErrors()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<TLeft, TRight>(TLeft test, TRight other)
where TLeft : struct
where TRight : struct
{
return ReferenceEquals(
test,
other);
}
}
}",
GetCSharpMethodResultAt(13, 17, "TLeft"),
GetCSharpMethodResultAt(14, 17, "TRight"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of TLeft As Structure, TRight As Structure)(test as TLeft, other as TRight)
Return ReferenceEquals(test, other)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 36, "TLeft"),
GetVisualBasicMethodResultAt(7, 42, "TRight"));
}
[Fact]
public async Task LeftArgumentFailsForValueTypeWhenRightIsNull()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod()
{
return ReferenceEquals(IntPtr.Zero, null);
}
}
}",
GetCSharpMethodResultAt(10, 36, "System.IntPtr"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod()
Return ReferenceEquals(IntPtr.Zero, Nothing)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 36, "System.IntPtr"));
}
[Fact]
public async Task RightArgumentFailsForValueTypeWhenLeftIsNull()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod()
{
return object.ReferenceEquals(null, 4);
}
}
}",
GetCSharpMethodResultAt(10, 49, "int"));
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod()
Return Object.ReferenceEquals(Nothing, 4)
End Function
End Class
End Namespace",
GetVisualBasicMethodResultAt(7, 52, "Integer"));
}
[Fact]
public async Task DoNotWarnForUserDefinedConversions()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
namespace TestNamespace
{
class CacheKey
{
public static explicit operator CacheKey(int value)
{
return null;
}
}
class TestClass
{
private static bool TestMethod()
{
return object.ReferenceEquals(null, (CacheKey)4);
}
}
}");
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System
Namespace TestNamespace
Class CacheKey
Public Shared Narrowing Operator CType(value as Integer) as CacheKey
Return Nothing
End Operator
End Class
Class TestClass
Private Shared Function TestMethod()
Return Object.ReferenceEquals(Nothing, CType(4, CacheKey))
End Function
End Class
End Namespace");
}
[Fact]
public async Task Comparer_ReferenceTypesAreOK()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return ReferenceEqualityComparer.Instance.Equals(string.Empty, test);
}
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return ReferenceEqualityComparer.Instance.Equals(string.Empty, test)
End Function
End Class
End Namespace",
}.RunAsync();
}
[Fact]
public async Task Comparer_LeftArgumentFailsForValueType()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return ReferenceEqualityComparer.Instance.Equals(IntPtr.Zero, test);
}
}
}",
ExpectedDiagnostics = { GetCSharpComparerResultAt(11, 62, "System.IntPtr") },
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return ReferenceEqualityComparer.Instance.Equals(IntPtr.Zero, test)
End Function
End Class
End Namespace",
ExpectedDiagnostics = { GetVisualBasicComparerResultAt(8, 62, "System.IntPtr") },
}.RunAsync();
}
[Fact]
public async Task Comparer_RightArgumentFailsForValueType()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
return ReferenceEqualityComparer.Instance.Equals(test, 4);
}
}
}",
ExpectedDiagnostics = { GetCSharpComparerResultAt(11, 68, "int") },
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Return ReferenceEqualityComparer.Instance.Equals(test, 4)
End Function
End Class
End Namespace",
ExpectedDiagnostics = { GetVisualBasicComparerResultAt(8, 68, "Integer") },
}.RunAsync();
}
[Fact]
public async Task Comparer_NoErrorForUnconstrainedGeneric()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
{
return ReferenceEqualityComparer.Instance.Equals(test, other);
}
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T)(test as T, other as Object)
Return ReferenceEqualityComparer.Instance.Equals(test, other)
End Function
End Class
End Namespace",
}.RunAsync();
}
[Fact]
public async Task Comparer_NoErrorForInterfaceConstrainedGeneric()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
where T : IDisposable
{
return ReferenceEqualityComparer.Instance.Equals(test, other);
}
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T As IDisposable)(test as T, other as Object)
Return ReferenceEqualityComparer.Instance.Equals(test, other)
End Function
End Class
End Namespace",
}.RunAsync();
}
[Fact]
public async Task Comparer_ErrorForValueTypeConstrainedGeneric()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<T>(T test, object other)
where T : struct
{
return ReferenceEqualityComparer.Instance.Equals(test, other);
}
}
}",
ExpectedDiagnostics = { GetCSharpComparerResultAt(12, 62, "T") },
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of T As Structure)(test as T, other as Object)
Return ReferenceEqualityComparer.Instance.Equals(test, other)
End Function
End Class
End Namespace",
ExpectedDiagnostics = { GetVisualBasicComparerResultAt(8, 62, "T") },
}.RunAsync();
}
[Fact]
public async Task Comparer_TwoValueTypesProducesTwoErrors()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod<TLeft, TRight>(TLeft test, TRight other)
where TLeft : struct
where TRight : struct
{
return ReferenceEqualityComparer.Instance.Equals(
test,
other);
}
}
}",
ExpectedDiagnostics =
{
GetCSharpComparerResultAt(14, 17, "TLeft"),
GetCSharpComparerResultAt(15, 17, "TRight"),
},
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(Of TLeft As Structure, TRight As Structure)(test as TLeft, other as TRight)
Return ReferenceEqualityComparer.Instance.Equals(test, other)
End Function
End Class
End Namespace",
ExpectedDiagnostics =
{
GetVisualBasicComparerResultAt(8, 62, "TLeft"),
GetVisualBasicComparerResultAt(8, 68, "TRight"),
},
}.RunAsync();
}
[Fact]
public async Task Comparer_LeftArgumentFailsForValueTypeWhenRightIsNull()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod()
{
return ReferenceEqualityComparer.Instance.Equals(IntPtr.Zero, null);
}
}
}",
ExpectedDiagnostics = { GetCSharpComparerResultAt(11, 62, "System.IntPtr") },
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod()
Return ReferenceEqualityComparer.Instance.Equals(IntPtr.Zero, Nothing)
End Function
End Class
End Namespace",
ExpectedDiagnostics = { GetVisualBasicComparerResultAt(8, 62, "System.IntPtr") },
}.RunAsync();
}
[Fact]
public async Task Comparer_RightArgumentFailsForValueTypeWhenLeftIsNull()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod()
{
return ReferenceEqualityComparer.Instance.Equals(null, 4);
}
}
}",
ExpectedDiagnostics = { GetCSharpComparerResultAt(11, 68, "int") },
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod()
Return ReferenceEqualityComparer.Instance.Equals(Nothing, 4)
End Function
End Class
End Namespace",
ExpectedDiagnostics = { GetVisualBasicComparerResultAt(8, 71, "Integer") },
}.RunAsync();
}
[Fact]
public async Task Comparer_DoNotWarnForUserDefinedConversions()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections.Generic;
namespace TestNamespace
{
class CacheKey
{
public static explicit operator CacheKey(int value)
{
return null;
}
}
class TestClass
{
private static bool TestMethod()
{
return ReferenceEqualityComparer.Instance.Equals(null, (CacheKey)4);
}
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections.Generic
Namespace TestNamespace
Class CacheKey
Public Shared Narrowing Operator CType(value as Integer) as CacheKey
Return Nothing
End Operator
End Class
Class TestClass
Private Shared Function TestMethod()
Return ReferenceEqualityComparer.Instance.Equals(Nothing, CType(4, CacheKey))
End Function
End Class
End Namespace",
}.RunAsync();
}
[Fact]
public async Task ComparerDoesNotTrackThroughInterface()
{
await new VerifyCS.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
using System;
using System.Collections;
using System.Collections.Generic;
namespace TestNamespace
{
class TestClass
{
private static bool TestMethod(string test)
{
IEqualityComparer<object> generic = ReferenceEqualityComparer.Instance;
IEqualityComparer nonGeneric = ReferenceEqualityComparer.Instance;
return generic.Equals(4, 5) || nonGeneric.Equals(4, 5);
}
}
}",
}.RunAsync();
await new VerifyVB.Test
{
ReferenceAssemblies = ReferenceAssemblies.Net.Net50,
TestCode = @"
Imports System
Imports System.Collections
Imports System.Collections.Generic
Namespace TestNamespace
Class TestClass
Private Shared Function TestMethod(test as String)
Dim generic as IEqualityComparer(Of object) = ReferenceEqualityComparer.Instance
Dim nonGeneric as IEqualityComparer = ReferenceEqualityComparer.Instance
Return generic.Equals(4, 5) Or nonGeneric.Equals(4, 5)
End Function
End Class
End Namespace",
}.RunAsync();
}
private DiagnosticResult GetCSharpMethodResultAt(int line, int column, string typeName)
=> GetCSharpResultAt(DoNotUseReferenceEqualsWithValueTypesAnalyzer.MethodRule, line, column, typeName);
private DiagnosticResult GetVisualBasicMethodResultAt(int line, int column, string typeName)
=> GetVisualBasicResultAt(DoNotUseReferenceEqualsWithValueTypesAnalyzer.MethodRule, line, column, typeName);
private DiagnosticResult GetCSharpComparerResultAt(int line, int column, string typeName)
=> GetCSharpResultAt(DoNotUseReferenceEqualsWithValueTypesAnalyzer.ComparerRule, line, column, typeName);
private DiagnosticResult GetVisualBasicComparerResultAt(int line, int column, string typeName)
=> GetVisualBasicResultAt(DoNotUseReferenceEqualsWithValueTypesAnalyzer.ComparerRule, line, column, typeName);
private DiagnosticResult GetCSharpResultAt(DiagnosticDescriptor rule, int line, int column, string typeName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyCS.Diagnostic(rule).WithLocation(line, column).WithArguments(typeName);
#pragma warning restore RS0030 // Do not used banned APIs
private DiagnosticResult GetVisualBasicResultAt(DiagnosticDescriptor rule, int line, int column, string typeName)
#pragma warning disable RS0030 // Do not used banned APIs
=> VerifyVB.Diagnostic(rule).WithLocation(line, column).WithArguments(typeName);
#pragma warning restore RS0030 // Do not used banned APIs
}
}
| |
using Microsoft.IdentityModel;
using Microsoft.IdentityModel.S2S.Protocols.OAuth2;
using Microsoft.IdentityModel.S2S.Tokens;
using Microsoft.SharePoint.Client;
using Microsoft.SharePoint.Client.EventReceivers;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography.X509Certificates;
using System.Security.Principal;
using System.ServiceModel;
using System.Text;
using System.Web;
using System.Web.Configuration;
using System.Web.Script.Serialization;
using AudienceRestriction = Microsoft.IdentityModel.Tokens.AudienceRestriction;
using AudienceUriValidationFailedException = Microsoft.IdentityModel.Tokens.AudienceUriValidationFailedException;
using SecurityTokenHandlerConfiguration = Microsoft.IdentityModel.Tokens.SecurityTokenHandlerConfiguration;
using X509SigningCredentials = Microsoft.IdentityModel.SecurityTokenService.X509SigningCredentials;
namespace Core.ConnSigRAngJSApps
{
public static class TokenHelper
{
#region public fields
/// <summary>
/// SharePoint principal.
/// </summary>
public const string SharePointPrincipal = "00000003-0000-0ff1-ce00-000000000000";
/// <summary>
/// Lifetime of HighTrust access token, 12 hours.
/// </summary>
public static readonly TimeSpan HighTrustAccessTokenLifetime = TimeSpan.FromHours(12.0);
#endregion public fields
#region public methods
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequest request)
{
return GetContextTokenFromRequest(new HttpRequestWrapper(request));
}
/// <summary>
/// Retrieves the context token string from the specified request by looking for well-known parameter names in the
/// POSTed form parameters and the querystring. Returns null if no context token is found.
/// </summary>
/// <param name="request">HttpRequest in which to look for a context token</param>
/// <returns>The context token string</returns>
public static string GetContextTokenFromRequest(HttpRequestBase request)
{
string[] paramNames = { "AppContext", "AppContextToken", "AccessToken", "SPAppToken" };
foreach (string paramName in paramNames)
{
if (!string.IsNullOrEmpty(request.Form[paramName]))
{
return request.Form[paramName];
}
if (!string.IsNullOrEmpty(request.QueryString[paramName]))
{
return request.QueryString[paramName];
}
}
return null;
}
/// <summary>
/// Validate that a specified context token string is intended for this application based on the parameters
/// specified in web.config. Parameters used from web.config used for validation include ClientId,
/// HostedAppHostNameOverride, HostedAppHostName, ClientSecret, and Realm (if it is specified). If HostedAppHostNameOverride is present,
/// it will be used for validation. Otherwise, if the <paramref name="appHostName"/> is not
/// null, it is used for validation instead of the web.config's HostedAppHostName. If the token is invalid, an
/// exception is thrown. If the token is valid, TokenHelper's static STS metadata url is updated based on the token contents
/// and a JsonWebSecurityToken based on the context token is returned.
/// </summary>
/// <param name="contextTokenString">The context token to validate</param>
/// <param name="appHostName">The URL authority, consisting of Domain Name System (DNS) host name or IP address and the port number, to use for token audience validation.
/// If null, HostedAppHostName web.config setting is used instead. HostedAppHostNameOverride web.config setting, if present, will be used
/// for validation instead of <paramref name="appHostName"/> .</param>
/// <returns>A JsonWebSecurityToken based on the context token.</returns>
public static SharePointContextToken ReadAndValidateContextToken(string contextTokenString, string appHostName = null)
{
JsonWebSecurityTokenHandler tokenHandler = CreateJsonWebSecurityTokenHandler();
SecurityToken securityToken = tokenHandler.ReadToken(contextTokenString);
JsonWebSecurityToken jsonToken = securityToken as JsonWebSecurityToken;
SharePointContextToken token = SharePointContextToken.Create(jsonToken);
string stsAuthority = (new Uri(token.SecurityTokenServiceUri)).Authority;
int firstDot = stsAuthority.IndexOf('.');
GlobalEndPointPrefix = stsAuthority.Substring(0, firstDot);
AcsHostUrl = stsAuthority.Substring(firstDot + 1);
tokenHandler.ValidateToken(jsonToken);
string[] acceptableAudiences;
if (!String.IsNullOrEmpty(HostedAppHostNameOverride))
{
acceptableAudiences = HostedAppHostNameOverride.Split(';');
}
else if (appHostName == null)
{
acceptableAudiences = new[] { HostedAppHostName };
}
else
{
acceptableAudiences = new[] { appHostName };
}
bool validationSuccessful = false;
string realm = Realm ?? token.Realm;
foreach (var audience in acceptableAudiences)
{
string principal = GetFormattedPrincipal(ClientId, audience, realm);
if (StringComparer.OrdinalIgnoreCase.Equals(token.Audience, principal))
{
validationSuccessful = true;
break;
}
}
if (!validationSuccessful)
{
throw new AudienceUriValidationFailedException(
String.Format(CultureInfo.CurrentCulture,
"\"{0}\" is not the intended audience \"{1}\"", String.Join(";", acceptableAudiences), token.Audience));
}
return token;
}
/// <summary>
/// Retrieves an access token from ACS to call the source of the specified context token at the specified
/// targetHost. The targetHost must be registered for the principal that sent the context token.
/// </summary>
/// <param name="contextToken">Context token issued by the intended access token audience</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <returns>An access token with an audience matching the context token's source</returns>
public static OAuth2AccessTokenResponse GetAccessToken(SharePointContextToken contextToken, string targetHost)
{
string targetPrincipalName = contextToken.TargetPrincipalName;
// Extract the refreshToken from the context token
string refreshToken = contextToken.RefreshToken;
if (String.IsNullOrEmpty(refreshToken))
{
return null;
}
string targetRealm = Realm ?? contextToken.Realm;
return GetAccessToken(refreshToken,
targetPrincipalName,
targetHost,
targetRealm);
}
/// <summary>
/// Uses the specified authorization code to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="authorizationCode">Authorization code to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string authorizationCode,
string targetPrincipalName,
string targetHost,
string targetRealm,
Uri redirectUri)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
// Create request for token. The RedirectUri is null here. This will fail if redirect uri is registered
OAuth2AccessTokenRequest oauth2Request =
OAuth2MessageFactory.CreateAccessTokenRequestWithAuthorizationCode(
clientId,
ClientSecret,
authorizationCode,
redirectUri,
resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Uses the specified refresh token to retrieve an access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="refreshToken">Refresh token to exchange for access token</param>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAccessToken(
string refreshToken,
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, null, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithRefreshToken(clientId, ClientSecret, refreshToken, resource);
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Retrieves an app-only access token from ACS to call the specified principal
/// at the specified targetHost. The targetHost must be registered for target principal. If specified realm is
/// null, the "Realm" setting in web.config will be used instead.
/// </summary>
/// <param name="targetPrincipalName">Name of the target principal to retrieve an access token for</param>
/// <param name="targetHost">Url authority of the target principal</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <returns>An access token with an audience of the target principal</returns>
public static OAuth2AccessTokenResponse GetAppOnlyAccessToken(
string targetPrincipalName,
string targetHost,
string targetRealm)
{
if (targetRealm == null)
{
targetRealm = Realm;
}
string resource = GetFormattedPrincipal(targetPrincipalName, targetHost, targetRealm);
string clientId = GetFormattedPrincipal(ClientId, HostedAppHostName, targetRealm);
OAuth2AccessTokenRequest oauth2Request = OAuth2MessageFactory.CreateAccessTokenRequestWithClientCredentials(clientId, ClientSecret, resource);
oauth2Request.Resource = resource;
// Get token
OAuth2S2SClient client = new OAuth2S2SClient();
OAuth2AccessTokenResponse oauth2Response;
try
{
oauth2Response =
client.Issue(AcsMetadataParser.GetStsUrl(targetRealm), oauth2Request) as OAuth2AccessTokenResponse;
}
catch (WebException wex)
{
using (StreamReader sr = new StreamReader(wex.Response.GetResponseStream()))
{
string responseText = sr.ReadToEnd();
throw new WebException(wex.Message + " - " + responseText, wex);
}
}
return oauth2Response;
}
/// <summary>
/// Creates a client context based on the properties of a remote event receiver
/// </summary>
/// <param name="properties">Properties of a remote event receiver</param>
/// <returns>A ClientContext ready to call the web where the event originated</returns>
public static ClientContext CreateRemoteEventReceiverClientContext(SPRemoteEventProperties properties)
{
Uri sharepointUrl;
if (properties.ListEventProperties != null)
{
sharepointUrl = new Uri(properties.ListEventProperties.WebUrl);
}
else if (properties.ItemEventProperties != null)
{
sharepointUrl = new Uri(properties.ItemEventProperties.WebUrl);
}
else if (properties.WebEventProperties != null)
{
sharepointUrl = new Uri(properties.WebEventProperties.FullUrl);
}
else
{
return null;
}
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Creates a client context based on the properties of an app event
/// </summary>
/// <param name="properties">Properties of an app event</param>
/// <param name="useAppWeb">True to target the app web, false to target the host web</param>
/// <returns>A ClientContext ready to call the app web or the parent web</returns>
public static ClientContext CreateAppEventClientContext(SPRemoteEventProperties properties, bool useAppWeb)
{
if (properties.AppEventProperties == null)
{
return null;
}
Uri sharepointUrl = useAppWeb ? properties.AppEventProperties.AppWebFullUrl : properties.AppEventProperties.HostWebFullUrl;
if (IsHighTrustApp())
{
return GetS2SClientContextWithWindowsIdentity(sharepointUrl, null);
}
return CreateAcsClientContextForUrl(properties, sharepointUrl);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string authorizationCode,
Uri redirectUri)
{
return GetClientContextWithAuthorizationCode(targetUrl, SharePointPrincipal, authorizationCode, GetRealmFromTargetUrl(new Uri(targetUrl)), redirectUri);
}
/// <summary>
/// Retrieves an access token from ACS using the specified authorization code, and uses that access token to
/// create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="targetPrincipalName">Name of the target SharePoint principal</param>
/// <param name="authorizationCode">Authorization code to use when retrieving the access token from ACS</param>
/// <param name="targetRealm">Realm to use for the access token's nameid and audience</param>
/// <param name="redirectUri">Redirect URI registerd for this app</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithAuthorizationCode(
string targetUrl,
string targetPrincipalName,
string authorizationCode,
string targetRealm,
Uri redirectUri)
{
Uri targetUri = new Uri(targetUrl);
string accessToken =
GetAccessToken(authorizationCode, targetPrincipalName, targetUri.Authority, targetRealm, redirectUri).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Uses the specified access token to create a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="accessToken">Access token to be used when calling the specified targetUrl</param>
/// <returns>A ClientContext ready to call targetUrl with the specified access token</returns>
public static ClientContext GetClientContextWithAccessToken(string targetUrl, string accessToken)
{
ClientContext clientContext = new ClientContext(targetUrl);
clientContext.AuthenticationMode = ClientAuthenticationMode.Anonymous;
clientContext.FormDigestHandlingEnabled = false;
clientContext.ExecutingWebRequest +=
delegate(object oSender, WebRequestEventArgs webRequestEventArgs)
{
webRequestEventArgs.WebRequestExecutor.RequestHeaders["Authorization"] =
"Bearer " + accessToken;
};
return clientContext;
}
/// <summary>
/// Retrieves an access token from ACS using the specified context token, and uses that access token to create
/// a client context
/// </summary>
/// <param name="targetUrl">Url of the target SharePoint site</param>
/// <param name="contextTokenString">Context token received from the target SharePoint site</param>
/// <param name="appHostUrl">Url authority of the hosted app. If this is null, the value in the HostedAppHostName
/// of web.config will be used instead</param>
/// <returns>A ClientContext ready to call targetUrl with a valid access token</returns>
public static ClientContext GetClientContextWithContextToken(
string targetUrl,
string contextTokenString,
string appHostUrl)
{
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, appHostUrl);
Uri targetUri = new Uri(targetUrl);
string accessToken = GetAccessToken(contextToken, targetUri.Authority).AccessToken;
return GetClientContextWithAccessToken(targetUrl, accessToken);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request consent and get back
/// an authorization code.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="scope">Space-delimited permissions to request from the SharePoint site in "shorthand" format
/// (e.g. "Web.Read Site.Write")</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to after consent is
/// granted</param>
/// <returns>Url of the SharePoint site's OAuth authorization page</returns>
public static string GetAuthorizationUrl(string contextUrl, string scope, string redirectUri)
{
return string.Format(
"{0}{1}?IsDlg=1&client_id={2}&scope={3}&response_type=code&redirect_uri={4}",
EnsureTrailingSlash(contextUrl),
AuthorizationPage,
ClientId,
scope,
redirectUri);
}
/// <summary>
/// Returns the SharePoint url to which the app should redirect the browser to request a new context token.
/// </summary>
/// <param name="contextUrl">Absolute Url of the SharePoint site</param>
/// <param name="redirectUri">Uri to which SharePoint should redirect the browser to with a context token</param>
/// <returns>Url of the SharePoint site's context token redirect page</returns>
public static string GetAppContextTokenRequestUrl(string contextUrl, string redirectUri)
{
return string.Format(
"{0}{1}?client_id={2}&redirect_uri={3}",
EnsureTrailingSlash(contextUrl),
RedirectPage,
ClientId,
redirectUri);
}
/// <summary>
/// Retrieves an S2S access token signed by the application's private certificate on behalf of the specified
/// WindowsIdentity and intended for the SharePoint at the targetApplicationUri. If no Realm is specified in
/// web.config, an auth challenge will be issued to the targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>An access token with an audience of the target principal</returns>
public static string GetS2SAccessTokenWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
return GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
}
/// <summary>
/// Retrieves an S2S client context with an access token signed by the application's private certificate on
/// behalf of the specified WindowsIdentity and intended for application at the targetApplicationUri using the
/// targetRealm. If no Realm is specified in web.config, an auth challenge will be issued to the
/// targetApplicationUri to discover it.
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <param name="identity">Windows identity of the user on whose behalf to create the access token</param>
/// <returns>A ClientContext using an access token with an audience of the target application</returns>
public static ClientContext GetS2SClientContextWithWindowsIdentity(
Uri targetApplicationUri,
WindowsIdentity identity)
{
string realm = string.IsNullOrEmpty(Realm) ? GetRealmFromTargetUrl(targetApplicationUri) : Realm;
JsonWebTokenClaim[] claims = identity != null ? GetClaimsWithWindowsIdentity(identity) : null;
string accessToken = GetS2SAccessTokenWithClaims(targetApplicationUri.Authority, realm, claims);
return GetClientContextWithAccessToken(targetApplicationUri.ToString(), accessToken);
}
/// <summary>
/// Get authentication realm from SharePoint
/// </summary>
/// <param name="targetApplicationUri">Url of the target SharePoint site</param>
/// <returns>String representation of the realm GUID</returns>
public static string GetRealmFromTargetUrl(Uri targetApplicationUri)
{
WebRequest request = WebRequest.Create(targetApplicationUri + "/_vti_bin/client.svc");
request.Headers.Add("Authorization: Bearer ");
try
{
using (request.GetResponse())
{
}
}
catch (WebException e)
{
if (e.Response == null)
{
return null;
}
string bearerResponseHeader = e.Response.Headers["WWW-Authenticate"];
if (string.IsNullOrEmpty(bearerResponseHeader))
{
return null;
}
const string bearer = "Bearer realm=\"";
int bearerIndex = bearerResponseHeader.IndexOf(bearer, StringComparison.Ordinal);
if (bearerIndex < 0)
{
return null;
}
int realmIndex = bearerIndex + bearer.Length;
if (bearerResponseHeader.Length >= realmIndex + 36)
{
string targetRealm = bearerResponseHeader.Substring(realmIndex, 36);
Guid realmGuid;
if (Guid.TryParse(targetRealm, out realmGuid))
{
return targetRealm;
}
}
}
return null;
}
/// <summary>
/// Determines if this is a high trust app.
/// </summary>
/// <returns>True if this is a high trust app.</returns>
public static bool IsHighTrustApp()
{
return SigningCredentials != null;
}
/// <summary>
/// Ensures that the specified URL ends with '/' if it is not null or empty.
/// </summary>
/// <param name="url">The url.</param>
/// <returns>The url ending with '/' if it is not null or empty.</returns>
public static string EnsureTrailingSlash(string url)
{
if (!string.IsNullOrEmpty(url) && url[url.Length - 1] != '/')
{
return url + "/";
}
return url;
}
#endregion
#region private fields
//
// Configuration Constants
//
private const string AuthorizationPage = "_layouts/15/OAuthAuthorize.aspx";
private const string RedirectPage = "_layouts/15/AppRedirect.aspx";
private const string AcsPrincipalName = "00000001-0000-0000-c000-000000000000";
private const string AcsMetadataEndPointRelativeUrl = "metadata/json/1";
private const string S2SProtocol = "OAuth2";
private const string DelegationIssuance = "DelegationIssuance1.0";
private const string NameIdentifierClaimType = JsonWebTokenConstants.ReservedClaims.NameIdentifier;
private const string TrustedForImpersonationClaimType = "trustedfordelegation";
private const string ActorTokenClaimType = JsonWebTokenConstants.ReservedClaims.ActorToken;
//
// Environment Constants
//
private static string GlobalEndPointPrefix = "accounts";
private static string AcsHostUrl = "accesscontrol.windows.net";
//
// Hosted app configuration
//
private static readonly string ClientId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientId")) ? WebConfigurationManager.AppSettings.Get("HostedAppName") : WebConfigurationManager.AppSettings.Get("ClientId");
private static readonly string IssuerId = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("IssuerId")) ? ClientId : WebConfigurationManager.AppSettings.Get("IssuerId");
private static readonly string HostedAppHostNameOverride = WebConfigurationManager.AppSettings.Get("HostedAppHostNameOverride");
private static readonly string HostedAppHostName = WebConfigurationManager.AppSettings.Get("HostedAppHostName");
private static readonly string ClientSecret = string.IsNullOrEmpty(WebConfigurationManager.AppSettings.Get("ClientSecret")) ? WebConfigurationManager.AppSettings.Get("HostedAppSigningKey") : WebConfigurationManager.AppSettings.Get("ClientSecret");
private static readonly string SecondaryClientSecret = WebConfigurationManager.AppSettings.Get("SecondaryClientSecret");
private static readonly string Realm = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ServiceNamespace = WebConfigurationManager.AppSettings.Get("Realm");
private static readonly string ClientSigningCertificatePath = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePath");
private static readonly string ClientSigningCertificatePassword = WebConfigurationManager.AppSettings.Get("ClientSigningCertificatePassword");
private static readonly X509Certificate2 ClientCertificate = (string.IsNullOrEmpty(ClientSigningCertificatePath) || string.IsNullOrEmpty(ClientSigningCertificatePassword)) ? null : new X509Certificate2(ClientSigningCertificatePath, ClientSigningCertificatePassword);
private static readonly X509SigningCredentials SigningCredentials = (ClientCertificate == null) ? null : new X509SigningCredentials(ClientCertificate, SecurityAlgorithms.RsaSha256Signature, SecurityAlgorithms.Sha256Digest);
#endregion
#region private methods
private static ClientContext CreateAcsClientContextForUrl(SPRemoteEventProperties properties, Uri sharepointUrl)
{
string contextTokenString = properties.ContextToken;
if (String.IsNullOrEmpty(contextTokenString))
{
return null;
}
SharePointContextToken contextToken = ReadAndValidateContextToken(contextTokenString, OperationContext.Current.IncomingMessageHeaders.To.Host);
string accessToken = GetAccessToken(contextToken, sharepointUrl.Authority).AccessToken;
return GetClientContextWithAccessToken(sharepointUrl.ToString(), accessToken);
}
private static string GetAcsMetadataEndpointUrl()
{
return Path.Combine(GetAcsGlobalEndpointUrl(), AcsMetadataEndPointRelativeUrl);
}
private static string GetFormattedPrincipal(string principalName, string hostName, string realm)
{
if (!String.IsNullOrEmpty(hostName))
{
return String.Format(CultureInfo.InvariantCulture, "{0}/{1}@{2}", principalName, hostName, realm);
}
return String.Format(CultureInfo.InvariantCulture, "{0}@{1}", principalName, realm);
}
private static string GetAcsPrincipalName(string realm)
{
return GetFormattedPrincipal(AcsPrincipalName, new Uri(GetAcsGlobalEndpointUrl()).Host, realm);
}
private static string GetAcsGlobalEndpointUrl()
{
return String.Format(CultureInfo.InvariantCulture, "https://{0}.{1}/", GlobalEndPointPrefix, AcsHostUrl);
}
private static JsonWebSecurityTokenHandler CreateJsonWebSecurityTokenHandler()
{
JsonWebSecurityTokenHandler handler = new JsonWebSecurityTokenHandler();
handler.Configuration = new SecurityTokenHandlerConfiguration();
handler.Configuration.AudienceRestriction = new AudienceRestriction(AudienceUriMode.Never);
handler.Configuration.CertificateValidator = X509CertificateValidator.None;
List<byte[]> securityKeys = new List<byte[]>();
securityKeys.Add(Convert.FromBase64String(ClientSecret));
if (!string.IsNullOrEmpty(SecondaryClientSecret))
{
securityKeys.Add(Convert.FromBase64String(SecondaryClientSecret));
}
List<SecurityToken> securityTokens = new List<SecurityToken>();
securityTokens.Add(new MultipleSymmetricKeySecurityToken(securityKeys));
handler.Configuration.IssuerTokenResolver =
SecurityTokenResolver.CreateDefaultSecurityTokenResolver(
new ReadOnlyCollection<SecurityToken>(securityTokens),
false);
SymmetricKeyIssuerNameRegistry issuerNameRegistry = new SymmetricKeyIssuerNameRegistry();
foreach (byte[] securitykey in securityKeys)
{
issuerNameRegistry.AddTrustedIssuer(securitykey, GetAcsPrincipalName(ServiceNamespace));
}
handler.Configuration.IssuerNameRegistry = issuerNameRegistry;
return handler;
}
private static string GetS2SAccessTokenWithClaims(
string targetApplicationHostName,
string targetRealm,
IEnumerable<JsonWebTokenClaim> claims)
{
return IssueToken(
ClientId,
IssuerId,
targetRealm,
SharePointPrincipal,
targetRealm,
targetApplicationHostName,
true,
claims,
claims == null);
}
private static JsonWebTokenClaim[] GetClaimsWithWindowsIdentity(WindowsIdentity identity)
{
JsonWebTokenClaim[] claims = new JsonWebTokenClaim[]
{
new JsonWebTokenClaim(NameIdentifierClaimType, identity.User.Value.ToLower()),
new JsonWebTokenClaim("nii", "urn:office:idp:activedirectory")
};
return claims;
}
private static string IssueToken(
string sourceApplication,
string issuerApplication,
string sourceRealm,
string targetApplication,
string targetRealm,
string targetApplicationHostName,
bool trustedForDelegation,
IEnumerable<JsonWebTokenClaim> claims,
bool appOnly = false)
{
if (null == SigningCredentials)
{
throw new InvalidOperationException("SigningCredentials was not initialized");
}
#region Actor token
string issuer = string.IsNullOrEmpty(sourceRealm) ? issuerApplication : string.Format("{0}@{1}", issuerApplication, sourceRealm);
string nameid = string.IsNullOrEmpty(sourceRealm) ? sourceApplication : string.Format("{0}@{1}", sourceApplication, sourceRealm);
string audience = string.Format("{0}/{1}@{2}", targetApplication, targetApplicationHostName, targetRealm);
List<JsonWebTokenClaim> actorClaims = new List<JsonWebTokenClaim>();
actorClaims.Add(new JsonWebTokenClaim(JsonWebTokenConstants.ReservedClaims.NameIdentifier, nameid));
if (trustedForDelegation && !appOnly)
{
actorClaims.Add(new JsonWebTokenClaim(TrustedForImpersonationClaimType, "true"));
}
// Create token
JsonWebSecurityToken actorToken = new JsonWebSecurityToken(
issuer: issuer,
audience: audience,
validFrom: DateTime.UtcNow,
validTo: DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
signingCredentials: SigningCredentials,
claims: actorClaims);
string actorTokenString = new JsonWebSecurityTokenHandler().WriteTokenAsString(actorToken);
if (appOnly)
{
// App-only token is the same as actor token for delegated case
return actorTokenString;
}
#endregion Actor token
#region Outer token
List<JsonWebTokenClaim> outerClaims = null == claims ? new List<JsonWebTokenClaim>() : new List<JsonWebTokenClaim>(claims);
outerClaims.Add(new JsonWebTokenClaim(ActorTokenClaimType, actorTokenString));
JsonWebSecurityToken jsonToken = new JsonWebSecurityToken(
nameid, // outer token issuer should match actor token nameid
audience,
DateTime.UtcNow,
DateTime.UtcNow.Add(HighTrustAccessTokenLifetime),
outerClaims);
string accessToken = new JsonWebSecurityTokenHandler().WriteTokenAsString(jsonToken);
#endregion Outer token
return accessToken;
}
#endregion
#region AcsMetadataParser
// This class is used to get MetaData document from the global STS endpoint. It contains
// methods to parse the MetaData document and get endpoints and STS certificate.
public static class AcsMetadataParser
{
public static X509Certificate2 GetAcsSigningCert(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
if (null != document.keys && document.keys.Count > 0)
{
JsonKey signingKey = document.keys[0];
if (null != signingKey && null != signingKey.keyValue)
{
return new X509Certificate2(Encoding.UTF8.GetBytes(signingKey.keyValue.value));
}
}
throw new Exception("Metadata document does not contain ACS signing certificate.");
}
public static string GetDelegationServiceUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint delegationEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == DelegationIssuance);
if (null != delegationEndpoint)
{
return delegationEndpoint.location;
}
throw new Exception("Metadata document does not contain Delegation Service endpoint Url");
}
private static JsonMetadataDocument GetMetadataDocument(string realm)
{
string acsMetadataEndpointUrlWithRealm = String.Format(CultureInfo.InvariantCulture, "{0}?realm={1}",
GetAcsMetadataEndpointUrl(),
realm);
byte[] acsMetadata;
using (WebClient webClient = new WebClient())
{
acsMetadata = webClient.DownloadData(acsMetadataEndpointUrlWithRealm);
}
string jsonResponseString = Encoding.UTF8.GetString(acsMetadata);
JavaScriptSerializer serializer = new JavaScriptSerializer();
JsonMetadataDocument document = serializer.Deserialize<JsonMetadataDocument>(jsonResponseString);
if (null == document)
{
throw new Exception("No metadata document found at the global endpoint " + acsMetadataEndpointUrlWithRealm);
}
return document;
}
public static string GetStsUrl(string realm)
{
JsonMetadataDocument document = GetMetadataDocument(realm);
JsonEndpoint s2sEndpoint = document.endpoints.SingleOrDefault(e => e.protocol == S2SProtocol);
if (null != s2sEndpoint)
{
return s2sEndpoint.location;
}
throw new Exception("Metadata document does not contain STS endpoint url");
}
private class JsonMetadataDocument
{
public string serviceName { get; set; }
public List<JsonEndpoint> endpoints { get; set; }
public List<JsonKey> keys { get; set; }
}
private class JsonEndpoint
{
public string location { get; set; }
public string protocol { get; set; }
public string usage { get; set; }
}
private class JsonKeyValue
{
public string type { get; set; }
public string value { get; set; }
}
private class JsonKey
{
public string usage { get; set; }
public JsonKeyValue keyValue { get; set; }
}
}
#endregion
}
/// <summary>
/// A JsonWebSecurityToken generated by SharePoint to authenticate to a 3rd party application and allow callbacks using a refresh token
/// </summary>
public class SharePointContextToken : JsonWebSecurityToken
{
public static SharePointContextToken Create(JsonWebSecurityToken contextToken)
{
return new SharePointContextToken(contextToken.Issuer, contextToken.Audience, contextToken.ValidFrom, contextToken.ValidTo, contextToken.Claims);
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims)
: base(issuer, audience, validFrom, validTo, claims)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SecurityToken issuerToken, JsonWebSecurityToken actorToken)
: base(issuer, audience, validFrom, validTo, claims, issuerToken, actorToken)
{
}
public SharePointContextToken(string issuer, string audience, DateTime validFrom, DateTime validTo, IEnumerable<JsonWebTokenClaim> claims, SigningCredentials signingCredentials)
: base(issuer, audience, validFrom, validTo, claims, signingCredentials)
{
}
public string NameId
{
get
{
return GetClaimValue(this, "nameid");
}
}
/// <summary>
/// The principal name portion of the context token's "appctxsender" claim
/// </summary>
public string TargetPrincipalName
{
get
{
string appctxsender = GetClaimValue(this, "appctxsender");
if (appctxsender == null)
{
return null;
}
return appctxsender.Split('@')[0];
}
}
/// <summary>
/// The context token's "refreshtoken" claim
/// </summary>
public string RefreshToken
{
get
{
return GetClaimValue(this, "refreshtoken");
}
}
/// <summary>
/// The context token's "CacheKey" claim
/// </summary>
public string CacheKey
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string cacheKey = (string)dict["CacheKey"];
return cacheKey;
}
}
/// <summary>
/// The context token's "SecurityTokenServiceUri" claim
/// </summary>
public string SecurityTokenServiceUri
{
get
{
string appctx = GetClaimValue(this, "appctx");
if (appctx == null)
{
return null;
}
ClientContext ctx = new ClientContext("http://tempuri.org");
Dictionary<string, object> dict = (Dictionary<string, object>)ctx.ParseObjectFromJsonString(appctx);
string securityTokenServiceUri = (string)dict["SecurityTokenServiceUri"];
return securityTokenServiceUri;
}
}
/// <summary>
/// The realm portion of the context token's "audience" claim
/// </summary>
public string Realm
{
get
{
string aud = Audience;
if (aud == null)
{
return null;
}
string tokenRealm = aud.Substring(aud.IndexOf('@') + 1);
return tokenRealm;
}
}
private static string GetClaimValue(JsonWebSecurityToken token, string claimType)
{
if (token == null)
{
throw new ArgumentNullException("token");
}
foreach (JsonWebTokenClaim claim in token.Claims)
{
if (StringComparer.Ordinal.Equals(claim.ClaimType, claimType))
{
return claim.Value;
}
}
return null;
}
}
/// <summary>
/// Represents a security token which contains multiple security keys that are generated using symmetric algorithms.
/// </summary>
public class MultipleSymmetricKeySecurityToken : SecurityToken
{
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(IEnumerable<byte[]> keys)
: this(UniqueId.CreateUniqueId(), keys)
{
}
/// <summary>
/// Initializes a new instance of the MultipleSymmetricKeySecurityToken class.
/// </summary>
/// <param name="tokenId">The unique identifier of the security token.</param>
/// <param name="keys">An enumeration of Byte arrays that contain the symmetric keys.</param>
public MultipleSymmetricKeySecurityToken(string tokenId, IEnumerable<byte[]> keys)
{
if (keys == null)
{
throw new ArgumentNullException("keys");
}
if (String.IsNullOrEmpty(tokenId))
{
throw new ArgumentException("Value cannot be a null or empty string.", "tokenId");
}
foreach (byte[] key in keys)
{
if (key.Length <= 0)
{
throw new ArgumentException("The key length must be greater then zero.", "keys");
}
}
id = tokenId;
effectiveTime = DateTime.UtcNow;
securityKeys = CreateSymmetricSecurityKeys(keys);
}
/// <summary>
/// Gets the unique identifier of the security token.
/// </summary>
public override string Id
{
get
{
return id;
}
}
/// <summary>
/// Gets the cryptographic keys associated with the security token.
/// </summary>
public override ReadOnlyCollection<SecurityKey> SecurityKeys
{
get
{
return securityKeys.AsReadOnly();
}
}
/// <summary>
/// Gets the first instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidFrom
{
get
{
return effectiveTime;
}
}
/// <summary>
/// Gets the last instant in time at which this security token is valid.
/// </summary>
public override DateTime ValidTo
{
get
{
// Never expire
return DateTime.MaxValue;
}
}
/// <summary>
/// Returns a value that indicates whether the key identifier for this instance can be resolved to the specified key identifier.
/// </summary>
/// <param name="keyIdentifierClause">A SecurityKeyIdentifierClause to compare to this instance</param>
/// <returns>true if keyIdentifierClause is a SecurityKeyIdentifierClause and it has the same unique identifier as the Id property; otherwise, false.</returns>
public override bool MatchesKeyIdentifierClause(SecurityKeyIdentifierClause keyIdentifierClause)
{
if (keyIdentifierClause == null)
{
throw new ArgumentNullException("keyIdentifierClause");
}
// Since this is a symmetric token and we do not have IDs to distinguish tokens, we just check for the
// presence of a SymmetricIssuerKeyIdentifier. The actual mapping to the issuer takes place later
// when the key is matched to the issuer.
if (keyIdentifierClause is SymmetricIssuerKeyIdentifierClause)
{
return true;
}
return base.MatchesKeyIdentifierClause(keyIdentifierClause);
}
#region private members
private List<SecurityKey> CreateSymmetricSecurityKeys(IEnumerable<byte[]> keys)
{
List<SecurityKey> symmetricKeys = new List<SecurityKey>();
foreach (byte[] key in keys)
{
symmetricKeys.Add(new InMemorySymmetricSecurityKey(key));
}
return symmetricKeys;
}
private string id;
private DateTime effectiveTime;
private List<SecurityKey> securityKeys;
#endregion
}
}
| |
namespace System {
// This file defines an internal class used to throw exceptions in BCL code.
// The main purpose is to reduce code size.
//
// The old way to throw an exception generates quite a lot IL code and assembly code.
// Following is an example:
// C# source
// throw new ArgumentNullException("key", SR.GetString("ArgumentNull_Key"));
// IL code:
// IL_0003: ldstr "key"
// IL_0008: ldstr "ArgumentNull_Key"
// IL_000d: call string System.Environment::GetResourceString(string)
// IL_0012: newobj instance void System.ArgumentNullException::.ctor(string,string)
// IL_0017: throw
// which is 21bytes in IL.
//
// So we want to get rid of the ldstr and call to Environment.GetResource in IL.
// In order to do that, I created two enums: ExceptionResource, ExceptionArgument to represent the
// argument name and resource name in a small integer. The source code will be changed to
// ThrowHelper.ThrowArgumentNullException(ExceptionArgument.key, ExceptionResource.ArgumentNull_Key);
//
// The IL code will be 7 bytes.
// IL_0008: ldc.i4.4
// IL_0009: ldc.i4.4
// IL_000a: call void System.ThrowHelper::ThrowArgumentNullException(valuetype System.ExceptionArgument)
// IL_000f: ldarg.0
//
// This will also reduce the Jitted code size a lot.
//
// It is very important we do this for generic classes because we can easily generate the same code
// multiple times for different instantiation.
//
// <
#if !SILVERLIGHT
using System.Runtime.Serialization;
#endif
using System.Diagnostics;
internal static class ThrowHelper {
internal static void ThrowWrongKeyTypeArgumentException(object key, Type targetType) {
throw new ArgumentException(SR.GetString(SR.Arg_WrongType, key, targetType), "key");
}
internal static void ThrowWrongValueTypeArgumentException(object value, Type targetType) {
throw new ArgumentException(SR.GetString(SR.Arg_WrongType, value, targetType), "value");
}
internal static void ThrowKeyNotFoundException() {
throw new System.Collections.Generic.KeyNotFoundException();
}
internal static void ThrowArgumentException(ExceptionResource resource) {
throw new ArgumentException(SR.GetString(GetResourceName(resource)));
}
internal static void ThrowArgumentNullException(ExceptionArgument argument) {
throw new ArgumentNullException(GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument) {
throw new ArgumentOutOfRangeException(GetArgumentName(argument));
}
internal static void ThrowArgumentOutOfRangeException(ExceptionArgument argument, ExceptionResource resource) {
throw new ArgumentOutOfRangeException(GetArgumentName(argument), SR.GetString(GetResourceName(resource)));
}
internal static void ThrowInvalidOperationException(ExceptionResource resource) {
throw new InvalidOperationException(SR.GetString(GetResourceName(resource)));
}
#if !SILVERLIGHT
internal static void ThrowSerializationException(ExceptionResource resource) {
throw new SerializationException(SR.GetString(GetResourceName(resource)));
}
#endif
internal static void ThrowNotSupportedException(ExceptionResource resource) {
throw new NotSupportedException(SR.GetString(GetResourceName(resource)));
}
// Allow nulls for reference types and Nullable<U>, but not for value types.
internal static void IfNullAndNullsAreIllegalThenThrow<T>(object value, ExceptionArgument argName) {
// Note that default(T) is not equal to null for value types except when T is Nullable<U>.
if (value == null && !(default(T) == null))
ThrowHelper.ThrowArgumentNullException(argName);
}
//
// This function will convert an ExceptionArgument enum value to the argument name string.
//
internal static string GetArgumentName(ExceptionArgument argument) {
string argumentName = null;
switch (argument) {
case ExceptionArgument.array:
argumentName = "array";
break;
case ExceptionArgument.arrayIndex:
argumentName = "arrayIndex";
break;
case ExceptionArgument.capacity:
argumentName = "capacity";
break;
case ExceptionArgument.collection:
argumentName = "collection";
break;
case ExceptionArgument.converter:
argumentName = "converter";
break;
case ExceptionArgument.count:
argumentName = "count";
break;
case ExceptionArgument.dictionary:
argumentName = "dictionary";
break;
case ExceptionArgument.index:
argumentName = "index";
break;
case ExceptionArgument.info:
argumentName = "info";
break;
case ExceptionArgument.key:
argumentName = "key";
break;
case ExceptionArgument.match:
argumentName = "match";
break;
case ExceptionArgument.obj:
argumentName = "obj";
break;
case ExceptionArgument.queue:
argumentName = "queue";
break;
case ExceptionArgument.stack:
argumentName = "stack";
break;
case ExceptionArgument.startIndex:
argumentName = "startIndex";
break;
case ExceptionArgument.value:
argumentName = "value";
break;
case ExceptionArgument.item:
argumentName = "item";
break;
default:
Debug.Assert(false, "The enum value is not defined, please checked ExceptionArgumentName Enum.");
return string.Empty;
}
return argumentName;
}
//
// This function will convert an ExceptionResource enum value to the resource string.
//
internal static string GetResourceName(ExceptionResource resource) {
string resourceName = null;
switch (resource) {
case ExceptionResource.Argument_ImplementIComparable:
resourceName = SR.Argument_ImplementIComparable;
break;
case ExceptionResource.Argument_AddingDuplicate:
resourceName = SR.Argument_AddingDuplicate;
break;
case ExceptionResource.ArgumentOutOfRange_Index:
resourceName = SR.ArgumentOutOfRange_Index;
break;
case ExceptionResource.ArgumentOutOfRange_NeedNonNegNum:
resourceName = SR.ArgumentOutOfRange_NeedNonNegNum;
break;
case ExceptionResource.ArgumentOutOfRange_NeedNonNegNumRequired:
resourceName = SR.ArgumentOutOfRange_NeedNonNegNumRequired;
break;
case ExceptionResource.ArgumentOutOfRange_SmallCapacity:
resourceName = SR.ArgumentOutOfRange_SmallCapacity;
break;
case ExceptionResource.Arg_ArrayPlusOffTooSmall:
resourceName = SR.Arg_ArrayPlusOffTooSmall;
break;
case ExceptionResource.Arg_RankMultiDimNotSupported:
resourceName = SR.Arg_MultiRank;
break;
case ExceptionResource.Arg_NonZeroLowerBound:
resourceName = SR.Arg_NonZeroLowerBound;
break;
case ExceptionResource.Argument_InvalidArrayType:
resourceName = SR.Invalid_Array_Type;
break;
case ExceptionResource.Argument_InvalidOffLen:
resourceName = SR.Argument_InvalidOffLen;
break;
case ExceptionResource.InvalidOperation_CannotRemoveFromStackOrQueue:
resourceName = SR.InvalidOperation_CannotRemoveFromStackOrQueue;
break;
case ExceptionResource.InvalidOperation_EmptyCollection:
resourceName = SR.InvalidOperation_EmptyCollection;
break;
case ExceptionResource.InvalidOperation_EmptyQueue:
resourceName = SR.InvalidOperation_EmptyQueue;
break;
case ExceptionResource.InvalidOperation_EnumOpCantHappen:
resourceName = SR.InvalidOperation_EnumOpCantHappen;
break;
case ExceptionResource.InvalidOperation_EnumFailedVersion:
resourceName = SR.InvalidOperation_EnumFailedVersion;
break;
case ExceptionResource.InvalidOperation_EmptyStack:
resourceName = SR.InvalidOperation_EmptyStack;
break;
case ExceptionResource.InvalidOperation_EnumNotStarted:
resourceName = SR.InvalidOperation_EnumNotStarted;
break;
case ExceptionResource.InvalidOperation_EnumEnded:
resourceName = SR.InvalidOperation_EnumEnded;
break;
case ExceptionResource.NotSupported_KeyCollectionSet:
resourceName = SR.NotSupported_KeyCollectionSet;
break;
case ExceptionResource.NotSupported_SortedListNestedWrite:
resourceName = SR.NotSupported_SortedListNestedWrite;
break;
#if !SILVERLIGHT
case ExceptionResource.Serialization_InvalidOnDeser:
resourceName = SR.Serialization_InvalidOnDeser;
break;
case ExceptionResource.Serialization_MissingValues:
resourceName = SR.Serialization_MissingValues;
break;
case ExceptionResource.Serialization_MismatchedCount:
resourceName = SR.Serialization_MismatchedCount;
break;
#endif
case ExceptionResource.NotSupported_ValueCollectionSet:
resourceName = SR.NotSupported_ValueCollectionSet;
break;
default:
Debug.Assert(false, "The enum value is not defined, please checked ExceptionArgumentName Enum.");
return string.Empty;
}
return resourceName;
}
}
//
// The convention for this enum is using the argument name as the enum name
//
internal enum ExceptionArgument {
obj,
dictionary,
array,
info,
key,
collection,
match,
converter,
queue,
stack,
capacity,
index,
startIndex,
value,
count,
arrayIndex,
item,
}
//
// The convention for this enum is using the resource name as the enum name
//
internal enum ExceptionResource {
Argument_ImplementIComparable,
ArgumentOutOfRange_NeedNonNegNum,
ArgumentOutOfRange_NeedNonNegNumRequired,
Arg_ArrayPlusOffTooSmall,
Argument_AddingDuplicate,
Serialization_InvalidOnDeser,
Serialization_MismatchedCount,
Serialization_MissingValues,
Arg_RankMultiDimNotSupported,
Arg_NonZeroLowerBound,
Argument_InvalidArrayType,
NotSupported_KeyCollectionSet,
ArgumentOutOfRange_SmallCapacity,
ArgumentOutOfRange_Index,
Argument_InvalidOffLen,
NotSupported_ReadOnlyCollection,
InvalidOperation_CannotRemoveFromStackOrQueue,
InvalidOperation_EmptyCollection,
InvalidOperation_EmptyQueue,
InvalidOperation_EnumOpCantHappen,
InvalidOperation_EnumFailedVersion,
InvalidOperation_EmptyStack,
InvalidOperation_EnumNotStarted,
InvalidOperation_EnumEnded,
NotSupported_SortedListNestedWrite,
NotSupported_ValueCollectionSet,
}
}
| |
using System.Collections.Generic;
using System.Text;
using RabbitMQ.Client;
namespace EasyNetQ.Tests;
public sealed class BasicProperties : IBasicProperties
{
private string _contentType;
private string _contentEncoding;
private IDictionary<string, object> _headers;
private byte _deliveryMode;
private byte _priority;
private string _correlationId;
private string _replyTo;
private string _expiration;
private string _messageId;
private AmqpTimestamp _timestamp;
private string _type;
private string _userId;
private string _appId;
private string _clusterId;
private bool _contentType_present = false;
private bool _contentEncoding_present = false;
private bool _headers_present = false;
private bool _deliveryMode_present = false;
private bool _priority_present = false;
private bool _correlationId_present = false;
private bool _replyTo_present = false;
private bool _expiration_present = false;
private bool _messageId_present = false;
private bool _timestamp_present = false;
private bool _type_present = false;
private bool _userId_present = false;
private bool _appId_present = false;
private bool _clusterId_present = false;
public string ContentType
{
get => _contentType;
set
{
_contentType_present = value != null;
_contentType = value;
}
}
public string ContentEncoding
{
get => _contentEncoding;
set
{
_contentEncoding_present = value != null;
_contentEncoding = value;
}
}
public IDictionary<string, object> Headers
{
get => _headers;
set
{
_headers_present = value != null;
_headers = value;
}
}
public byte DeliveryMode
{
get => _deliveryMode;
set
{
_deliveryMode_present = true;
_deliveryMode = value;
}
}
public bool Persistent
{
get { return DeliveryMode == 2; }
set { DeliveryMode = value ? (byte)2 : (byte)1; }
}
public byte Priority
{
get => _priority;
set
{
_priority_present = true;
_priority = value;
}
}
public string CorrelationId
{
get => _correlationId;
set
{
_correlationId_present = value != null;
_correlationId = value;
}
}
public string ReplyTo
{
get => _replyTo;
set
{
_replyTo_present = value != null;
_replyTo = value;
}
}
public string Expiration
{
get => _expiration;
set
{
_expiration_present = value != null;
_expiration = value;
}
}
public string MessageId
{
get => _messageId;
set
{
_messageId_present = value != null;
_messageId = value;
}
}
public AmqpTimestamp Timestamp
{
get => _timestamp;
set
{
_timestamp_present = true;
_timestamp = value;
}
}
public string Type
{
get => _type;
set
{
_type_present = value != null;
_type = value;
}
}
public string UserId
{
get => _userId;
set
{
_userId_present = value != null;
_userId = value;
}
}
public string AppId
{
get => _appId;
set
{
_appId_present = value != null;
_appId = value;
}
}
public string ClusterId
{
get => _clusterId;
set
{
_clusterId_present = value != null;
_clusterId = value;
}
}
public void ClearContentType() => _contentType_present = false;
public void ClearContentEncoding() => _contentEncoding_present = false;
public void ClearHeaders() => _headers_present = false;
public void ClearDeliveryMode() => _deliveryMode_present = false;
public void ClearPriority() => _priority_present = false;
public void ClearCorrelationId() => _correlationId_present = false;
public void ClearReplyTo() => _replyTo_present = false;
public void ClearExpiration() => _expiration_present = false;
public void ClearMessageId() => _messageId_present = false;
public void ClearTimestamp() => _timestamp_present = false;
public void ClearType() => _type_present = false;
public void ClearUserId() => _userId_present = false;
public void ClearAppId() => _appId_present = false;
public void ClearClusterId() => _clusterId_present = false;
public bool IsContentTypePresent() => _contentType_present;
public bool IsContentEncodingPresent() => _contentEncoding_present;
public bool IsHeadersPresent() => _headers_present;
public bool IsDeliveryModePresent() => _deliveryMode_present;
public bool IsPriorityPresent() => _priority_present;
public bool IsCorrelationIdPresent() => _correlationId_present;
public bool IsReplyToPresent() => _replyTo_present;
public bool IsExpirationPresent() => _expiration_present;
public bool IsMessageIdPresent() => _messageId_present;
public bool IsTimestampPresent() => _timestamp_present;
public bool IsTypePresent() => _type_present;
public bool IsUserIdPresent() => _userId_present;
public bool IsAppIdPresent() => _appId_present;
public bool IsClusterIdPresent() => _clusterId_present;
public PublicationAddress ReplyToAddress
{
get { return PublicationAddress.Parse(ReplyTo); }
set { ReplyTo = value.ToString(); }
}
public BasicProperties() { }
public ushort ProtocolClassId => 60;
public string ProtocolClassName => "basic";
public void AppendPropertyDebugStringTo(StringBuilder sb)
{
sb.Append("(");
sb.Append("content-type="); sb.Append(_contentType_present ? (_contentType == null ? "(null)" : _contentType.ToString()) : "_"); sb.Append(", ");
sb.Append("content-encoding="); sb.Append(_contentEncoding_present ? (_contentEncoding == null ? "(null)" : _contentEncoding.ToString()) : "_"); sb.Append(", ");
sb.Append("headers="); sb.Append(_headers_present ? (_headers == null ? "(null)" : _headers.ToString()) : "_"); sb.Append(", ");
sb.Append("delivery-mode="); sb.Append(_deliveryMode_present ? _deliveryMode.ToString() : "_"); sb.Append(", ");
sb.Append("priority="); sb.Append(_priority_present ? _priority.ToString() : "_"); sb.Append(", ");
sb.Append("correlation-id="); sb.Append(_correlationId_present ? (_correlationId == null ? "(null)" : _correlationId.ToString()) : "_"); sb.Append(", ");
sb.Append("reply-to="); sb.Append(_replyTo_present ? (_replyTo == null ? "(null)" : _replyTo.ToString()) : "_"); sb.Append(", ");
sb.Append("expiration="); sb.Append(_expiration_present ? (_expiration == null ? "(null)" : _expiration.ToString()) : "_"); sb.Append(", ");
sb.Append("message-id="); sb.Append(_messageId_present ? (_messageId == null ? "(null)" : _messageId.ToString()) : "_"); sb.Append(", ");
sb.Append("timestamp="); sb.Append(_timestamp_present ? _timestamp.ToString() : "_"); sb.Append(", ");
sb.Append("type="); sb.Append(_type_present ? (_type == null ? "(null)" : _type.ToString()) : "_"); sb.Append(", ");
sb.Append("user-id="); sb.Append(_userId_present ? (_userId == null ? "(null)" : _userId.ToString()) : "_"); sb.Append(", ");
sb.Append("app-id="); sb.Append(_appId_present ? (_appId == null ? "(null)" : _appId.ToString()) : "_"); sb.Append(", ");
sb.Append("cluster-id="); sb.Append(_clusterId_present ? (_clusterId == null ? "(null)" : _clusterId.ToString()) : "_");
sb.Append(")");
}
}
| |
//
// LuaString.cs
//
// Author:
// Chris Howie <[email protected]>
//
// Copyright (c) 2013 Chris Howie
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
using System;
using System.Text;
using System.Collections;
namespace Eluant
{
public sealed class LuaString : LuaValueType,
IEquatable<LuaString>, IEquatable<string>,
IComparable, IComparable<LuaString>, IComparable<string>
{
private string stringValue;
private byte[] byteValue;
public string Value
{
get {
if (stringValue == null) {
if (byteValue.Length > 3 && byteValue[0] == 0x1B && byteValue[1] == 0x4C && byteValue[2] == 0x75 && byteValue[3] == 0x61)
{
// It is a binary chunk
StringBuilder s = new StringBuilder(byteValue.Length);
foreach (byte b in byteValue)
s.Append((char)b);
stringValue = s.ToString();
}
else
{
stringValue = Encoding.UTF8.GetString(byteValue, 0, byteValue.Length);
}
}
return stringValue;
}
}
public LuaString(string value)
{
if (value == null) { throw new ArgumentNullException("value"); }
stringValue = value;
byteValue = Encoding.UTF8.GetBytes(value);
}
public LuaString(byte[] value)
{
if (value == null) { throw new ArgumentNullException("value"); }
byteValue = (byte[])value.Clone();
}
public byte[] AsByteArray()
{
return (byte[])byteValue.Clone();
}
public override bool ToBoolean()
{
return true;
}
public override double? ToNumber()
{
double number;
if (double.TryParse(Value, out number)) {
return number;
}
return null;
}
public override string ToString()
{
return Value;
}
internal override object ToClrType(Type type)
{
if (type == typeof(string)) {
return Value;
}
if (type == typeof(byte[])) {
return AsByteArray();
}
return base.ToClrType(type);
}
public override bool Equals(LuaValue other)
{
return Equals(other as LuaString);
}
internal override void Push(LuaRuntime runtime)
{
// DW: Inserted at 06.01.2014, because of string length problems of strings with umlaute
LuaApi.lua_pushlstring(runtime.LuaState, byteValue,
#if WINDOWS_PHONE
//Encoding.UTF8.GetByteCount(Value)
byteValue.Length
#else
new UIntPtr(checked((uint)byteValue.Length))
#endif
);
}
public static implicit operator LuaString(string v)
{
return v == null ? null : new LuaString(v);
}
public static implicit operator string(LuaString s)
{
return object.ReferenceEquals(s, null) ? null : s.Value;
}
private int? hashCode = null;
public override int GetHashCode()
{
if (!hashCode.HasValue) {
hashCode = ByteArrayEqualityComparer.Instance.GetHashCode(byteValue);
}
return hashCode.Value;
}
public override bool Equals(object obj)
{
return Equals(obj as LuaString);
}
public bool Equals(LuaString obj)
{
if (object.ReferenceEquals(obj, this)) { return true; }
if (object.ReferenceEquals(obj, null)) { return false; }
return ByteArrayEqualityComparer.Instance.Equals(byteValue, obj.byteValue);
}
public bool Equals(string obj)
{
if (obj == null) { return false; }
return obj == Value;
}
// No (LuaString, LuaString) overload. With implicit conversion to string, that creates ambiguity.
public static bool operator==(LuaString a, LuaString b)
{
if (object.ReferenceEquals(a, null)) {
return object.ReferenceEquals(b, null);
}
if (object.ReferenceEquals(b, null)) {
return false;
}
return a.Equals(b);
}
public static bool operator!=(LuaString a, LuaString b)
{
return !(a == b);
}
public int CompareTo(LuaString s)
{
return CompareTo(object.ReferenceEquals(s, null) ? null : s.Value);
}
public int CompareTo(string s)
{
return Value.CompareTo(s);
}
public int CompareTo(object o)
{
var luaString = o as LuaString;
if (!object.ReferenceEquals(luaString, null)) { return CompareTo(luaString); }
var str = o as string;
if (str != null) { return CompareTo(str); }
throw new ArgumentException("Must be a LuaString or a String.", "o");
}
}
}
| |
#region License and Terms
// MoreLINQ - Extensions to LINQ to Objects
// Copyright (c) 2016 Atif Aziz. 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
#if !NO_ASYNC
namespace MoreLinq.Experimental
{
using System;
using System.Collections;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.ExceptionServices;
using System.Threading;
using System.Threading.Tasks;
using Unit = System.ValueTuple;
/// <summary>
/// Represents options for a query whose results evaluate asynchronously.
/// </summary>
public sealed class AwaitQueryOptions
{
/// <summary>
/// The default options used for a query whose results evaluate
/// asynchronously.
/// </summary>
public static readonly AwaitQueryOptions Default =
new AwaitQueryOptions(null /* = unbounded concurrency */,
TaskScheduler.Default,
preserveOrder: false);
/// <summary>
/// Gets a positive (non-zero) integer that specifies the maximum
/// number of asynchronous operations to have in-flight concurrently
/// or <c>null</c> to mean unlimited concurrency.
/// </summary>
public int? MaxConcurrency { get; }
/// <summary>
/// Get the scheduler to be used for any workhorse task.
/// </summary>
public TaskScheduler Scheduler { get; }
/// <summary>
/// Get a Boolean that determines whether results should be ordered
/// the same as the source.
/// </summary>
public bool PreserveOrder { get; }
AwaitQueryOptions(int? maxConcurrency, TaskScheduler scheduler, bool preserveOrder)
{
MaxConcurrency = maxConcurrency == null || maxConcurrency > 0
? maxConcurrency
: throw new ArgumentOutOfRangeException(
nameof(maxConcurrency), maxConcurrency,
"Maximum concurrency must be 1 or greater.");
Scheduler = scheduler ?? throw new ArgumentNullException(nameof(scheduler));
PreserveOrder = preserveOrder;
}
/// <summary>
/// Returns new options with the given concurrency limit.
/// </summary>
/// <param name="value">
/// The maximum concurrent asynchronous operation to keep in flight.
/// Use <c>null</c> to mean unbounded concurrency.</param>
/// <returns>Options with the new setting.</returns>
public AwaitQueryOptions WithMaxConcurrency(int? value) =>
value == MaxConcurrency ? this : new AwaitQueryOptions(value, Scheduler, PreserveOrder);
/// <summary>
/// Returns new options with the given scheduler.
/// </summary>
/// <param name="value">
/// The scheduler to use to for the workhorse task.</param>
/// <returns>Options with the new setting.</returns>
public AwaitQueryOptions WithScheduler(TaskScheduler value) =>
value == Scheduler ? this : new AwaitQueryOptions(MaxConcurrency, value, PreserveOrder);
/// <summary>
/// Returns new options with the given Boolean indicating whether or
/// not the results should be returned in the order of the source.
/// </summary>
/// <param name="value">
/// A Boolean where <c>true</c> means results are in source order and
/// <c>false</c> means that results can be delivered in order of
/// efficiency.</param>
/// <returns>Options with the new setting.</returns>
public AwaitQueryOptions WithPreserveOrder(bool value) =>
value == PreserveOrder ? this : new AwaitQueryOptions(MaxConcurrency, Scheduler, value);
}
/// <summary>
/// Represents a sequence whose elements or results evaluate asynchronously.
/// </summary>
/// <inheritdoc />
/// <typeparam name="T">The type of the source elements.</typeparam>
public interface IAwaitQuery<out T> : IEnumerable<T>
{
/// <summary>
/// The options that determine how the sequence evaluation behaves when
/// it is iterated.
/// </summary>
AwaitQueryOptions Options { get; }
/// <summary>
/// Returns a new query that will use the given options.
/// </summary>
/// <param name="options">The new options to use.</param>
/// <returns>
/// Returns a new query using the supplied options.
/// </returns>
IAwaitQuery<T> WithOptions(AwaitQueryOptions options);
}
static partial class ExperimentalEnumerable
{
/// <summary>
/// Converts a query whose results evaluate asynchronously to use
/// sequential instead of concurrent evaluation.
/// </summary>
/// <typeparam name="T">The type of the source elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <returns>The converted sequence.</returns>
public static IEnumerable<T> AsSequential<T>(this IAwaitQuery<T> source) =>
source.MaxConcurrency(1);
/// <summary>
/// Returns a query whose results evaluate asynchronously to use a
/// concurrency limit.
/// </summary>
/// <typeparam name="T">The type of the source elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="value"></param>
/// <returns>
/// A query whose results evaluate asynchronously using the given
/// concurrency limit.</returns>
public static IAwaitQuery<T> MaxConcurrency<T>(this IAwaitQuery<T> source, int value) =>
source.WithOptions(source.Options.WithMaxConcurrency(value));
/// <summary>
/// Returns a query whose results evaluate asynchronously and
/// concurrently with no defined limitation on concurrency.
/// </summary>
/// <typeparam name="T">The type of the source elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <returns>
/// A query whose results evaluate asynchronously using no defined
/// limitation on concurrency.</returns>
public static IAwaitQuery<T> UnboundedConcurrency<T>(this IAwaitQuery<T> source) =>
source.WithOptions(source.Options.WithMaxConcurrency(null));
/// <summary>
/// Returns a query whose results evaluate asynchronously and uses the
/// given scheduler for the workhorse task.
/// </summary>
/// <typeparam name="T">The type of the source elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="value">The scheduler to use.</param>
/// <returns>
/// A query whose results evaluate asynchronously and uses the
/// given scheduler for the workhorse task.</returns>
public static IAwaitQuery<T> Scheduler<T>(this IAwaitQuery<T> source, TaskScheduler value)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (value == null) throw new ArgumentNullException(nameof(value));
return source.WithOptions(source.Options.WithScheduler(value));
}
/// <summary>
/// Returns a query whose results evaluate asynchronously but which
/// are returned in the order of the source.
/// </summary>
/// <typeparam name="T">The type of the source elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <returns>
/// A query whose results evaluate asynchronously but which
/// are returned in the order of the source.</returns>
/// <remarks>
/// Internally, the asynchronous operations will be done concurrently
/// but the results will be yielded in order.
/// </remarks>
public static IAwaitQuery<T> AsOrdered<T>(this IAwaitQuery<T> source) =>
PreserveOrder(source, true);
/// <summary>
/// Returns a query whose results evaluate asynchronously but which
/// are returned without guarantee of the source order.
/// </summary>
/// <typeparam name="T">The type of the source elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <returns>
/// A query whose results evaluate asynchronously but which
/// are returned without guarantee of the source order.</returns>
public static IAwaitQuery<T> AsUnordered<T>(this IAwaitQuery<T> source) =>
PreserveOrder(source, false);
/// <summary>
/// Returns a query whose results evaluate asynchronously and a Boolean
/// argument indicating whether the source order of the results is
/// preserved.
/// </summary>
/// <typeparam name="T">The type of the source elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="value">
/// A Boolean where <c>true</c> means results are in source order and
/// <c>false</c> means that results can be delivered in order of
/// efficiency.</param>
/// <returns>
/// A query whose results evaluate asynchronously and returns the
/// results ordered or unordered based on <paramref name="value"/>.
/// </returns>
public static IAwaitQuery<T> PreserveOrder<T>(this IAwaitQuery<T> source, bool value) =>
source.WithOptions(source.Options.WithPreserveOrder(value));
/// <summary>
/// Creates a sequence query that streams the result of each task in
/// the source sequence as it completes asynchronously.
/// </summary>
/// <typeparam name="T">
/// The type of each task's result as well as the type of the elements
/// of the resulting sequence.</typeparam>
/// <param name="source">The source sequence of tasks.</param>
/// <returns>
/// A sequence query that streams the result of each task in
/// <paramref name="source"/> as it completes asynchronously.
/// </returns>
/// <remarks>
/// <para>
/// This method uses deferred execution semantics. The results are
/// yielded as each asynchronous task completes and, by default,
/// not guaranteed to be based on the source sequence order. If order
/// is important, compose further with
/// <see cref="AsOrdered{T}"/>.</para>
/// <para>
/// This method starts a new task where the tasks are awaited. If the
/// resulting sequence is partially consumed then there's a good chance
/// that some tasks will be wasted, those that are in flight.</para>
/// <para>
/// The tasks in <paramref name="source"/> are already assumed to be in
/// flight therefore changing concurrency options via
/// <see cref="AsSequential{T}"/>, <see cref="MaxConcurrency{T}"/> or
/// <see cref="UnboundedConcurrency{T}"/> will only change how many
/// tasks are awaited at any given moment, not how many will be
/// kept in flight. For the latter effect, use the other overload.
/// </para>
/// </remarks>
public static IAwaitQuery<T> Await<T>(this IEnumerable<Task<T>> source) =>
source.Await((e, _) => e);
/// <summary>
/// Creates a sequence query that streams the result of each task in
/// the source sequence as it completes asynchronously. A
/// <see cref="CancellationToken"/> is passed for each asynchronous
/// evaluation to abort any asynchronous operations in flight if the
/// sequence is not fully iterated.
/// </summary>
/// <typeparam name="T">The type of the source elements.</typeparam>
/// <typeparam name="TResult">The type of the result elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="evaluator">A function to begin the asynchronous
/// evaluation of each element, the second parameter of which is a
/// <see cref="CancellationToken"/> that can be used to abort
/// asynchronous operations.</param>
/// <returns>
/// A sequence query that stream its results as they are
/// evaluated asynchronously.
/// </returns>
/// <remarks>
/// <para>
/// This method uses deferred execution semantics. The results are
/// yielded as each asynchronous evaluation completes and, by default,
/// not guaranteed to be based on the source sequence order. If order
/// is important, compose further with
/// <see cref="AsOrdered{T}"/>.</para>
/// <para>
/// This method starts a new task where the asynchronous evaluations
/// take place and awaited. If the resulting sequence is partially
/// consumed then there's a good chance that some projection work will
/// be wasted and a cooperative effort is done that depends on the
/// <paramref name="evaluator"/> function (via a
/// <see cref="CancellationToken"/> as its second argument) to cancel
/// those in flight.</para>
/// <para>
/// The <paramref name="evaluator"/> function should be designed to be
/// thread-agnostic.</para>
/// <para>
/// The task returned by <paramref name="evaluator"/> should be started
/// when the function is called (and not just a mere projection)
/// otherwise changing concurrency options via
/// <see cref="AsSequential{T}"/>, <see cref="MaxConcurrency{T}"/> or
/// <see cref="UnboundedConcurrency{T}"/> will only change how many
/// tasks are awaited at any given moment, not how many will be
/// kept in flight.
/// </para>
/// </remarks>
public static IAwaitQuery<TResult> Await<T, TResult>(
this IEnumerable<T> source, Func<T, CancellationToken, Task<TResult>> evaluator) =>
AwaitQuery.Create(options =>
from t in source.AwaitCompletion(evaluator, (_, t) => t)
.WithOptions(options)
select t.GetAwaiter().GetResult());
/*
/// <summary>
/// Awaits completion of all asynchronous evaluations.
/// </summary>
public static IAwaitQuery<TResult> AwaitCompletion<T, TT, TResult>(
this IEnumerable<T> source,
Func<T, CancellationToken, Task<TT>> evaluator,
Func<T, TT, TResult> resultSelector,
Func<T, Exception, TResult> errorSelector,
Func<T, TResult> cancellationSelector) =>
AwaitQuery.Create(options =>
from e in source.AwaitCompletion(evaluator, (item, task) => (Item: item, Task: task))
.WithOptions(options)
select e.Task.IsFaulted
? errorSelector(e.Item, e.Task.Exception)
: e.Task.IsCanceled
? cancellationSelector(e.Item)
: resultSelector(e.Item, e.Task.Result));
*/
/// <summary>
/// Awaits completion of all asynchronous evaluations irrespective of
/// whether they succeed or fail. An additional argument specifies a
/// function that projects the final result given the source item and
/// completed task.
/// </summary>
/// <typeparam name="T">The type of the source elements.</typeparam>
/// <typeparam name="TTaskResult"> The type of the tasks's result.</typeparam>
/// <typeparam name="TResult">The type of the result elements.</typeparam>
/// <param name="source">The source sequence.</param>
/// <param name="evaluator">A function to begin the asynchronous
/// evaluation of each element, the second parameter of which is a
/// <see cref="CancellationToken"/> that can be used to abort
/// asynchronous operations.</param>
/// <param name="resultSelector">A fucntion that projects the final
/// result given the source item and its asynchronous completion
/// result.</param>
/// <returns>
/// A sequence query that stream its results as they are
/// evaluated asynchronously.
/// </returns>
/// <remarks>
/// <para>
/// This method uses deferred execution semantics. The results are
/// yielded as each asynchronous evaluation completes and, by default,
/// not guaranteed to be based on the source sequence order. If order
/// is important, compose further with
/// <see cref="AsOrdered{T}"/>.</para>
/// <para>
/// This method starts a new task where the asynchronous evaluations
/// take place and awaited. If the resulting sequence is partially
/// consumed then there's a good chance that some projection work will
/// be wasted and a cooperative effort is done that depends on the
/// <paramref name="evaluator"/> function (via a
/// <see cref="CancellationToken"/> as its second argument) to cancel
/// those in flight.</para>
/// <para>
/// The <paramref name="evaluator"/> function should be designed to be
/// thread-agnostic.</para>
/// <para>
/// The task returned by <paramref name="evaluator"/> should be started
/// when the function is called (and not just a mere projection)
/// otherwise changing concurrency options via
/// <see cref="AsSequential{T}"/>, <see cref="MaxConcurrency{T}"/> or
/// <see cref="UnboundedConcurrency{T}"/> will only change how many
/// tasks are awaited at any given moment, not how many will be
/// kept in flight.
/// </para>
/// </remarks>
public static IAwaitQuery<TResult> AwaitCompletion<T, TTaskResult, TResult>(
this IEnumerable<T> source,
Func<T, CancellationToken, Task<TTaskResult>> evaluator,
Func<T, Task<TTaskResult>, TResult> resultSelector)
{
if (source == null) throw new ArgumentNullException(nameof(source));
if (evaluator == null) throw new ArgumentNullException(nameof(evaluator));
return
AwaitQuery.Create(
options => _(options.MaxConcurrency,
options.Scheduler ?? TaskScheduler.Default,
options.PreserveOrder));
IEnumerable<TResult> _(int? maxConcurrency, TaskScheduler scheduler, bool ordered)
{
// A separate task will enumerate the source and launch tasks.
// It will post all progress as notices to the collection below.
// A notice is essentially a discriminated union like:
//
// type Notice<'a, 'b> =
// | End
// | Result of (int * 'a * Task<'b>)
// | Error of ExceptionDispatchInfo
//
// Note that BlockingCollection.CompleteAdding is never used to
// to mark the end (which its own notice above) because
// BlockingCollection.Add throws if called after CompleteAdding
// and we want to deliberately tolerate the race condition.
var notices = new BlockingCollection<(Notice, (int, T, Task<TTaskResult>), ExceptionDispatchInfo?)>();
var consumerCancellationTokenSource = new CancellationTokenSource();
(Exception?, Exception?) lastCriticalErrors = default;
var completed = false;
var cancellationTokenSource = new CancellationTokenSource();
var enumerator = source.Index().GetEnumerator();
IDisposable disposable = enumerator; // disables AccessToDisposedClosure warnings
try
{
var cancellationToken = cancellationTokenSource.Token;
// Fire-up a parallel loop to iterate through the source and
// launch tasks, posting a result-notice as each task
// completes and another, an end-notice, when all tasks have
// completed.
Task.Factory.StartNew(
async () =>
{
try
{
await enumerator.StartAsync(
e => evaluator(e.Value, cancellationToken),
(e, r) => PostNotice(Notice.Result, (e.Key, e.Value, r), default),
() => PostNotice(Notice.End, default, default),
maxConcurrency, cancellationToken);
}
catch (Exception e)
{
PostNotice(Notice.Error, default, e);
}
void PostNotice(Notice notice,
(int, T, Task<TTaskResult>) item,
Exception? error)
{
// If a notice fails to post then assume critical error
// conditions (like low memory), capture the error without
// further allocation of resources and trip the cancellation
// token source used by the main loop waiting on notices.
// Note that only the "last" critical error is reported
// as maintaining a list would incur allocations. The idea
// here is to make a best effort attempt to report any of
// the error conditions that may be occuring, which is still
// better than nothing.
try
{
var edi = error != null
? ExceptionDispatchInfo.Capture(error)
: null;
notices.Add((notice, item, edi));
}
catch (Exception e)
{
// Don't use ExceptionDispatchInfo.Capture here to avoid
// inducing allocations if already under low memory
// conditions.
lastCriticalErrors = (e, error);
consumerCancellationTokenSource.Cancel();
throw;
}
}
},
CancellationToken.None,
TaskCreationOptions.DenyChildAttach,
scheduler);
// Remainder here is the main loop that waits for and
// processes notices.
var nextKey = 0;
var holds = ordered ? new List<(int, T, Task<TTaskResult>)>() : null;
using (var notice = notices.GetConsumingEnumerable(consumerCancellationTokenSource.Token)
.GetEnumerator())
while (true)
{
try
{
if (!notice.MoveNext())
break;
}
catch (OperationCanceledException e) when (e.CancellationToken == consumerCancellationTokenSource.Token)
{
var (error1, error2) = lastCriticalErrors;
throw new Exception("One or more critical errors have occurred.",
error2 != null ? new AggregateException(error1, error2)
: new AggregateException(error1));
}
var (kind, result, error) = notice.Current;
if (kind == Notice.Error)
{
error!.Throw();
}
if (kind == Notice.End)
break;
Debug.Assert(kind == Notice.Result);
var (key, inp, value) = result;
if (holds == null || key == nextKey)
{
// If order does not need to be preserved or the key
// is the next that should be yielded then yield
// the result.
yield return resultSelector(inp, value);
if (holds != null) // preserve order?
{
// Release withheld results consecutive in key
// order to the one just yielded...
var releaseCount = 0;
for (nextKey++; holds.Count > 0; nextKey++)
{
var (candidateKey, ic, candidate) = holds[0];
if (candidateKey != nextKey)
break;
releaseCount++;
yield return resultSelector(ic, candidate);
}
holds.RemoveRange(0, releaseCount);
}
}
else
{
// Received a result out of order when order must be
// preserved, so withhold the result by finding out
// where it belongs in the order of results withheld
// so far and insert it in the list.
var i = holds.BinarySearch(result, TupleComparer<int, T, Task<TTaskResult>>.Item1);
Debug.Assert(i < 0);
holds.Insert(~i, result);
}
}
if (holds?.Count > 0) // yield any withheld, which should be in order...
{
foreach (var (key, x, value) in holds)
{
Debug.Assert(nextKey++ == key); //...assert so!
yield return resultSelector(x, value);
}
}
completed = true;
}
finally
{
// The cancellation token is signaled here for the case where
// tasks may be in flight but the user stopped the enumeration
// partway (e.g. Await was combined with a Take or TakeWhile).
// The in-flight tasks need to be aborted as well as the
// awaiter loop.
if (!completed)
cancellationTokenSource.Cancel();
disposable.Dispose();
}
}
}
enum Notice { End, Result, Error }
static async Task StartAsync<T, TResult>(
this IEnumerator<T> enumerator,
Func<T, Task<TResult>> starter,
Action<T, Task<TResult>> onTaskCompletion,
Action onEnd,
int? maxConcurrency,
CancellationToken cancellationToken)
{
if (enumerator == null) throw new ArgumentNullException(nameof(enumerator));
if (starter == null) throw new ArgumentNullException(nameof(starter));
if (onTaskCompletion == null) throw new ArgumentNullException(nameof(onTaskCompletion));
if (onEnd == null) throw new ArgumentNullException(nameof(onEnd));
if (maxConcurrency < 1) throw new ArgumentOutOfRangeException(nameof(maxConcurrency));
using (enumerator)
{
var pendingCount = 1; // terminator
void OnPendingCompleted()
{
if (Interlocked.Decrement(ref pendingCount) == 0)
onEnd();
}
var concurrencyGate = maxConcurrency is {} count
? new ConcurrencyGate(count)
: ConcurrencyGate.Unbounded;
while (enumerator.MoveNext())
{
try
{
await concurrencyGate.EnterAsync(cancellationToken);
}
catch (OperationCanceledException e) when (e.CancellationToken == cancellationToken)
{
return;
}
Interlocked.Increment(ref pendingCount);
var item = enumerator.Current;
var task = starter(item);
// Add a continutation that notifies completion of the task,
// along with the necessary housekeeping, in case it
// completes before maximum concurrency is reached.
#pragma warning disable 4014 // https://docs.microsoft.com/en-us/dotnet/csharp/language-reference/compiler-messages/cs4014
task.ContinueWith(cancellationToken: cancellationToken,
continuationOptions: TaskContinuationOptions.ExecuteSynchronously,
scheduler: TaskScheduler.Current,
continuationAction: t =>
{
concurrencyGate.Exit();
if (cancellationToken.IsCancellationRequested)
return;
onTaskCompletion(item, t);
OnPendingCompleted();
});
#pragma warning restore 4014
}
OnPendingCompleted();
}
}
static class AwaitQuery
{
public static IAwaitQuery<T>
Create<T>(
Func<AwaitQueryOptions, IEnumerable<T>> impl,
AwaitQueryOptions? options = null) =>
new AwaitQuery<T>(impl, options);
}
sealed class AwaitQuery<T> : IAwaitQuery<T>
{
readonly Func<AwaitQueryOptions, IEnumerable<T>> _impl;
public AwaitQuery(Func<AwaitQueryOptions, IEnumerable<T>> impl,
AwaitQueryOptions? options = null)
{
_impl = impl;
Options = options ?? AwaitQueryOptions.Default;
}
public AwaitQueryOptions Options { get; }
public IAwaitQuery<T> WithOptions(AwaitQueryOptions options)
{
if (options == null) throw new ArgumentNullException(nameof(options));
return Options == options ? this : new AwaitQuery<T>(_impl, options);
}
public IEnumerator<T> GetEnumerator() => _impl(Options).GetEnumerator();
IEnumerator IEnumerable.GetEnumerator() => GetEnumerator();
}
static class TupleComparer<T1, T2, T3>
{
public static readonly IComparer<(T1, T2, T3)> Item1 =
Comparer<(T1, T2, T3)>.Create((x, y) => Comparer<T1>.Default.Compare(x.Item1, y.Item1));
public static readonly IComparer<(T1, T2, T3)> Item2 =
Comparer<(T1, T2, T3)>.Create((x, y) => Comparer<T2>.Default.Compare(x.Item2, y.Item2));
public static readonly IComparer<(T1, T2, T3)> Item3 =
Comparer<(T1, T2, T3)>.Create((x, y) => Comparer<T3>.Default.Compare(x.Item3, y.Item3));
}
static class CompletedTask
{
#if NET451 || NETSTANDARD1_0
public static readonly Task Instance;
static CompletedTask()
{
var tcs = new TaskCompletionSource<Unit>();
tcs.SetResult(default);
Instance = tcs.Task;
}
#else
public static readonly Task Instance = Task.CompletedTask;
#endif
}
sealed class ConcurrencyGate
{
public static readonly ConcurrencyGate Unbounded = new ConcurrencyGate();
readonly SemaphoreSlim? _semaphore;
ConcurrencyGate(SemaphoreSlim? semaphore = null) =>
_semaphore = semaphore;
public ConcurrencyGate(int max) :
this(new SemaphoreSlim(max, max)) {}
public Task EnterAsync(CancellationToken token)
{
if (_semaphore == null)
{
token.ThrowIfCancellationRequested();
return CompletedTask.Instance;
}
return _semaphore.WaitAsync(token);
}
public void Exit() =>
_semaphore?.Release();
}
}
}
#endif // !NO_ASYNC
| |
using UnityEngine;
using System.Collections;
[AddComponentMenu("2D Toolkit/Sprite/tk2dAnimatedSprite (Obsolete)")]
public class tk2dAnimatedSprite : tk2dSprite
{
#region SpriteAnimatorRouting
[SerializeField] tk2dSpriteAnimator _animator = null;
public tk2dSpriteAnimator Animator {
get {
CheckAddAnimatorInternal();
return _animator;
}
}
void CheckAddAnimatorInternal() {
if (_animator == null) {
_animator = gameObject.GetComponent<tk2dSpriteAnimator>();
if (_animator == null) {
_animator = gameObject.AddComponent<tk2dSpriteAnimator>();
_animator.Library = anim;
_animator.DefaultClipId = clipId;
_animator.playAutomatically = playAutomatically;
}
}
}
#endregion
// Required for serialization
[SerializeField] private tk2dSpriteAnimation anim;
[SerializeField] private int clipId = 0;
public bool playAutomatically = false;
public bool createCollider = false;
// Required for backwards compatility
protected override bool NeedBoxCollider() {
return createCollider;
}
public tk2dSpriteAnimation Library {
get {
return Animator.Library;
}
set {
Animator.Library = value;
}
}
public int DefaultClipId {
get {
return Animator.DefaultClipId;
}
set {
Animator.DefaultClipId = value;
}
}
// Wrapped functions
public static bool g_paused
{
get { return tk2dSpriteAnimator.g_Paused; }
set { tk2dSpriteAnimator.g_Paused = value; }
}
public bool Paused
{
get { return Animator.Paused; }
set { Animator.Paused = value; }
}
/// <summary>
/// Animation complete delegate
/// </summary>
public delegate void AnimationCompleteDelegate(tk2dAnimatedSprite sprite, int clipId);
/// <summary>
/// Animation complete event. This is called when the animation has completed playing. Will not trigger on looped animations
/// </summary>
public AnimationCompleteDelegate animationCompleteDelegate;
/// <summary>
/// Animation event delegate.
/// </summary>
public delegate void AnimationEventDelegate(tk2dAnimatedSprite sprite, tk2dSpriteAnimationClip clip, tk2dSpriteAnimationFrame frame, int frameNum);
/// <summary>
/// Animation event. This is called when the frame displayed has <see cref="tk2dSpriteAnimationFrame.triggerEvent"/> set.
/// The triggering frame is passed to the delegate, and the eventInfo / Int / Float can be extracted from there.
/// </summary>
public AnimationEventDelegate animationEventDelegate;
void ProxyCompletedHandler(tk2dSpriteAnimator anim, tk2dSpriteAnimationClip clip) {
if (animationCompleteDelegate != null) {
int clipId = -1;
tk2dSpriteAnimationClip[] clips = (anim.Library != null) ? anim.Library.clips : null;
if (clips != null) {
for (int i = 0; i < clips.Length; ++i) {
if (clips[i] == clip) {
clipId = i;
break;
}
}
}
animationCompleteDelegate(this, clipId);
}
}
void ProxyEventTriggeredHandler(tk2dSpriteAnimator anim, tk2dSpriteAnimationClip clip, int frame) {
if (animationEventDelegate != null) {
animationEventDelegate(this, clip, clip.frames[frame], frame);
}
}
void OnEnable() {
Animator.AnimationCompleted = ProxyCompletedHandler;
Animator.AnimationEventTriggered = ProxyEventTriggeredHandler;
}
void OnDisable() {
Animator.AnimationCompleted = null;
Animator.AnimationEventTriggered = null;
}
// execution order on tk2dSpriteAnimator should be AFTER tk2dAnimatedSprite
void Start()
{
CheckAddAnimatorInternal();
}
/// <summary>
/// Adds a tk2dAnimatedSprite as a component to the gameObject passed in, setting up necessary parameters and building geometry.
/// </summary>
public static tk2dAnimatedSprite AddComponent(GameObject go, tk2dSpriteAnimation anim, int clipId)
{
var clip = anim.clips[clipId];
tk2dAnimatedSprite animSprite = go.AddComponent<tk2dAnimatedSprite>();
animSprite.SetSprite(clip.frames[0].spriteCollection, clip.frames[0].spriteId);
animSprite.anim = anim;
return animSprite;
}
#region Play
public void Play() {
if (Animator.DefaultClip != null) {
Animator.Play(Animator.DefaultClip);
}
}
public void Play(float clipStartTime) {
if (Animator.DefaultClip != null) {
Animator.PlayFrom(Animator.DefaultClip, clipStartTime);
}
}
public void PlayFromFrame(int frame) {
if (Animator.DefaultClip != null) {
Animator.PlayFromFrame(Animator.DefaultClip, frame);
}
}
public void Play(string name) {
Animator.Play(name);
}
public void PlayFromFrame(string name, int frame) {
Animator.PlayFromFrame(name, frame);
}
public void Play(string name, float clipStartTime) {
Animator.PlayFrom(name, clipStartTime);
}
public void Play(tk2dSpriteAnimationClip clip, float clipStartTime) {
Animator.PlayFrom(clip, clipStartTime);
}
public void Play(tk2dSpriteAnimationClip clip, float clipStartTime, float overrideFps) {
Animator.Play(clip, clipStartTime, overrideFps);
}
#endregion
public tk2dSpriteAnimationClip CurrentClip { get { return Animator.CurrentClip; } }
public float ClipTimeSeconds { get { return Animator.ClipTimeSeconds; } }
public float ClipFps {
get { return Animator.ClipFps; }
set { Animator.ClipFps = value; }
}
public void Stop() {
Animator.Stop();
}
public void StopAndResetFrame() {
Animator.StopAndResetFrame();
}
[System.Obsolete]
public bool isPlaying() {
return Animator.Playing;
}
public bool IsPlaying(string name) {
return Animator.Playing;
}
public bool IsPlaying(tk2dSpriteAnimationClip clip) {
return Animator.IsPlaying(clip);
}
public bool Playing {
get { return Animator.Playing; }
}
public int GetClipIdByName(string name) {
return Animator.GetClipIdByName(name);
}
public tk2dSpriteAnimationClip GetClipByName(string name) {
return Animator.GetClipByName(name);
}
public static float DefaultFps { get { return tk2dSpriteAnimator.DefaultFps; } }
public void Pause() {
Animator.Pause();
}
public void Resume() {
Animator.Resume();
}
public void SetFrame(int currFrame) {
Animator.SetFrame(currFrame);
}
public void SetFrame(int currFrame, bool triggerEvent) {
Animator.SetFrame(currFrame, triggerEvent);
}
public void UpdateAnimation(float deltaTime) {
Animator.UpdateAnimation(deltaTime);
}
}
| |
// 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.Text;
using System.Xml;
namespace System.Runtime.Serialization.Xml.Canonicalization.Tests
{
internal static class C14nUtil
{
public const string NamespaceUrlForXmlPrefix = "http://www.w3.org/XML/1998/namespace";
public static bool IsEmptyDefaultNamespaceDeclaration(string prefix, string value)
{
return prefix.Length == 0 && value.Length == 0;
}
public static bool IsXmlPrefixDeclaration(string prefix, string value)
{
return prefix == "xml" && value == NamespaceUrlForXmlPrefix;
}
public static string[] TokenizeInclusivePrefixList(string prefixList)
{
if (prefixList == null)
{
return null;
}
string[] prefixes = prefixList.Split(null);
int count = 0;
for (int i = 0; i < prefixes.Length; i++)
{
string prefix = prefixes[i];
if (prefix == "#default")
{
prefixes[count++] = string.Empty;
}
else if (prefix.Length > 0)
{
prefixes[count++] = prefix;
}
}
if (count == 0)
{
return null;
}
else if (count == prefixes.Length)
{
return prefixes;
}
else
{
string[] result = new string[count];
Array.Copy(prefixes, result, count);
return result;
}
}
}
internal sealed class CanonicalEncoder
{
private const char Char10 = (char)10;
private const char Char13 = (char)13;
private const char Char9 = (char)9;
private const char Char32 = (char)32;
private const string Char13String = "\r";
private const string Char13EntityReference = "
";
private const int charBufSize = 252;
private const int byteBufSize = charBufSize * 4 + 4;
internal static readonly UTF8Encoding Utf8WithoutPreamble = new UTF8Encoding(false);
private readonly Encoder _encoder;
private readonly byte[] _byteBuf;
private readonly char[] _charBuf;
private int _count;
private Stream _stream;
private bool _needsReset;
public CanonicalEncoder(Stream stream)
{
_encoder = Utf8WithoutPreamble.GetEncoder();
_charBuf = new char[charBufSize];
_byteBuf = new byte[byteBufSize];
SetOutput(stream);
}
public void Encode(char c)
{
if (_count >= charBufSize)
{
WriteBuffer(false);
}
_charBuf[_count++] = c;
}
public void Encode(string str)
{
unsafe
{
fixed (char* start = str)
{
char* end = start + str.Length;
for (char* p = start; p < end; p++)
{
Encode(*p);
}
}
}
}
public void Encode(char[] buffer, int offset, int count)
{
ValidateBufferBounds(buffer, offset, count);
unsafe
{
fixed (char* bufferStart = buffer)
{
char* start = bufferStart + offset;
char* end = bufferStart + (offset + count);
for (char* p = start; p < end; p++)
{
Encode(*p);
}
}
}
}
public void EncodeAttribute(string prefix, string localName, string value)
{
Encode(' ');
if (prefix == null || prefix.Length == 0)
{
Encode(localName);
}
else
{
Encode(prefix);
Encode(':');
Encode(localName);
}
Encode("=\"");
EncodeWithTranslation(value, CanonicalEncoder.XmlStringType.AttributeValue);
Encode('\"');
}
public void EncodeComment(string value, XmlDocumentPosition docPosition)
{
if (docPosition == XmlDocumentPosition.AfterRootElement)
{
Encode(Char10);
}
Encode("<!--");
EncodeWithLineBreakNormalization(value);
Encode("-->");
if (docPosition == XmlDocumentPosition.BeforeRootElement)
{
Encode(Char10);
}
}
public void EncodeEndElement(string prefix, string localName)
{
Encode("</");
if (prefix.Length != 0)
{
Encode(prefix);
Encode(':');
}
Encode(localName);
Encode('>');
}
public void EncodeStartElementOpen(string prefix, string localName)
{
Encode("<");
if (prefix.Length != 0)
{
Encode(prefix);
Encode(':');
}
Encode(localName);
}
public void EncodeStartElementClose()
{
Encode('>');
}
public void EncodeWithLineBreakNormalization(string str)
{
unsafe
{
fixed (char* start = str)
{
char* end = start + str.Length;
for (char* p = start; p < end; p++)
{
if (*p == Char13)
{
Encode(Char13EntityReference);
}
else
{
Encode(*p);
}
}
}
}
}
public void EncodeWithTranslation(char[] buffer, int offset, int count, XmlStringType valueType)
{
ValidateBufferBounds(buffer, offset, count);
unsafe
{
fixed (char* bufferStart = buffer)
{
char* start = bufferStart + offset;
char* end = bufferStart + (offset + count);
EncodeWithTranslation(start, end, valueType);
}
}
}
public void EncodeWithTranslation(string str, XmlStringType valueType)
{
unsafe
{
fixed (char* start = str)
{
char* end = start + str.Length;
EncodeWithTranslation(start, end, valueType);
}
}
}
private unsafe void EncodeWithTranslation(char* start, char* end, XmlStringType valueType)
{
for (char* p = start; p < end; p++)
{
switch (*p)
{
case '&':
Encode("&");
break;
case '<':
Encode("<");
break;
case '>':
if (valueType != XmlStringType.AttributeValue)
{
Encode(">");
}
else
{
Encode(*p);
}
break;
case Char13:
Encode(Char13EntityReference);
break;
case Char10:
if (valueType == XmlStringType.AttributeValue)
{
Encode("
");
}
else
{
Encode(*p);
}
break;
case Char9:
if (valueType == XmlStringType.AttributeValue)
{
Encode("	");
}
else
{
Encode(*p);
}
break;
case '\"':
if (valueType == XmlStringType.AttributeValue)
{
Encode(""");
}
else
{
Encode(*p);
}
break;
default:
Encode(*p);
break;
}
}
}
public void Flush()
{
WriteBuffer(true);
}
public void Reset()
{
Flush();
if (_needsReset)
{
_encoder.Reset();
_needsReset = false;
}
}
public void SetOutput(Stream stream)
{
Reset();
_stream = stream;
}
private void WriteBuffer(bool flush)
{
if (_count > 0)
{
int numBytesAdded = _encoder.GetBytes(_charBuf, 0, _count, _byteBuf, 0, flush);
WriteBufferCore(_byteBuf, 0, numBytesAdded, flush);
_count = 0;
}
}
private void WriteBufferCore(byte[] buffer, int offset, int count, bool flush)
{
_needsReset = true;
_stream.Write(buffer, offset, count);
if (flush)
{
_stream.Flush();
}
}
public static void WriteEscapedChars(XmlWriter writer, char[] buffer, int index, int count)
{
int unescapedSegmentStart = index;
int bound = index + count;
for (int i = index; i < bound; i++)
{
if (buffer[i] == Char13)
{
if (unescapedSegmentStart < i)
{
writer.WriteChars(buffer, unescapedSegmentStart, i - unescapedSegmentStart);
}
writer.WriteCharEntity(Char13);
unescapedSegmentStart = i + 1;
}
}
if (unescapedSegmentStart < bound)
{
writer.WriteChars(buffer, unescapedSegmentStart, bound - unescapedSegmentStart);
}
}
public static void WriteEscapedString(XmlWriter writer, string s)
{
int unescapedSegmentStart = 0;
for (int i = 0; i < s.Length; i++)
{
if (s[i] == Char13)
{
if (unescapedSegmentStart < i)
{
writer.WriteString(s.Substring(unescapedSegmentStart, i - unescapedSegmentStart));
}
writer.WriteCharEntity(Char13);
unescapedSegmentStart = i + 1;
}
}
if (unescapedSegmentStart < s.Length)
{
writer.WriteString(s.Substring(unescapedSegmentStart, s.Length - unescapedSegmentStart));
}
}
public static void ValidateBufferBounds(Array buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException(nameof(buffer));
}
if (count < 0 || count > buffer.Length)
{
throw new ArgumentOutOfRangeException("count");
}
if (offset < 0 || offset > buffer.Length - count)
{
throw new ArgumentOutOfRangeException("offset");
}
}
public enum XmlStringType
{
AttributeValue,
CDataContent,
TextContent,
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="HtmlRawTextWriterGenerator.cxx" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
// <owner current="true" primary="true">[....]</owner>
//------------------------------------------------------------------------------
// WARNING: This file is generated and should not be modified directly. Instead,
// modify XmlTextWriterGenerator.cxx and run gen.bat in the same directory.
// This batch file will execute the following commands:
//
// cl.exe /C /EP /D _XML_UTF8_TEXT_WRITER HtmlTextWriterGenerator.cxx > HtmlUtf8TextWriter.cs
// cl.exe /C /EP /D _XML_ENCODED_TEXT_WRITER HtmlTextWriterGenerator.cxx > HtmlEncodedTextWriter.cs
//
// Because these two implementations of XmlTextWriter are so similar, the C++ preprocessor
// is used to generate each implementation from one template file, using macros and ifdefs.
using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Schema;
//using System.Xml.Query;
using System.Diagnostics;
using MS.Internal.Xml;
namespace System.Xml {
internal class HtmlEncodedRawTextWriter : XmlEncodedRawTextWriter {
//
// Fields
//
protected ByteStack elementScope;
protected ElementProperties currentElementProperties;
private AttributeProperties currentAttributeProperties;
private bool endsWithAmpersand;
private byte [] uriEscapingBuffer;
// settings
private string mediaType;
private bool doNotEscapeUriAttributes;
//
// Static fields
//
protected static TernaryTreeReadOnly elementPropertySearch;
protected static TernaryTreeReadOnly attributePropertySearch;
//
// Constants
//
private const int StackIncrement = 10;
//
// Constructors
//
public HtmlEncodedRawTextWriter( TextWriter writer, XmlWriterSettings settings ) : base( writer, settings ) {
Init( settings );
}
public HtmlEncodedRawTextWriter( Stream stream, XmlWriterSettings settings ) : base( stream, settings ) {
Init( settings );
}
//
// XmlRawWriter implementation
//
internal override void WriteXmlDeclaration( XmlStandalone standalone ) {
// Ignore xml declaration
}
internal override void WriteXmlDeclaration( string xmldecl ) {
// Ignore xml declaration
}
/// Html rules allow public ID without system ID and always output "html"
public override void WriteDocType( string name, string pubid, string sysid, string subset ) {
Debug.Assert( name != null && name.Length > 0 );
if ( trackTextContent && inTextContent != false ) { ChangeTextContentMark( false ); }
RawText( "<!DOCTYPE ");
// Bug 114337: Always output "html" or "HTML" in doc-type, even if "name" is something else
if ( name == "HTML" )
RawText( "HTML" );
else
RawText( "html" );
if ( pubid != null ) {
RawText( " PUBLIC \"" );
RawText( pubid );
if ( sysid != null ) {
RawText( "\" \"" );
RawText( sysid );
}
bufChars[bufPos++] = (char) '"';
}
else if ( sysid != null ) {
RawText( " SYSTEM \"" );
RawText( sysid );
bufChars[bufPos++] = (char) '"';
}
else {
bufChars[bufPos++] = (char) ' ';
}
if ( subset != null ) {
bufChars[bufPos++] = (char) '[';
RawText( subset );
bufChars[bufPos++] = (char) ']';
}
bufChars[this.bufPos++] = (char) '>';
}
// For the HTML element, it should call this method with ns and prefix as String.Empty
public override void WriteStartElement( string prefix, string localName, string ns ) {
Debug.Assert( localName != null && localName.Length != 0 && prefix != null && ns != null );
elementScope.Push( (byte)currentElementProperties );
if ( ns.Length == 0 ) {
Debug.Assert( prefix.Length == 0 );
if ( trackTextContent && inTextContent != false ) { ChangeTextContentMark( false ); }
currentElementProperties = (ElementProperties)elementPropertySearch.FindCaseInsensitiveString( localName );
base.bufChars[bufPos++] = (char) '<';
base.RawText( localName );
base.attrEndPos = bufPos;
}
else {
// Since the HAS_NS has no impact to the ElementTextBlock behavior,
// we don't need to push it into the stack.
currentElementProperties = ElementProperties.HAS_NS;
base.WriteStartElement( prefix, localName, ns );
}
}
// Output >. For HTML needs to output META info
internal override void StartElementContent() {
base.bufChars[base.bufPos++] = (char) '>';
// Detect whether content is output
this.contentPos = this.bufPos;
if ( ( currentElementProperties & ElementProperties.HEAD ) != 0 ) {
WriteMetaElement();
}
}
// end element with />
// for HTML(ns.Length == 0)
// not an empty tag <h1></h1>
// empty tag <basefont>
internal override void WriteEndElement( string prefix, string localName, string ns ) {
if ( ns.Length == 0 ) {
Debug.Assert( prefix.Length == 0 );
if ( trackTextContent && inTextContent != false ) { ChangeTextContentMark( false ); }
if ( ( currentElementProperties & ElementProperties.EMPTY ) == 0 ) {
bufChars[base.bufPos++] = (char) '<';
bufChars[base.bufPos++] = (char) '/';
base.RawText( localName );
bufChars[base.bufPos++] = (char) '>';
}
}
else {
//xml content
base.WriteEndElement( prefix, localName, ns );
}
currentElementProperties = (ElementProperties)elementScope.Pop();
}
internal override void WriteFullEndElement( string prefix, string localName, string ns ) {
if ( ns.Length == 0 ) {
Debug.Assert( prefix.Length == 0 );
if ( trackTextContent && inTextContent != false ) { ChangeTextContentMark( false ); }
if ( ( currentElementProperties & ElementProperties.EMPTY ) == 0 ) {
bufChars[base.bufPos++] = (char) '<';
bufChars[base.bufPos++] = (char) '/';
base.RawText( localName );
bufChars[base.bufPos++] = (char) '>';
}
}
else {
//xml content
base.WriteFullEndElement( prefix, localName, ns );
}
currentElementProperties = (ElementProperties)elementScope.Pop();
}
// 1. How the outputBooleanAttribute(fBOOL) and outputHtmlUriText(fURI) being set?
// When SA is called.
//
// BOOL_PARENT URI_PARENT Others
// fURI
// URI att false true false
//
// fBOOL
// BOOL att true false false
//
// How they change the attribute output behaviors?
//
// 1) fURI=true fURI=false
// SA a=" a="
// AT HtmlURIText HtmlText
// EA " "
//
// 2) fBOOL=true fBOOL=false
// SA a a="
// AT HtmlText output nothing
// EA output nothing "
//
// When they get reset?
// At the end of attribute.
// 2. How the outputXmlTextElementScoped(fENs) and outputXmlTextattributeScoped(fANs) are set?
// fANs is in the scope of the fENs.
//
// SE(localName) SE(ns, pre, localName) SA(localName) SA(ns, pre, localName)
// fENs false(default) true(action)
// fANs false(default) false(default) false(default) true(action)
// how they get reset?
//
// EE(localName) EE(ns, pre, localName) EENC(ns, pre, localName) EA(localName) EA(ns, pre, localName)
// fENs false(action)
// fANs false(action)
// How they change the TextOutput?
//
// fENs | fANs Else
// AT XmlText HtmlText
//
//
// 3. Flags for processing &{ split situations
//
// When the flag is set?
//
// AT src[lastchar]='&' flag&{ = true;
//
// when it get result?
//
// AT method.
//
// How it changes the behaviors?
//
// flag&{=true
//
// AT if (src[0] == '{') {
// output "&{"
// }
// else {
// output &
// }
//
// EA output amp;
//
// SA if (flagBOOL == false) { output =";}
//
// AT if (flagBOOL) { return};
// if (flagNS) {XmlText;} {
// }
// else if (flagURI) {
// HtmlURIText;
// }
// else {
// HtmlText;
// }
//
// AT if (flagNS) {XmlText;} {
// }
// else if (flagURI) {
// HtmlURIText;
// }
// else if (!flagBOOL) {
// HtmlText; //flag&{ handling
// }
//
//
// EA if (flagBOOL == false) { output "
// }
// else if (flag&{) {
// output amp;
// }
//
public override void WriteStartAttribute( string prefix, string localName, string ns ) {
Debug.Assert( localName != null && localName.Length != 0 && prefix != null && ns != null );
if ( ns.Length == 0 ) {
Debug.Assert( prefix.Length == 0 );
if ( trackTextContent && inTextContent != false ) { ChangeTextContentMark( false ); }
if ( base.attrEndPos == bufPos ) {
base.bufChars[bufPos++] = (char) ' ';
}
base.RawText( localName );
if ( ( currentElementProperties & ( ElementProperties.BOOL_PARENT | ElementProperties.URI_PARENT | ElementProperties.NAME_PARENT ) ) != 0 ) {
currentAttributeProperties = (AttributeProperties)attributePropertySearch.FindCaseInsensitiveString( localName ) &
(AttributeProperties)currentElementProperties;
if ( ( currentAttributeProperties & AttributeProperties.BOOLEAN ) != 0 ) {
base.inAttributeValue = true;
return;
}
}
else {
currentAttributeProperties = AttributeProperties.DEFAULT;
}
base.bufChars[bufPos++] = (char) '=';
base.bufChars[bufPos++] = (char) '"';
}
else {
base.WriteStartAttribute( prefix, localName, ns );
currentAttributeProperties = AttributeProperties.DEFAULT;
}
base.inAttributeValue = true;
}
// Output the amp; at end of EndAttribute
public override void WriteEndAttribute() {
if ( ( currentAttributeProperties & AttributeProperties.BOOLEAN ) != 0 ) {
base.attrEndPos = bufPos;
}
else {
if ( endsWithAmpersand ) {
OutputRestAmps();
endsWithAmpersand = false;
}
if ( trackTextContent && inTextContent != false ) { ChangeTextContentMark( false ); }
base.bufChars[bufPos++] = (char) '"';
}
base.inAttributeValue = false;
base.attrEndPos = bufPos;
}
// HTML PI's use ">" to terminate rather than "?>".
public override void WriteProcessingInstruction( string target, string text ) {
Debug.Assert( target != null && target.Length != 0 && text != null );
if ( trackTextContent && inTextContent != false ) { ChangeTextContentMark( false ); }
bufChars[base.bufPos++] = (char) '<';
bufChars[base.bufPos++] = (char) '?';
base.RawText( target );
bufChars[base.bufPos++] = (char) ' ';
base.WriteCommentOrPi( text, '?' );
base.bufChars[base.bufPos++] = (char) '>';
if ( base.bufPos > base.bufLen ) {
FlushBuffer();
}
}
// Serialize either attribute or element text using HTML rules.
public override unsafe void WriteString( string text ) {
Debug.Assert( text != null );
if ( trackTextContent && inTextContent != true ) { ChangeTextContentMark( true ); }
fixed ( char * pSrc = text ) {
char * pSrcEnd = pSrc + text.Length;
if ( base.inAttributeValue) {
WriteHtmlAttributeTextBlock( pSrc, pSrcEnd );
}
else {
WriteHtmlElementTextBlock( pSrc, pSrcEnd );
}
}
}
public override void WriteEntityRef( string name ) {
throw new InvalidOperationException( Res.GetString( Res.Xml_InvalidOperation ) );
}
public override void WriteCharEntity( char ch ) {
throw new InvalidOperationException( Res.GetString( Res.Xml_InvalidOperation ) );
}
public override void WriteSurrogateCharEntity( char lowChar, char highChar ) {
throw new InvalidOperationException( Res.GetString( Res.Xml_InvalidOperation ) );
}
public override unsafe void WriteChars( char[] buffer, int index, int count ) {
Debug.Assert( buffer != null );
Debug.Assert( index >= 0 );
Debug.Assert( count >= 0 && index + count <= buffer.Length );
if ( trackTextContent && inTextContent != true ) { ChangeTextContentMark( true ); }
fixed ( char * pSrcBegin = &buffer[index] ) {
if ( inAttributeValue ) {
WriteAttributeTextBlock( pSrcBegin, pSrcBegin + count );
}
else {
WriteElementTextBlock( pSrcBegin, pSrcBegin + count );
}
}
}
//
// Private methods
//
private void Init( XmlWriterSettings settings ) {
Debug.Assert( (int)ElementProperties.URI_PARENT == (int)AttributeProperties.URI );
Debug.Assert( (int)ElementProperties.BOOL_PARENT == (int)AttributeProperties.BOOLEAN );
Debug.Assert( (int)ElementProperties.NAME_PARENT == (int)AttributeProperties.NAME );
if ( elementPropertySearch == null ) {
//elementPropertySearch should be init last for the mutli thread safe situation.
attributePropertySearch = new TernaryTreeReadOnly(HtmlTernaryTree.htmlAttributes );
elementPropertySearch = new TernaryTreeReadOnly( HtmlTernaryTree.htmlElements );
}
elementScope = new ByteStack( StackIncrement );
uriEscapingBuffer = new byte[5];
currentElementProperties = ElementProperties.DEFAULT;
mediaType = settings.MediaType;
doNotEscapeUriAttributes = settings.DoNotEscapeUriAttributes;
}
protected void WriteMetaElement() {
base.RawText("<META http-equiv=\"Content-Type\"");
if ( mediaType == null ) {
mediaType = "text/html";
}
base.RawText( " content=\"" );
base.RawText( mediaType );
base.RawText( "; charset=" );
base.RawText( base.encoding.WebName );
base.RawText( "\">" );
}
// Justify the stack usage:
//
// Nested elements has following possible position combinations
// 1. <E1>Content1<E2>Content2</E2></E1>
// 2. <E1><E2>Content2</E2>Content1</E1>
// 3. <E1>Content<E2>Cotent2</E2>Content1</E1>
//
// In the situation 2 and 3, the stored currentElementProrperties will be E2's,
// only the top of the stack is the real E1 element properties.
protected unsafe void WriteHtmlElementTextBlock( char * pSrc, char * pSrcEnd ) {
if ( ( currentElementProperties & ElementProperties.NO_ENTITIES ) != 0 ) {
base.RawText( pSrc, pSrcEnd );
} else {
base.WriteElementTextBlock( pSrc, pSrcEnd );
}
}
protected unsafe void WriteHtmlAttributeTextBlock( char * pSrc, char * pSrcEnd ) {
if ( ( currentAttributeProperties & ( AttributeProperties.BOOLEAN | AttributeProperties.URI | AttributeProperties.NAME ) ) != 0 ) {
if ( ( currentAttributeProperties & AttributeProperties.BOOLEAN ) != 0 ) {
//if output boolean attribute, ignore this call.
return;
}
if ( ( currentAttributeProperties & ( AttributeProperties.URI | AttributeProperties.NAME ) ) != 0 && !doNotEscapeUriAttributes ) {
WriteUriAttributeText( pSrc, pSrcEnd );
}
else {
WriteHtmlAttributeText( pSrc, pSrcEnd );
}
}
else if ( ( currentElementProperties & ElementProperties.HAS_NS ) != 0 ) {
base.WriteAttributeTextBlock( pSrc, pSrcEnd );
}
else {
WriteHtmlAttributeText( pSrc, pSrcEnd );
}
}
//
// &{ split cases
// 1). HtmlAttributeText("a&");
// HtmlAttributeText("{b}");
//
// 2). HtmlAttributeText("a&");
// EndAttribute();
// 3).split with Flush by the user
// HtmlAttributeText("a&");
// FlushBuffer();
// HtmlAttributeText("{b}");
//
// Solutions:
// case 1)hold the & output as &
// if the next income character is {, output {
// else output amp;
//
private unsafe void WriteHtmlAttributeText( char * pSrc, char *pSrcEnd ) {
if ( endsWithAmpersand ) {
if ( pSrcEnd - pSrc > 0 && pSrc[0] != '{' ) {
OutputRestAmps();
}
endsWithAmpersand = false;
}
fixed ( char * pDstBegin = bufChars ) {
char * pDst = pDstBegin + this.bufPos;
char ch = (char)0;
for (;;) {
char * pDstEnd = pDst + ( pSrcEnd - pSrc );
if ( pDstEnd > pDstBegin + bufLen ) {
pDstEnd = pDstBegin + bufLen;
}
while ( pDst < pDstEnd && ( ( ( xmlCharType.charProperties[( ch = *pSrc )] & XmlCharType.fAttrValue ) != 0 ) ) ) {
*pDst++ = (char)ch;
pSrc++;
}
Debug.Assert( pSrc <= pSrcEnd );
// end of value
if ( pSrc >= pSrcEnd ) {
break;
}
// end of buffer
if ( pDst >= pDstEnd ) {
bufPos = (int)(pDst - pDstBegin);
FlushBuffer();
pDst = pDstBegin + 1;
continue;
}
// some character needs to be escaped
switch ( ch ) {
case '&':
if ( pSrc + 1 == pSrcEnd ) {
endsWithAmpersand = true;
}
else if ( pSrc[1] != '{' ) {
pDst = XmlEncodedRawTextWriter.AmpEntity(pDst);
break;
}
*pDst++ = (char)ch;
break;
case '"':
pDst = QuoteEntity( pDst );
break;
case '<':
case '>':
case '\'':
case (char)0x9:
*pDst++ = (char)ch;
break;
case (char)0xD:
// do not normalize new lines in attributes - just escape them
pDst = CarriageReturnEntity( pDst );
break;
case (char)0xA:
// do not normalize new lines in attributes - just escape them
pDst = LineFeedEntity( pDst );
break;
default:
EncodeChar( ref pSrc, pSrcEnd, ref pDst);
continue;
}
pSrc++;
}
bufPos = (int)(pDst - pDstBegin);
}
}
private unsafe void WriteUriAttributeText( char * pSrc, char * pSrcEnd ) {
if ( endsWithAmpersand ) {
if ( pSrcEnd - pSrc > 0 && pSrc[0] != '{' ) {
OutputRestAmps();
}
this.endsWithAmpersand = false;
}
fixed ( char * pDstBegin = bufChars ) {
char * pDst = pDstBegin + this.bufPos;
char ch = (char)0;
for (;;) {
char * pDstEnd = pDst + ( pSrcEnd - pSrc );
if ( pDstEnd > pDstBegin + bufLen ) {
pDstEnd = pDstBegin + bufLen;
}
while ( pDst < pDstEnd && ( ( ( xmlCharType.charProperties[( ch = *pSrc )] & XmlCharType.fAttrValue ) != 0 ) && ch < 0x80 ) ) {
*pDst++ = (char)ch;
pSrc++;
}
Debug.Assert( pSrc <= pSrcEnd );
// end of value
if ( pSrc >= pSrcEnd ) {
break;
}
// end of buffer
if ( pDst >= pDstEnd ) {
bufPos = (int)(pDst - pDstBegin);
FlushBuffer();
pDst = pDstBegin + 1;
continue;
}
// some character needs to be escaped
switch ( ch ) {
case '&':
if ( pSrc + 1 == pSrcEnd ) {
endsWithAmpersand = true;
}
else if ( pSrc[1] != '{' ) {
pDst = XmlEncodedRawTextWriter.AmpEntity(pDst);
break;
}
*pDst++ = (char)ch;
break;
case '"':
pDst = QuoteEntity( pDst );
break;
case '<':
case '>':
case '\'':
case (char)0x9:
*pDst++ = (char)ch;
break;
case (char)0xD:
// do not normalize new lines in attributes - just escape them
pDst = CarriageReturnEntity( pDst );
break;
case (char)0xA:
// do not normalize new lines in attributes - just escape them
pDst = LineFeedEntity( pDst );
break;
default:
const string hexDigits = "0123456789ABCDEF";
fixed ( byte * pUriEscapingBuffer = uriEscapingBuffer ) {
byte * pByte = pUriEscapingBuffer;
byte * pEnd = pByte;
XmlUtf8RawTextWriter.CharToUTF8( ref pSrc, pSrcEnd, ref pEnd );
while ( pByte < pEnd ) {
*pDst++ = (char) '%';
*pDst++ = (char) hexDigits[*pByte >> 4];
*pDst++ = (char) hexDigits[*pByte & 0xF];
pByte++;
}
}
continue;
}
pSrc++;
}
bufPos = (int)(pDst - pDstBegin);
}
}
// For handling &{ in Html text field. If & is not followed by {, it still needs to be escaped.
private void OutputRestAmps() {
base.bufChars[bufPos++] = (char)'a';
base.bufChars[bufPos++] = (char)'m';
base.bufChars[bufPos++] = (char)'p';
base.bufChars[bufPos++] = (char)';';
}
}
//
// Indentation HtmlWriter only indent <BLOCK><BLOCK> situations
//
// Here are all the cases:
// ELEMENT1 actions ELEMENT2 actions SC EE
// 1). SE SC store SE blockPro SE a). check ELEMENT1 blockPro <A> </A>
// EE if SE, EE are blocks b). true: check ELEMENT2 blockPro <B> <B>
// c). detect ELEMENT is SE, SC
// d). increase the indexlevel
//
// 2). SE SC, Store EE blockPro EE a). check stored blockPro <A></A> </A>
// EE if SE, EE are blocks b). true: indexLevel same </B>
//
//
// This is an alternative way to make the output looks better
//
// Indentation HtmlWriter only indent <BLOCK><BLOCK> situations
//
// Here are all the cases:
// ELEMENT1 actions ELEMENT2 actions Samples
// 1). SE SC store SE blockPro SE a). check ELEMENT1 blockPro <A>(blockPos)
// b). true: check ELEMENT2 blockPro <B>
// c). detect ELEMENT is SE, SC
// d). increase the indentLevel
//
// 2). EE Store EE blockPro SE a). check stored blockPro </A>
// b). true: indentLevel same <B>
// c). output block2
//
// 3). EE same as above EE a). check stored blockPro </A>
// b). true: --indentLevel </B>
// c). output block2
//
// 4). SE SC same as above EE a). check stored blockPro <A></A>
// b). true: indentLevel no change
internal class HtmlEncodedRawTextWriterIndent : HtmlEncodedRawTextWriter {
//
// Fields
//
int indentLevel;
// for detecting SE SC sitution
int endBlockPos;
// settings
string indentChars;
bool newLineOnAttributes;
//
// Constructors
//
public HtmlEncodedRawTextWriterIndent( TextWriter writer, XmlWriterSettings settings ) : base( writer, settings ) {
Init( settings );
}
public HtmlEncodedRawTextWriterIndent( Stream stream, XmlWriterSettings settings ) : base( stream, settings ) {
Init( settings );
}
//
// XmlRawWriter overrides
//
/// <summary>
/// Serialize the document type declaration.
/// </summary>
public override void WriteDocType( string name, string pubid, string sysid, string subset ) {
base.WriteDocType( name, pubid, sysid, subset );
// Allow indentation after DocTypeDecl
endBlockPos = base.bufPos;
}
public override void WriteStartElement(string prefix, string localName, string ns ) {
Debug.Assert( localName != null && localName.Length != 0 && prefix != null && ns != null );
if ( trackTextContent && inTextContent != false ) { ChangeTextContentMark( false ); }
base.elementScope.Push( (byte)base.currentElementProperties );
if ( ns.Length == 0 ) {
Debug.Assert( prefix.Length == 0 );
base.currentElementProperties = (ElementProperties)elementPropertySearch.FindCaseInsensitiveString( localName );
if ( endBlockPos == base.bufPos && ( base.currentElementProperties & ElementProperties.BLOCK_WS ) != 0 ) {
WriteIndent();
}
indentLevel++;
base.bufChars[bufPos++] = (char) '<';
}
else {
base.currentElementProperties = ElementProperties.HAS_NS | ElementProperties.BLOCK_WS;
if ( endBlockPos == base.bufPos ) {
WriteIndent();
}
indentLevel++;
base.bufChars[base.bufPos++] = (char) '<';
if ( prefix.Length != 0 ) {
base.RawText( prefix );
base.bufChars[base.bufPos++] = (char) ':';
}
}
base.RawText( localName );
base.attrEndPos = bufPos;
}
internal override void StartElementContent() {
base.bufChars[base.bufPos++] = (char) '>';
// Detect whether content is output
base.contentPos = base.bufPos;
if ( ( currentElementProperties & ElementProperties.HEAD ) != 0) {
WriteIndent();
WriteMetaElement();
endBlockPos = base.bufPos;
}
else if ( ( base.currentElementProperties & ElementProperties.BLOCK_WS ) != 0 ) {
// store the element block position
endBlockPos = base.bufPos;
}
}
internal override void WriteEndElement( string prefix, string localName, string ns ) {
bool isBlockWs;
Debug.Assert( localName != null && localName.Length != 0 && prefix != null && ns != null );
indentLevel--;
// If this element has block whitespace properties,
isBlockWs = ( base.currentElementProperties & ElementProperties.BLOCK_WS ) != 0;
if ( isBlockWs ) {
// And if the last node to be output had block whitespace properties,
// And if content was output within this element,
if ( endBlockPos == base.bufPos && base.contentPos != base.bufPos ) {
// Then indent
WriteIndent();
}
}
base.WriteEndElement(prefix, localName, ns);
// Reset contentPos in case of empty elements
base.contentPos = 0;
// Mark end of element in buffer for element's with block whitespace properties
if ( isBlockWs ) {
endBlockPos = base.bufPos;
}
}
public override void WriteStartAttribute( string prefix, string localName, string ns ) {
if ( newLineOnAttributes ) {
RawText( base.newLineChars );
indentLevel++;
WriteIndent();
indentLevel--;
}
base.WriteStartAttribute( prefix, localName, ns );
}
protected override void FlushBuffer() {
// Make sure the buffer will reset the block position
endBlockPos = ( endBlockPos == base.bufPos ) ? 1 : 0;
base.FlushBuffer();
}
//
// Private methods
//
private void Init( XmlWriterSettings settings ) {
indentLevel = 0;
indentChars = settings.IndentChars;
newLineOnAttributes = settings.NewLineOnAttributes;
}
private void WriteIndent() {
// <block><inline> -- suppress ws betw <block> and <inline>
// <block><block> -- don't suppress ws betw <block> and <block>
// <block>text -- suppress ws betw <block> and text (handled by wcharText method)
// <block><?PI?> -- suppress ws betw <block> and PI
// <block><!-- --> -- suppress ws betw <block> and comment
// <inline><block> -- suppress ws betw <inline> and <block>
// <inline><inline> -- suppress ws betw <inline> and <inline>
// <inline>text -- suppress ws betw <inline> and text (handled by wcharText method)
// <inline><?PI?> -- suppress ws betw <inline> and PI
// <inline><!-- --> -- suppress ws betw <inline> and comment
RawText( base.newLineChars );
for ( int i = indentLevel; i > 0; i-- ) {
RawText( indentChars );
}
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
using Baseline;
using Marten.Exceptions;
using Marten.Internal;
using Marten.Linq.Fields;
using Marten.Linq.Filters;
using Marten.Linq.SqlGeneration;
using Remotion.Linq.Clauses;
using Remotion.Linq.Clauses.Expressions;
using Remotion.Linq.Clauses.ResultOperators;
using Remotion.Linq.Parsing;
using Weasel.Postgresql.SqlGeneration;
namespace Marten.Linq.Parsing
{
internal partial class WhereClauseParser : RelinqExpressionVisitor, IWhereFragmentHolder
{
private static readonly IDictionary<ExpressionType, string> _operators = new Dictionary<ExpressionType, string>
{
{ExpressionType.Equal, "="},
{ExpressionType.NotEqual, "!="},
{ExpressionType.GreaterThan, ">"},
{ExpressionType.GreaterThanOrEqual, ">="},
{ExpressionType.LessThan, "<"},
{ExpressionType.LessThanOrEqual, "<="}
};
private readonly IMartenSession _session;
private readonly Statement _statement;
private IWhereFragmentHolder _holder;
public WhereClauseParser(IMartenSession session, Statement statement)
{
_session = session;
_statement = statement;
_holder = this;
}
public ISqlFragment Build(WhereClause clause)
{
_holder = this;
Where = null;
Visit(clause.Predicate);
if (Where == null)
{
throw new BadLinqExpressionException($"Unsupported Where clause: '{clause.Predicate}'");
}
return Where;
}
public ISqlFragment Where { get; private set; }
public bool InSubQuery { get; set; }
void IWhereFragmentHolder.Register(ISqlFragment fragment)
{
Where = fragment;
}
protected override Expression VisitSubQuery(SubQueryExpression expression)
{
var parser = new SubQueryFilterParser(this, expression);
var where = parser.BuildWhereFragment();
_holder.Register(where);
return null;
}
protected override Expression VisitMethodCall(MethodCallExpression node)
{
var where = _session.Options.Linq.BuildWhereFragment(_statement.Fields, node, _session.Serializer);
_holder.Register(where);
return null;
}
protected override Expression VisitBinary(BinaryExpression node)
{
if (_operators.TryGetValue(node.NodeType, out var op))
{
var binary = new BinaryExpressionVisitor(this);
_holder.Register(binary.BuildWhereFragment(node, op));
return null;
}
switch (node.NodeType)
{
case ExpressionType.AndAlso:
buildCompoundWhereFragment(node, "and");
break;
case ExpressionType.OrElse:
buildCompoundWhereFragment(node, "or");
break;
default:
throw new BadLinqExpressionException($"Unsupported expression type '{node.NodeType}' in binary expression");
}
return null;
}
private void buildCompoundWhereFragment(BinaryExpression node, string separator)
{
var original = _holder;
var compound = CompoundWhereFragment.For(separator);
_holder.Register(compound);
_holder = compound;
Visit(node.Left);
_holder = compound;
Visit(node.Right);
_holder = original;
}
protected override Expression VisitUnary(UnaryExpression node)
{
if (node.NodeType == ExpressionType.Not)
{
var original = _holder;
if (original is IReversibleWhereFragment r)
{
_holder.Register(r.Reverse());
return Visit(node.Operand);
}
else
{
_holder = new NotWhereFragment(original);
var returnValue = Visit(node.Operand);
_holder = original;
return returnValue;
}
}
return base.VisitUnary(node);
}
protected override Expression VisitMember(MemberExpression node)
{
if (node.Type == typeof(bool))
{
var field = _statement.Fields.FieldFor(node);
_holder.Register(new BooleanFieldIsTrue(field));
return null;
}
return base.VisitMember(node);
}
protected override Expression VisitConstant(ConstantExpression node)
{
if ((node.Type == typeof(bool)))
{
if (InSubQuery)
{
throw new BadLinqExpressionException("Unsupported Where() clause in a sub-collection expression");
}
_holder.Register(new WhereFragment(node.Value.ToString().ToLower()));
}
return base.VisitConstant(node);
}
internal enum SubQueryUsage
{
Any,
Count,
Contains,
Intersect
}
internal class SubQueryFilterParser : RelinqExpressionVisitor
{
private readonly WhereClauseParser _parent;
private readonly SubQueryExpression _expression;
#pragma warning disable 414
private bool _isDistinct;
#pragma warning restore 414
private readonly WhereClause[] _wheres;
private readonly Expression _contains;
public SubQueryFilterParser(WhereClauseParser parent, SubQueryExpression expression)
{
_parent = parent;
_expression = expression;
foreach (var @operator in expression.QueryModel.ResultOperators)
{
switch (@operator)
{
case AnyResultOperator _:
Usage = SubQueryUsage.Any;
break;
case CountResultOperator _:
Usage = SubQueryUsage.Count;
break;
case LongCountResultOperator _:
Usage = SubQueryUsage.Count;
break;
case DistinctResultOperator _:
_isDistinct = true;
break;
case ContainsResultOperator op:
Usage = op.Item is QuerySourceReferenceExpression
? SubQueryUsage.Intersect
: SubQueryUsage.Contains;
_contains = op.Item;
break;
default:
throw new BadLinqExpressionException($"Invalid result operator {@operator} in sub query '{expression}'");
}
}
_wheres = expression.QueryModel.BodyClauses.OfType<WhereClause>().ToArray();
}
public SubQueryUsage Usage { get; }
public ISqlFragment BuildWhereFragment()
{
switch (Usage)
{
case SubQueryUsage.Any:
return buildWhereForAny(findArrayField());
case SubQueryUsage.Contains:
return buildWhereForContains(findArrayField());
case SubQueryUsage.Intersect:
return new WhereInArrayFilter("data", (ConstantExpression)_expression.QueryModel.MainFromClause.FromExpression);
default:
throw new NotSupportedException();
}
}
private ArrayField findArrayField()
{
ArrayField field;
try
{
field = (ArrayField) _parent._statement.Fields.FieldFor(_expression.QueryModel.MainFromClause.FromExpression);
}
catch (Exception e)
{
throw new BadLinqExpressionException("The sub query is not sourced from a supported collection type", e);
}
return field;
}
private ISqlFragment buildWhereForContains(ArrayField field)
{
if (_contains is ConstantExpression c)
{
var flattened = new FlattenerStatement(field, _parent._session, _parent._statement);
var idSelectorStatement = new ContainsIdSelectorStatement(flattened, _parent._session, c);
return new WhereCtIdInSubQuery(idSelectorStatement.ExportName, flattened);
}
throw new NotSupportedException();
}
private ISqlFragment buildWhereForAny(ArrayField field)
{
if (_wheres.Any())
{
var flattened = new FlattenerStatement(field, _parent._session, _parent._statement);
var itemType = _expression.QueryModel.MainFromClause.ItemType;
var elementFields =
_parent._session.Options.ChildTypeMappingFor(itemType);
var idSelectorStatement = new IdSelectorStatement(_parent._session, elementFields, flattened);
idSelectorStatement.WhereClauses.AddRange(_wheres);
idSelectorStatement.CompileLocal(_parent._session);
return new WhereCtIdInSubQuery(idSelectorStatement.ExportName, flattened);
}
return new CollectionIsNotEmpty(field);
}
public CountComparisonStatement BuildCountComparisonStatement()
{
if (Usage != SubQueryUsage.Count)
{
throw new BadLinqExpressionException("Invalid comparison");
}
var field = findArrayField();
var flattened = new FlattenerStatement(field, _parent._session, _parent._statement);
var elementFields =
_parent._session.Options.ChildTypeMappingFor(field.ElementType);
var statement = new CountComparisonStatement(_parent._session, field.ElementType, elementFields, flattened);
if (_wheres.Any())
{
statement.WhereClauses.AddRange(_wheres);
statement.CompileLocal(_parent._session);
}
return statement;
}
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace tk2dRuntime
{
static class SpriteCollectionGenerator
{
public static tk2dSpriteCollectionData CreateFromTexture(Texture texture, tk2dSpriteCollectionSize size, Rect region, Vector2 anchor)
{
return CreateFromTexture(texture, size, new string[] { "Unnamed" }, new Rect[] { region }, new Vector2[] { anchor } );
}
public static tk2dSpriteCollectionData CreateFromTexture(Texture texture, tk2dSpriteCollectionSize size, string[] names, Rect[] regions, Vector2[] anchors) {
Vector2 textureDimensions = new Vector2( texture.width, texture.height );
return CreateFromTexture( texture, size, textureDimensions, names, regions, null, anchors, null );
}
public static tk2dSpriteCollectionData CreateFromTexture(
Texture texture,
tk2dSpriteCollectionSize size,
Vector2 textureDimensions,
string[] names,
Rect[] regions,
Rect[] trimRects, Vector2[] anchors,
bool[] rotated)
{
return CreateFromTexture(null, texture, size, textureDimensions, names, regions, trimRects, anchors, rotated);
}
public static tk2dSpriteCollectionData CreateFromTexture(
GameObject parentObject,
Texture texture,
tk2dSpriteCollectionSize size,
Vector2 textureDimensions,
string[] names,
Rect[] regions,
Rect[] trimRects, Vector2[] anchors,
bool[] rotated)
{
GameObject go = ( parentObject != null ) ? parentObject : new GameObject("SpriteCollection");
tk2dSpriteCollectionData sc = go.AddComponent<tk2dSpriteCollectionData>();
sc.Transient = true;
sc.version = tk2dSpriteCollectionData.CURRENT_VERSION;
sc.invOrthoSize = 1.0f / size.OrthoSize;
sc.halfTargetHeight = size.TargetHeight * 0.5f;
sc.premultipliedAlpha = false;
string shaderName = "tk2d/BlendVertexColor";
#if UNITY_EDITOR
{
Shader ts = Shader.Find(shaderName);
string assetPath = UnityEditor.AssetDatabase.GetAssetPath(ts);
if (assetPath.ToLower().IndexOf("/resources/") == -1) {
UnityEditor.EditorUtility.DisplayDialog("tk2dRuntimeSpriteCollection Error",
"The tk2d/BlendVertexColor shader needs to be in a resources folder for this to work.\n\n" +
"Create a subdirectory named 'resources' where the shaders are, and move the BlendVertexColor shader into this directory.\n\n"+
"eg. TK2DROOT/tk2d/Shaders/Resources/BlendVertexColor\n\n" +
"Be sure to do this from within Unity and not from Explorer/Finder.",
"Ok");
return null;
}
}
#endif
sc.material = new Material(Shader.Find(shaderName));
sc.material.mainTexture = texture;
sc.materials = new Material[1] { sc.material };
sc.textures = new Texture[1] { texture };
sc.buildKey = UnityEngine.Random.Range(0, Int32.MaxValue);
float scale = 2.0f * size.OrthoSize / size.TargetHeight;
Rect trimRect = new Rect(0, 0, 0, 0);
// Generate geometry
sc.spriteDefinitions = new tk2dSpriteDefinition[regions.Length];
for (int i = 0; i < regions.Length; ++i) {
bool defRotated = (rotated != null) ? rotated[i] : false;
if (trimRects != null) {
trimRect = trimRects[i];
}
else {
if (defRotated) trimRect.Set( 0, 0, regions[i].height, regions[i].width );
else trimRect.Set( 0, 0, regions[i].width, regions[i].height );
}
sc.spriteDefinitions[i] = CreateDefinitionForRegionInTexture(names[i], textureDimensions, scale, regions[i], trimRect, anchors[i], defRotated);
}
foreach (var def in sc.spriteDefinitions) {
def.material = sc.material;
}
return sc;
}
static tk2dSpriteDefinition CreateDefinitionForRegionInTexture(string name, Vector2 textureDimensions, float scale, Rect uvRegion, Rect trimRect, Vector2 anchor, bool rotated)
{
float h = uvRegion.height;
float w = uvRegion.width;
float fwidth = textureDimensions.x;
float fheight = textureDimensions.y;
var def = new tk2dSpriteDefinition();
def.flipped = rotated ? tk2dSpriteDefinition.FlipMode.TPackerCW : tk2dSpriteDefinition.FlipMode.None;
def.extractRegion = false;
def.name = name;
def.colliderType = tk2dSpriteDefinition.ColliderType.Unset;
Vector2 uvOffset = new Vector2(0.001f, 0.001f);
Vector2 v0 = new Vector2((uvRegion.x + uvOffset.x) / fwidth, 1.0f - (uvRegion.y + uvRegion.height + uvOffset.y) / fheight);
Vector2 v1 = new Vector2((uvRegion.x + uvRegion.width - uvOffset.x) / fwidth, 1.0f - (uvRegion.y - uvOffset.y) / fheight);
// Correction offset to make the sprite correctly centered at 0, 0
Vector2 offset = new Vector2( trimRect.x - anchor.x, -trimRect.y + anchor.y );
if (rotated) {
offset.y -= w;
}
offset *= scale;
Vector3 b0 = new Vector3( -anchor.x * scale, anchor.y * scale, 0 );
Vector3 b1 = b0 + new Vector3( trimRect.width * scale, -trimRect.height * scale, 0 );
Vector3 pos0 = new Vector3(0, -h * scale, 0.0f);
Vector3 pos1 = pos0 + new Vector3(w * scale, h * scale, 0.0f);
if (rotated) {
def.positions = new Vector3[] {
new Vector3(-pos1.y + offset.x, pos0.x + offset.y, 0),
new Vector3(-pos0.y + offset.x, pos0.x + offset.y, 0),
new Vector3(-pos1.y + offset.x, pos1.x + offset.y, 0),
new Vector3(-pos0.y + offset.x, pos1.x + offset.y, 0),
};
def.uvs = new Vector2[] {
new Vector2(v0.x,v1.y),
new Vector2(v0.x,v0.y),
new Vector2(v1.x,v1.y),
new Vector2(v1.x,v0.y),
};
}
else
{
def.positions = new Vector3[] {
new Vector3(pos0.x + offset.x, pos0.y + offset.y, 0),
new Vector3(pos1.x + offset.x, pos0.y + offset.y, 0),
new Vector3(pos0.x + offset.x, pos1.y + offset.y, 0),
new Vector3(pos1.x + offset.x, pos1.y + offset.y, 0)
};
def.uvs = new Vector2[] {
new Vector2(v0.x,v0.y),
new Vector2(v1.x,v0.y),
new Vector2(v0.x,v1.y),
new Vector2(v1.x,v1.y)
};
}
def.normals = new Vector3[0];
def.tangents = new Vector4[0];
def.indices = new int[] {
0, 3, 1, 2, 3, 0
};
Vector3 boundsMin = new Vector3(b0.x, b1.y, 0);
Vector3 boundsMax = new Vector3(b1.x, b0.y, 0);
// todo - calc trimmed bounds properly
def.boundsData = new Vector3[2] {
(boundsMax + boundsMin) / 2.0f,
(boundsMax - boundsMin)
};
def.untrimmedBoundsData = new Vector3[2] {
(boundsMax + boundsMin) / 2.0f,
(boundsMax - boundsMin)
};
def.texelSize = new Vector2(scale, scale);
return def;
}
// Texture packer import
public static tk2dSpriteCollectionData CreateFromTexturePacker( tk2dSpriteCollectionSize spriteCollectionSize, string texturePackerFileContents, Texture texture ) {
List<string> names = new List<string>();
List<Rect> rects = new List<Rect>();
List<Rect> trimRects = new List<Rect>();
List<Vector2> anchors = new List<Vector2>();
List<bool> rotated = new List<bool>();
int state = 0;
System.IO.TextReader tr = new System.IO.StringReader(texturePackerFileContents);
// tmp state
bool entryRotated = false;
bool entryTrimmed = false;
string entryName = "";
Rect entryRect = new Rect();
Rect entryTrimData = new Rect();
Vector2 textureDimensions = Vector2.zero;
Vector2 anchor = Vector2.zero;
// gonna write a non-allocating parser for this one day.
// all these substrings & splits can't be good
// but should be a tiny bit better than an xml / json parser...
string line = tr.ReadLine();
while (line != null) {
if (line.Length > 0) {
char cmd = line[0];
switch (state) {
case 0: {
switch (cmd) {
case 'i': break; // ignore version field for now
case 'w': textureDimensions.x = Int32.Parse(line.Substring(2)); break;
case 'h': textureDimensions.y = Int32.Parse(line.Substring(2)); break;
// total number of sprites would be ideal to statically allocate
case '~': state++; break;
}
}
break;
case 1: {
switch (cmd) {
case 'n': entryName = line.Substring(2); break;
case 'r': entryRotated = Int32.Parse(line.Substring(2)) == 1; break;
case 's': { // sprite
string[] tokens = line.Split();
entryRect.Set( Int32.Parse(tokens[1]), Int32.Parse(tokens[2]), Int32.Parse(tokens[3]), Int32.Parse(tokens[4]) );
}
break;
case 'o': { // origin
string[] tokens = line.Split();
entryTrimData.Set( Int32.Parse(tokens[1]), Int32.Parse(tokens[2]), Int32.Parse(tokens[3]), Int32.Parse(tokens[4]) );
entryTrimmed = true;
}
break;
case '~': {
names.Add(entryName);
rotated.Add(entryRotated);
rects.Add(entryRect);
if (!entryTrimmed) {
// The entryRect dimensions will be the wrong way around if the sprite is rotated
if (entryRotated) entryTrimData.Set(0, 0, entryRect.height, entryRect.width);
else entryTrimData.Set(0, 0, entryRect.width, entryRect.height);
}
trimRects.Add(entryTrimData);
anchor.Set( (int)(entryTrimData.width / 2), (int)(entryTrimData.height / 2) );
anchors.Add( anchor );
entryName = "";
entryTrimmed = false;
entryRotated = false;
}
break;
}
}
break;
}
}
line = tr.ReadLine();
}
return CreateFromTexture(
texture,
spriteCollectionSize,
textureDimensions,
names.ToArray(),
rects.ToArray(),
trimRects.ToArray(),
anchors.ToArray(),
rotated.ToArray() );
}
}
}
| |
namespace BrickBreakerLevelEditor
{
partial class EditorForm
{
/// <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(EditorForm));
System.Windows.Forms.TreeNode treeNode1 = new System.Windows.Forms.TreeNode("Level01", 2, 2);
System.Windows.Forms.TreeNode treeNode2 = new System.Windows.Forms.TreeNode("Level02", 2, 2);
System.Windows.Forms.TreeNode treeNode3 = new System.Windows.Forms.TreeNode("Group01", 1, 1, new System.Windows.Forms.TreeNode[] {
treeNode1,
treeNode2});
System.Windows.Forms.TreeNode treeNode4 = new System.Windows.Forms.TreeNode("Project [Example01]", new System.Windows.Forms.TreeNode[] {
treeNode3});
Chapter24.LevelData levelData1 = new Chapter24.LevelData();
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolNew = new System.Windows.Forms.ToolStripButton();
this.toolOpen = new System.Windows.Forms.ToolStripButton();
this.toolSave = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator2 = new System.Windows.Forms.ToolStripSeparator();
this.cmdDrawGrid = new System.Windows.Forms.ToolStripButton();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.toolHitsToClear = new System.Windows.Forms.ToolStripDropDownButton();
this.toolStripMenuItem2 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem3 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem4 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem5 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem6 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem7 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem8 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem9 = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripMenuItem10 = new System.Windows.Forms.ToolStripMenuItem();
this.splitContainer1 = new System.Windows.Forms.SplitContainer();
this.treeView1 = new System.Windows.Forms.TreeView();
this.imageList1 = new System.Windows.Forms.ImageList(this.components);
this.toolStrip2 = new System.Windows.Forms.ToolStrip();
this.toolAddNewLevel = new System.Windows.Forms.ToolStripButton();
this.toolCopyLevel = new System.Windows.Forms.ToolStripButton();
this.toolMoveLevelUp = new System.Windows.Forms.ToolStripButton();
this.toolMoveLevelDown = new System.Windows.Forms.ToolStripButton();
this.toolDeleteLevel = new System.Windows.Forms.ToolStripButton();
this.menuStrip1 = new System.Windows.Forms.MenuStrip();
this.mnuFile = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileNew = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileOpen = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileClose = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileSave = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileSaveAs = new System.Windows.Forms.ToolStripMenuItem();
this.mnuFileExit = new System.Windows.Forms.ToolStripMenuItem();
this.openFileDialog1 = new System.Windows.Forms.OpenFileDialog();
this.saveFileDialog1 = new System.Windows.Forms.SaveFileDialog();
this.brickBreakerEditorControl1 = new BrickBreakerLevelEditor.EditorControl();
this.toolStrip1.SuspendLayout();
this.splitContainer1.Panel1.SuspendLayout();
this.splitContainer1.Panel2.SuspendLayout();
this.splitContainer1.SuspendLayout();
this.toolStrip2.SuspendLayout();
this.menuStrip1.SuspendLayout();
this.SuspendLayout();
//
// toolStrip1
//
this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolNew,
this.toolOpen,
this.toolSave,
this.toolStripSeparator2,
this.cmdDrawGrid,
this.toolStripSeparator1,
this.toolHitsToClear});
this.toolStrip1.Location = new System.Drawing.Point(0, 24);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(594, 25);
this.toolStrip1.TabIndex = 0;
this.toolStrip1.Text = "toolStrip1";
//
// toolNew
//
this.toolNew.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolNew.Image = ((System.Drawing.Image)(resources.GetObject("toolNew.Image")));
this.toolNew.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolNew.Name = "toolNew";
this.toolNew.Size = new System.Drawing.Size(23, 22);
this.toolNew.Text = "Create New Project";
this.toolNew.Click += new System.EventHandler(this.toolNew_Click);
//
// toolOpen
//
this.toolOpen.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolOpen.Image = ((System.Drawing.Image)(resources.GetObject("toolOpen.Image")));
this.toolOpen.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolOpen.Name = "toolOpen";
this.toolOpen.Size = new System.Drawing.Size(23, 22);
this.toolOpen.Text = "Open Project";
this.toolOpen.Click += new System.EventHandler(this.toolOpen_Click);
//
// toolSave
//
this.toolSave.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolSave.Image = ((System.Drawing.Image)(resources.GetObject("toolSave.Image")));
this.toolSave.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolSave.Name = "toolSave";
this.toolSave.Size = new System.Drawing.Size(23, 22);
this.toolSave.Text = "Save Project";
this.toolSave.Click += new System.EventHandler(this.toolSave_Click);
//
// toolStripSeparator2
//
this.toolStripSeparator2.Name = "toolStripSeparator2";
this.toolStripSeparator2.Size = new System.Drawing.Size(6, 25);
//
// cmdDrawGrid
//
this.cmdDrawGrid.Checked = true;
this.cmdDrawGrid.CheckOnClick = true;
this.cmdDrawGrid.CheckState = System.Windows.Forms.CheckState.Checked;
this.cmdDrawGrid.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.cmdDrawGrid.Image = ((System.Drawing.Image)(resources.GetObject("cmdDrawGrid.Image")));
this.cmdDrawGrid.ImageTransparentColor = System.Drawing.Color.Magenta;
this.cmdDrawGrid.Name = "cmdDrawGrid";
this.cmdDrawGrid.Size = new System.Drawing.Size(23, 22);
this.cmdDrawGrid.Text = "Show Grid";
this.cmdDrawGrid.CheckedChanged += new System.EventHandler(this.cmdDrawGrid_CheckedChanged);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(6, 25);
//
// toolHitsToClear
//
this.toolHitsToClear.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolHitsToClear.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolStripMenuItem2,
this.toolStripMenuItem3,
this.toolStripMenuItem4,
this.toolStripMenuItem5,
this.toolStripMenuItem6,
this.toolStripMenuItem7,
this.toolStripMenuItem8,
this.toolStripMenuItem9,
this.toolStripMenuItem10});
this.toolHitsToClear.Image = ((System.Drawing.Image)(resources.GetObject("toolHitsToClear.Image")));
this.toolHitsToClear.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolHitsToClear.Name = "toolHitsToClear";
this.toolHitsToClear.Size = new System.Drawing.Size(29, 22);
this.toolHitsToClear.Text = "Hits to Clear";
//
// toolStripMenuItem2
//
this.toolStripMenuItem2.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem2.Image")));
this.toolStripMenuItem2.Name = "toolStripMenuItem2";
this.toolStripMenuItem2.Size = new System.Drawing.Size(112, 22);
this.toolStripMenuItem2.Tag = "1";
this.toolStripMenuItem2.Text = "1 Hits";
this.toolStripMenuItem2.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// toolStripMenuItem3
//
this.toolStripMenuItem3.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem3.Image")));
this.toolStripMenuItem3.Name = "toolStripMenuItem3";
this.toolStripMenuItem3.Size = new System.Drawing.Size(112, 22);
this.toolStripMenuItem3.Tag = "2";
this.toolStripMenuItem3.Text = "2 Hits";
this.toolStripMenuItem3.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// toolStripMenuItem4
//
this.toolStripMenuItem4.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem4.Image")));
this.toolStripMenuItem4.Name = "toolStripMenuItem4";
this.toolStripMenuItem4.Size = new System.Drawing.Size(112, 22);
this.toolStripMenuItem4.Tag = "3";
this.toolStripMenuItem4.Text = "3 Hits";
this.toolStripMenuItem4.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// toolStripMenuItem5
//
this.toolStripMenuItem5.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem5.Image")));
this.toolStripMenuItem5.Name = "toolStripMenuItem5";
this.toolStripMenuItem5.Size = new System.Drawing.Size(112, 22);
this.toolStripMenuItem5.Tag = "4";
this.toolStripMenuItem5.Text = "4 Hits";
this.toolStripMenuItem5.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// toolStripMenuItem6
//
this.toolStripMenuItem6.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem6.Image")));
this.toolStripMenuItem6.Name = "toolStripMenuItem6";
this.toolStripMenuItem6.Size = new System.Drawing.Size(112, 22);
this.toolStripMenuItem6.Tag = "5";
this.toolStripMenuItem6.Text = "5 Hits";
this.toolStripMenuItem6.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// toolStripMenuItem7
//
this.toolStripMenuItem7.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem7.Image")));
this.toolStripMenuItem7.Name = "toolStripMenuItem7";
this.toolStripMenuItem7.Size = new System.Drawing.Size(112, 22);
this.toolStripMenuItem7.Tag = "6";
this.toolStripMenuItem7.Text = "6 Hits";
this.toolStripMenuItem7.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// toolStripMenuItem8
//
this.toolStripMenuItem8.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem8.Image")));
this.toolStripMenuItem8.Name = "toolStripMenuItem8";
this.toolStripMenuItem8.Size = new System.Drawing.Size(112, 22);
this.toolStripMenuItem8.Tag = "7";
this.toolStripMenuItem8.Text = "7 Hits";
this.toolStripMenuItem8.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// toolStripMenuItem9
//
this.toolStripMenuItem9.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem9.Image")));
this.toolStripMenuItem9.Name = "toolStripMenuItem9";
this.toolStripMenuItem9.Size = new System.Drawing.Size(112, 22);
this.toolStripMenuItem9.Tag = "8";
this.toolStripMenuItem9.Text = "8 Hits";
this.toolStripMenuItem9.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// toolStripMenuItem10
//
this.toolStripMenuItem10.Image = ((System.Drawing.Image)(resources.GetObject("toolStripMenuItem10.Image")));
this.toolStripMenuItem10.Name = "toolStripMenuItem10";
this.toolStripMenuItem10.Size = new System.Drawing.Size(112, 22);
this.toolStripMenuItem10.Tag = "9";
this.toolStripMenuItem10.Text = "9 Hits";
this.toolStripMenuItem10.Click += new System.EventHandler(this.toolStripMenuItem2_Click);
//
// splitContainer1
//
this.splitContainer1.Dock = System.Windows.Forms.DockStyle.Fill;
this.splitContainer1.FixedPanel = System.Windows.Forms.FixedPanel.Panel1;
this.splitContainer1.Location = new System.Drawing.Point(0, 49);
this.splitContainer1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.splitContainer1.Name = "splitContainer1";
//
// splitContainer1.Panel1
//
this.splitContainer1.Panel1.Controls.Add(this.treeView1);
this.splitContainer1.Panel1.Controls.Add(this.toolStrip2);
//
// splitContainer1.Panel2
//
this.splitContainer1.Panel2.AutoScroll = true;
this.splitContainer1.Panel2.BackColor = System.Drawing.SystemColors.ControlDark;
this.splitContainer1.Panel2.Controls.Add(this.brickBreakerEditorControl1);
this.splitContainer1.Size = new System.Drawing.Size(594, 412);
this.splitContainer1.SplitterDistance = 195;
this.splitContainer1.SplitterWidth = 3;
this.splitContainer1.TabIndex = 1;
//
// treeView1
//
this.treeView1.Dock = System.Windows.Forms.DockStyle.Fill;
this.treeView1.HideSelection = false;
this.treeView1.ImageIndex = 0;
this.treeView1.ImageList = this.imageList1;
this.treeView1.Location = new System.Drawing.Point(0, 25);
this.treeView1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.treeView1.Name = "treeView1";
treeNode1.ImageIndex = 2;
treeNode1.Name = "Node2";
treeNode1.SelectedImageIndex = 2;
treeNode1.Text = "Level01";
treeNode2.ImageIndex = 2;
treeNode2.Name = "Node3";
treeNode2.SelectedImageIndex = 2;
treeNode2.Text = "Level02";
treeNode3.ImageIndex = 1;
treeNode3.Name = "Node1";
treeNode3.SelectedImageIndex = 1;
treeNode3.Text = "Group01";
treeNode4.Name = "Node0";
treeNode4.Text = "Project [Example01]";
treeNode4.ToolTipText = "c:\\projects\\XNA Book\\Genre\\BrickBreaker\\levels\\Example01.bbp";
this.treeView1.Nodes.AddRange(new System.Windows.Forms.TreeNode[] {
treeNode4});
this.treeView1.SelectedImageIndex = 0;
this.treeView1.Size = new System.Drawing.Size(195, 387);
this.treeView1.TabIndex = 0;
this.treeView1.AfterSelect += new System.Windows.Forms.TreeViewEventHandler(this.treeView1_AfterSelect);
//
// imageList1
//
this.imageList1.ImageStream = ((System.Windows.Forms.ImageListStreamer)(resources.GetObject("imageList1.ImageStream")));
this.imageList1.TransparentColor = System.Drawing.Color.Transparent;
this.imageList1.Images.SetKeyName(0, "project.png");
this.imageList1.Images.SetKeyName(1, "");
this.imageList1.Images.SetKeyName(2, "level.png");
//
// toolStrip2
//
this.toolStrip2.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.toolAddNewLevel,
this.toolCopyLevel,
this.toolMoveLevelUp,
this.toolMoveLevelDown,
this.toolDeleteLevel});
this.toolStrip2.Location = new System.Drawing.Point(0, 0);
this.toolStrip2.Name = "toolStrip2";
this.toolStrip2.Size = new System.Drawing.Size(195, 25);
this.toolStrip2.TabIndex = 1;
this.toolStrip2.Text = "toolStrip2";
//
// toolAddNewLevel
//
this.toolAddNewLevel.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolAddNewLevel.Image = ((System.Drawing.Image)(resources.GetObject("toolAddNewLevel.Image")));
this.toolAddNewLevel.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolAddNewLevel.Name = "toolAddNewLevel";
this.toolAddNewLevel.Size = new System.Drawing.Size(23, 22);
this.toolAddNewLevel.Text = "Add New Level";
this.toolAddNewLevel.Click += new System.EventHandler(this.toolAddNewLevel_Click);
//
// toolCopyLevel
//
this.toolCopyLevel.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolCopyLevel.Image = ((System.Drawing.Image)(resources.GetObject("toolCopyLevel.Image")));
this.toolCopyLevel.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolCopyLevel.Name = "toolCopyLevel";
this.toolCopyLevel.Size = new System.Drawing.Size(23, 22);
this.toolCopyLevel.Text = "toolStripButton1";
this.toolCopyLevel.ToolTipText = "Copy Level";
this.toolCopyLevel.Click += new System.EventHandler(this.toolCopyLevel_Click);
//
// toolMoveLevelUp
//
this.toolMoveLevelUp.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolMoveLevelUp.Image = ((System.Drawing.Image)(resources.GetObject("toolMoveLevelUp.Image")));
this.toolMoveLevelUp.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolMoveLevelUp.Name = "toolMoveLevelUp";
this.toolMoveLevelUp.Size = new System.Drawing.Size(23, 22);
this.toolMoveLevelUp.Text = "Move Level Up";
this.toolMoveLevelUp.Click += new System.EventHandler(this.toolMoveLevelUp_Click);
//
// toolMoveLevelDown
//
this.toolMoveLevelDown.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolMoveLevelDown.Image = ((System.Drawing.Image)(resources.GetObject("toolMoveLevelDown.Image")));
this.toolMoveLevelDown.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolMoveLevelDown.Name = "toolMoveLevelDown";
this.toolMoveLevelDown.Size = new System.Drawing.Size(23, 22);
this.toolMoveLevelDown.Text = "Move Level Down";
this.toolMoveLevelDown.Click += new System.EventHandler(this.toolMoveLevelDown_Click);
//
// toolDeleteLevel
//
this.toolDeleteLevel.DisplayStyle = System.Windows.Forms.ToolStripItemDisplayStyle.Image;
this.toolDeleteLevel.Image = ((System.Drawing.Image)(resources.GetObject("toolDeleteLevel.Image")));
this.toolDeleteLevel.ImageTransparentColor = System.Drawing.Color.Magenta;
this.toolDeleteLevel.Name = "toolDeleteLevel";
this.toolDeleteLevel.Size = new System.Drawing.Size(23, 22);
this.toolDeleteLevel.Text = "Delete Level";
this.toolDeleteLevel.Click += new System.EventHandler(this.toolDeleteLevel_Click);
//
// menuStrip1
//
this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuFile});
this.menuStrip1.Location = new System.Drawing.Point(0, 0);
this.menuStrip1.Name = "menuStrip1";
this.menuStrip1.Padding = new System.Windows.Forms.Padding(4, 2, 0, 2);
this.menuStrip1.Size = new System.Drawing.Size(594, 24);
this.menuStrip1.TabIndex = 2;
this.menuStrip1.Text = "menuStrip1";
//
// mnuFile
//
this.mnuFile.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.mnuFileNew,
this.mnuFileOpen,
this.mnuFileClose,
this.mnuFileSave,
this.mnuFileSaveAs,
this.mnuFileExit});
this.mnuFile.Name = "mnuFile";
this.mnuFile.Size = new System.Drawing.Size(35, 20);
this.mnuFile.Text = "&File";
//
// mnuFileNew
//
this.mnuFileNew.Name = "mnuFileNew";
this.mnuFileNew.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.N)));
this.mnuFileNew.Size = new System.Drawing.Size(207, 22);
this.mnuFileNew.Text = "&New";
this.mnuFileNew.Click += new System.EventHandler(this.mnuFileNew_Click);
//
// mnuFileOpen
//
this.mnuFileOpen.Name = "mnuFileOpen";
this.mnuFileOpen.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.O)));
this.mnuFileOpen.Size = new System.Drawing.Size(207, 22);
this.mnuFileOpen.Text = "&Open";
this.mnuFileOpen.Click += new System.EventHandler(this.mnuFileOpen_Click);
//
// mnuFileClose
//
this.mnuFileClose.Name = "mnuFileClose";
this.mnuFileClose.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.F4)));
this.mnuFileClose.Size = new System.Drawing.Size(207, 22);
this.mnuFileClose.Text = "&Close";
//
// mnuFileSave
//
this.mnuFileSave.Name = "mnuFileSave";
this.mnuFileSave.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.S)));
this.mnuFileSave.Size = new System.Drawing.Size(207, 22);
this.mnuFileSave.Text = "&Save";
this.mnuFileSave.Click += new System.EventHandler(this.mnuFileSave_Click);
//
// mnuFileSaveAs
//
this.mnuFileSaveAs.Name = "mnuFileSaveAs";
this.mnuFileSaveAs.ShortcutKeys = ((System.Windows.Forms.Keys)(((System.Windows.Forms.Keys.Control | System.Windows.Forms.Keys.Shift)
| System.Windows.Forms.Keys.S)));
this.mnuFileSaveAs.Size = new System.Drawing.Size(207, 22);
this.mnuFileSaveAs.Text = "Save &As ...";
this.mnuFileSaveAs.Click += new System.EventHandler(this.mnuFileSaveAs_Click);
//
// mnuFileExit
//
this.mnuFileExit.Name = "mnuFileExit";
this.mnuFileExit.ShortcutKeys = ((System.Windows.Forms.Keys)((System.Windows.Forms.Keys.Alt | System.Windows.Forms.Keys.F4)));
this.mnuFileExit.Size = new System.Drawing.Size(207, 22);
this.mnuFileExit.Text = "E&xit";
this.mnuFileExit.Click += new System.EventHandler(this.mnuFileExit_Click);
//
// openFileDialog1
//
this.openFileDialog1.FileName = "openFileDialog1";
this.openFileDialog1.Filter = "BrickBreaker Projects|*.bbp|All Files|*.*";
//
// saveFileDialog1
//
this.saveFileDialog1.Filter = "BrickBreaker Projects|*.bbp|All Files|*.*";
//
// brickBreakerEditorControl1
//
this.brickBreakerEditorControl1.DrawGrid = true;
levelData1.BrickHeight = 20;
levelData1.BrickWidth = 40;
levelData1.Changed = true;
this.brickBreakerEditorControl1.LevelData = levelData1;
this.brickBreakerEditorControl1.Location = new System.Drawing.Point(0, 0);
this.brickBreakerEditorControl1.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.brickBreakerEditorControl1.Name = "brickBreakerEditorControl1";
this.brickBreakerEditorControl1.NumHitsToClear = 1;
this.brickBreakerEditorControl1.Size = new System.Drawing.Size(480, 480);
this.brickBreakerEditorControl1.TabIndex = 0;
//
// EditorForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(594, 461);
this.Controls.Add(this.splitContainer1);
this.Controls.Add(this.toolStrip1);
this.Controls.Add(this.menuStrip1);
this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Name = "EditorForm";
this.Text = "BrickBreaker Level Editor";
this.FormClosing += new System.Windows.Forms.FormClosingEventHandler(this.BrickBreakerEditor_FormClosing);
this.toolStrip1.ResumeLayout(false);
this.toolStrip1.PerformLayout();
this.splitContainer1.Panel1.ResumeLayout(false);
this.splitContainer1.Panel1.PerformLayout();
this.splitContainer1.Panel2.ResumeLayout(false);
this.splitContainer1.ResumeLayout(false);
this.toolStrip2.ResumeLayout(false);
this.toolStrip2.PerformLayout();
this.menuStrip1.ResumeLayout(false);
this.menuStrip1.PerformLayout();
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private System.Windows.Forms.ToolStrip toolStrip1;
private System.Windows.Forms.SplitContainer splitContainer1;
private System.Windows.Forms.TreeView treeView1;
private System.Windows.Forms.ImageList imageList1;
private EditorControl brickBreakerEditorControl1;
private System.Windows.Forms.ToolStripButton cmdDrawGrid;
private System.Windows.Forms.MenuStrip menuStrip1;
private System.Windows.Forms.ToolStripMenuItem mnuFile;
private System.Windows.Forms.ToolStripMenuItem mnuFileNew;
private System.Windows.Forms.ToolStripMenuItem mnuFileOpen;
private System.Windows.Forms.ToolStripMenuItem mnuFileClose;
private System.Windows.Forms.ToolStripMenuItem mnuFileSave;
private System.Windows.Forms.ToolStripMenuItem mnuFileSaveAs;
private System.Windows.Forms.ToolStripMenuItem mnuFileExit;
private System.Windows.Forms.ToolStrip toolStrip2;
private System.Windows.Forms.ToolStripButton toolMoveLevelUp;
private System.Windows.Forms.ToolStripButton toolMoveLevelDown;
private System.Windows.Forms.ToolStripButton toolDeleteLevel;
private System.Windows.Forms.ToolStripButton toolAddNewLevel;
private System.Windows.Forms.OpenFileDialog openFileDialog1;
private System.Windows.Forms.SaveFileDialog saveFileDialog1;
private System.Windows.Forms.ToolStripDropDownButton toolHitsToClear;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem2;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem3;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem4;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem5;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem6;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem7;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem8;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem9;
private System.Windows.Forms.ToolStripMenuItem toolStripMenuItem10;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator2;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripButton toolNew;
private System.Windows.Forms.ToolStripButton toolOpen;
private System.Windows.Forms.ToolStripButton toolSave;
private System.Windows.Forms.ToolStripButton toolCopyLevel;
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp.Extensions;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.ExtractMethod;
using Microsoft.CodeAnalysis.Shared.Extensions;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
namespace Microsoft.CodeAnalysis.CSharp.ExtractMethod
{
internal static class Extensions
{
public static ExpressionSyntax GetUnparenthesizedExpression(this SyntaxNode node)
{
var parenthesizedExpression = node as ParenthesizedExpressionSyntax;
if (parenthesizedExpression == null)
{
return node as ExpressionSyntax;
}
return GetUnparenthesizedExpression(parenthesizedExpression.Expression);
}
public static StatementSyntax GetStatementUnderContainer(this SyntaxNode node)
{
Contract.ThrowIfNull(node);
while (node != null)
{
if (node.Parent != null &&
node.Parent.IsStatementContainerNode())
{
return node as StatementSyntax;
}
node = node.Parent;
}
return null;
}
public static StatementSyntax GetParentLabeledStatementIfPossible(this SyntaxNode node)
{
return (StatementSyntax)((node.Parent is LabeledStatementSyntax) ? node.Parent : node);
}
public static bool IsStatementContainerNode(this SyntaxNode node)
{
return node is BlockSyntax || node is SwitchSectionSyntax;
}
public static BlockSyntax GetBlockBody(this SyntaxNode node)
{
return node.TypeSwitch(
(BaseMethodDeclarationSyntax m) => m.Body,
(AccessorDeclarationSyntax a) => a.Body,
(SimpleLambdaExpressionSyntax s) => s.Body as BlockSyntax,
(ParenthesizedLambdaExpressionSyntax p) => p.Body as BlockSyntax,
(AnonymousMethodExpressionSyntax a) => a.Block);
}
public static bool UnderValidContext(this SyntaxNode node)
{
Contract.ThrowIfNull(node);
Func<SyntaxNode, bool> predicate = n =>
{
if (n is BaseMethodDeclarationSyntax ||
n is AccessorDeclarationSyntax ||
n is BlockSyntax ||
n is GlobalStatementSyntax)
{
return true;
}
var constructorInitializer = n as ConstructorInitializerSyntax;
if (constructorInitializer != null)
{
return constructorInitializer.ContainsInArgument(node.Span);
}
return false;
};
if (!node.GetAncestorsOrThis<SyntaxNode>().Any(predicate))
{
return false;
}
if (node.FromScript() || node.GetAncestor<TypeDeclarationSyntax>() != null)
{
return true;
}
return false;
}
public static bool UnderValidContext(this SyntaxToken token)
{
return token.GetAncestors<SyntaxNode>().Any(n => n.CheckTopLevel(token.Span));
}
public static bool PartOfConstantInitializerExpression(this SyntaxNode node)
{
return node.PartOfConstantInitializerExpression<FieldDeclarationSyntax>(n => n.Modifiers) ||
node.PartOfConstantInitializerExpression<LocalDeclarationStatementSyntax>(n => n.Modifiers);
}
private static bool PartOfConstantInitializerExpression<T>(this SyntaxNode node, Func<T, SyntaxTokenList> modifiersGetter) where T : SyntaxNode
{
var decl = node.GetAncestor<T>();
if (decl == null)
{
return false;
}
if (!modifiersGetter(decl).Any(t => t.Kind() == SyntaxKind.ConstKeyword))
{
return false;
}
// we are under decl with const modifier, check we are part of initializer expression
var equal = node.GetAncestor<EqualsValueClauseSyntax>();
if (equal == null)
{
return false;
}
return equal.Value != null && equal.Value.Span.Contains(node.Span);
}
public static bool ContainArgumentlessThrowWithoutEnclosingCatch(this IEnumerable<SyntaxToken> tokens, TextSpan textSpan)
{
foreach (var token in tokens)
{
if (token.Kind() != SyntaxKind.ThrowKeyword)
{
continue;
}
var throwStatement = token.Parent as ThrowStatementSyntax;
if (throwStatement == null || throwStatement.Expression != null)
{
continue;
}
var catchClause = token.GetAncestor<CatchClauseSyntax>();
if (catchClause == null || !textSpan.Contains(catchClause.Span))
{
return true;
}
}
return false;
}
public static bool ContainPreprocessorCrossOver(this IEnumerable<SyntaxToken> tokens, TextSpan textSpan)
{
int activeRegions = 0;
int activeIfs = 0;
foreach (var trivia in tokens.GetAllTrivia())
{
if (!textSpan.Contains(trivia.Span))
{
continue;
}
switch (trivia.Kind())
{
case SyntaxKind.RegionDirectiveTrivia:
activeRegions++;
break;
case SyntaxKind.EndRegionDirectiveTrivia:
if (activeRegions <= 0)
{
return true;
}
activeRegions--;
break;
case SyntaxKind.IfDirectiveTrivia:
activeIfs++;
break;
case SyntaxKind.EndIfDirectiveTrivia:
if (activeIfs <= 0)
{
return true;
}
activeIfs--;
break;
case SyntaxKind.ElseDirectiveTrivia:
case SyntaxKind.ElifDirectiveTrivia:
if (activeIfs <= 0)
{
return true;
}
break;
}
}
return activeIfs != 0 || activeRegions != 0;
}
public static IEnumerable<SyntaxTrivia> GetAllTrivia(this IEnumerable<SyntaxToken> tokens)
{
foreach (var token in tokens)
{
foreach (var trivia in token.LeadingTrivia)
{
yield return trivia;
}
foreach (var trivia in token.TrailingTrivia)
{
yield return trivia;
}
}
}
public static bool HasSyntaxAnnotation(this HashSet<SyntaxAnnotation> set, SyntaxNode node)
{
return set.Any(a => node.GetAnnotatedNodesAndTokens(a).Any());
}
public static bool HasHybridTriviaBetween(this SyntaxToken token1, SyntaxToken token2)
{
if (token1.TrailingTrivia.Any(t => !t.IsElastic()))
{
return true;
}
if (token2.LeadingTrivia.Any(t => !t.IsElastic()))
{
return true;
}
return false;
}
public static bool IsArrayInitializer(this SyntaxNode node)
{
return node is InitializerExpressionSyntax && node.Parent is EqualsValueClauseSyntax;
}
public static bool IsExpressionInCast(this SyntaxNode node)
{
return node is ExpressionSyntax && node.Parent is CastExpressionSyntax;
}
public static bool IsExpression(this SyntaxNode node)
{
return node is ExpressionSyntax;
}
public static bool IsErrorType(this ITypeSymbol type)
{
return type == null || type.Kind == SymbolKind.ErrorType;
}
public static bool IsObjectType(this ITypeSymbol type)
{
return type == null || type.SpecialType == SpecialType.System_Object;
}
public static bool BetweenFieldAndNonFieldMember(this SyntaxToken token1, SyntaxToken token2)
{
if (token1.RawKind != (int)SyntaxKind.SemicolonToken || !(token1.Parent is FieldDeclarationSyntax))
{
return false;
}
var field = token2.GetAncestor<FieldDeclarationSyntax>();
return field == null;
}
}
}
| |
// 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 Avalonia.Input.Platform;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reactive.Linq;
using Avalonia.Controls.Presenters;
using Avalonia.Controls.Primitives;
using Avalonia.Controls.Templates;
using Avalonia.Controls.Utils;
using Avalonia.Input;
using Avalonia.Interactivity;
using Avalonia.Media;
using Avalonia.Metadata;
using Avalonia.Data;
namespace Avalonia.Controls
{
public class TextBox : TemplatedControl, UndoRedoHelper<TextBox.UndoRedoState>.IUndoRedoHost
{
public static readonly StyledProperty<bool> AcceptsReturnProperty =
AvaloniaProperty.Register<TextBox, bool>("AcceptsReturn");
public static readonly StyledProperty<bool> AcceptsTabProperty =
AvaloniaProperty.Register<TextBox, bool>("AcceptsTab");
public static readonly DirectProperty<TextBox, bool> CanScrollHorizontallyProperty =
AvaloniaProperty.RegisterDirect<TextBox, bool>("CanScrollHorizontally", o => o.CanScrollHorizontally);
public static readonly DirectProperty<TextBox, int> CaretIndexProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(CaretIndex),
o => o.CaretIndex,
(o, v) => o.CaretIndex = v);
public static readonly DirectProperty<TextBox, IEnumerable<Exception>> DataValidationErrorsProperty =
AvaloniaProperty.RegisterDirect<TextBox, IEnumerable<Exception>>(
nameof(DataValidationErrors),
o => o.DataValidationErrors);
public static readonly StyledProperty<bool> IsReadOnlyProperty =
AvaloniaProperty.Register<TextBox, bool>(nameof(IsReadOnly));
public static readonly DirectProperty<TextBox, int> SelectionStartProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(SelectionStart),
o => o.SelectionStart,
(o, v) => o.SelectionStart = v);
public static readonly DirectProperty<TextBox, int> SelectionEndProperty =
AvaloniaProperty.RegisterDirect<TextBox, int>(
nameof(SelectionEnd),
o => o.SelectionEnd,
(o, v) => o.SelectionEnd = v);
public static readonly DirectProperty<TextBox, string> TextProperty =
TextBlock.TextProperty.AddOwner<TextBox>(
o => o.Text,
(o, v) => o.Text = v,
defaultBindingMode: BindingMode.TwoWay,
enableDataValidation: true);
public static readonly StyledProperty<TextAlignment> TextAlignmentProperty =
TextBlock.TextAlignmentProperty.AddOwner<TextBox>();
public static readonly StyledProperty<TextWrapping> TextWrappingProperty =
TextBlock.TextWrappingProperty.AddOwner<TextBox>();
public static readonly StyledProperty<string> WatermarkProperty =
AvaloniaProperty.Register<TextBox, string>("Watermark");
public static readonly StyledProperty<bool> UseFloatingWatermarkProperty =
AvaloniaProperty.Register<TextBox, bool>("UseFloatingWatermark");
struct UndoRedoState : IEquatable<UndoRedoState>
{
public string Text { get; }
public int CaretPosition { get; }
public UndoRedoState(string text, int caretPosition)
{
Text = text;
CaretPosition = caretPosition;
}
public bool Equals(UndoRedoState other) => ReferenceEquals(Text, other.Text) || Equals(Text, other.Text);
}
private string _text;
private int _caretIndex;
private int _selectionStart;
private int _selectionEnd;
private bool _canScrollHorizontally;
private TextPresenter _presenter;
private UndoRedoHelper<UndoRedoState> _undoRedoHelper;
private bool _ignoreTextChanges;
private IEnumerable<Exception> _dataValidationErrors;
static TextBox()
{
FocusableProperty.OverrideDefaultValue(typeof(TextBox), true);
}
public TextBox()
{
this.GetObservable(TextWrappingProperty)
.Select(x => x == TextWrapping.NoWrap)
.Subscribe(x => CanScrollHorizontally = x);
var horizontalScrollBarVisibility = this.GetObservable(AcceptsReturnProperty)
.Select(x => x ? ScrollBarVisibility.Auto : ScrollBarVisibility.Hidden);
Bind(
ScrollViewer.HorizontalScrollBarVisibilityProperty,
horizontalScrollBarVisibility,
BindingPriority.Style);
_undoRedoHelper = new UndoRedoHelper<UndoRedoState>(this);
}
public bool AcceptsReturn
{
get { return GetValue(AcceptsReturnProperty); }
set { SetValue(AcceptsReturnProperty, value); }
}
public bool AcceptsTab
{
get { return GetValue(AcceptsTabProperty); }
set { SetValue(AcceptsTabProperty, value); }
}
public bool CanScrollHorizontally
{
get { return _canScrollHorizontally; }
private set { SetAndRaise(CanScrollHorizontallyProperty, ref _canScrollHorizontally, value); }
}
public int CaretIndex
{
get
{
return _caretIndex;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(CaretIndexProperty, ref _caretIndex, value);
UndoRedoState state;
if (_undoRedoHelper.TryGetLastState(out state) && state.Text == Text)
_undoRedoHelper.UpdateLastState();
}
}
public IEnumerable<Exception> DataValidationErrors
{
get { return _dataValidationErrors; }
private set { SetAndRaise(DataValidationErrorsProperty, ref _dataValidationErrors, value); }
}
public bool IsReadOnly
{
get { return GetValue(IsReadOnlyProperty); }
set { SetValue(IsReadOnlyProperty, value); }
}
public int SelectionStart
{
get
{
return _selectionStart;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionStartProperty, ref _selectionStart, value);
}
}
public int SelectionEnd
{
get
{
return _selectionEnd;
}
set
{
value = CoerceCaretIndex(value);
SetAndRaise(SelectionEndProperty, ref _selectionEnd, value);
}
}
[Content]
public string Text
{
get { return _text; }
set
{
if (!_ignoreTextChanges)
{
CaretIndex = CoerceCaretIndex(CaretIndex, value?.Length ?? 0);
SetAndRaise(TextProperty, ref _text, value);
}
}
}
public TextAlignment TextAlignment
{
get { return GetValue(TextAlignmentProperty); }
set { SetValue(TextAlignmentProperty, value); }
}
public string Watermark
{
get { return GetValue(WatermarkProperty); }
set { SetValue(WatermarkProperty, value); }
}
public bool UseFloatingWatermark
{
get { return GetValue(UseFloatingWatermarkProperty); }
set { SetValue(UseFloatingWatermarkProperty, value); }
}
public TextWrapping TextWrapping
{
get { return GetValue(TextWrappingProperty); }
set { SetValue(TextWrappingProperty, value); }
}
protected override void OnTemplateApplied(TemplateAppliedEventArgs e)
{
_presenter = e.NameScope.Get<TextPresenter>("PART_TextPresenter");
_presenter.Cursor = new Cursor(StandardCursorType.Ibeam);
}
protected override void OnGotFocus(GotFocusEventArgs e)
{
base.OnGotFocus(e);
// when navigating to a textbox via the tab key, select all text if
// 1) this textbox is *not* a multiline textbox
// 2) this textbox has any text to select
if (e.NavigationMethod == NavigationMethod.Tab &&
!AcceptsReturn &&
Text?.Length > 0)
{
SelectionStart = 0;
SelectionEnd = Text.Length;
}
else
{
_presenter.ShowCaret();
}
}
protected override void OnLostFocus(RoutedEventArgs e)
{
base.OnLostFocus(e);
SelectionStart = 0;
SelectionEnd = 0;
_presenter.HideCaret();
}
protected override void OnTextInput(TextInputEventArgs e)
{
HandleTextInput(e.Text);
}
private void HandleTextInput(string input)
{
if (!IsReadOnly)
{
string text = Text ?? string.Empty;
int caretIndex = CaretIndex;
if (!string.IsNullOrEmpty(input))
{
DeleteSelection();
caretIndex = CaretIndex;
text = Text ?? string.Empty;
SetTextInternal(text.Substring(0, caretIndex) + input + text.Substring(caretIndex));
CaretIndex += input.Length;
SelectionStart = SelectionEnd = CaretIndex;
_undoRedoHelper.DiscardRedo();
}
}
}
private async void Copy()
{
await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard)))
.SetTextAsync(GetSelection());
}
private async void Paste()
{
var text = await ((IClipboard)AvaloniaLocator.Current.GetService(typeof(IClipboard))).GetTextAsync();
if (text == null)
{
return;
}
_undoRedoHelper.Snapshot();
HandleTextInput(text);
}
protected override void OnKeyDown(KeyEventArgs e)
{
string text = Text ?? string.Empty;
int caretIndex = CaretIndex;
bool movement = false;
bool handled = true;
var modifiers = e.Modifiers;
switch (e.Key)
{
case Key.A:
if (modifiers == InputModifiers.Control)
{
SelectAll();
}
break;
case Key.C:
if (modifiers == InputModifiers.Control)
{
Copy();
}
break;
case Key.X:
if (modifiers == InputModifiers.Control)
{
Copy();
DeleteSelection();
}
break;
case Key.V:
if (modifiers == InputModifiers.Control)
{
Paste();
}
break;
case Key.Z:
if (modifiers == InputModifiers.Control)
_undoRedoHelper.Undo();
break;
case Key.Y:
if (modifiers == InputModifiers.Control)
_undoRedoHelper.Redo();
break;
case Key.Left:
MoveHorizontal(-1, modifiers);
movement = true;
break;
case Key.Right:
MoveHorizontal(1, modifiers);
movement = true;
break;
case Key.Up:
MoveVertical(-1, modifiers);
movement = true;
break;
case Key.Down:
MoveVertical(1, modifiers);
movement = true;
break;
case Key.Home:
MoveHome(modifiers);
movement = true;
break;
case Key.End:
MoveEnd(modifiers);
movement = true;
break;
case Key.Back:
if (modifiers == InputModifiers.Control && SelectionStart == SelectionEnd)
{
SetSelectionForControlBackspace(modifiers);
}
if (!DeleteSelection() && CaretIndex > 0)
{
var removedCharacters = 1;
// handle deleting /r/n
// you don't ever want to leave a dangling /r around. So, if deleting /n, check to see if
// a /r should also be deleted.
if (CaretIndex > 1 &&
text[CaretIndex - 1] == '\n' &&
text[CaretIndex - 2] == '\r')
{
removedCharacters = 2;
}
SetTextInternal(text.Substring(0, caretIndex - removedCharacters) + text.Substring(caretIndex));
CaretIndex -= removedCharacters;
SelectionStart = SelectionEnd = CaretIndex;
}
break;
case Key.Delete:
if (modifiers == InputModifiers.Control && SelectionStart == SelectionEnd)
{
SetSelectionForControlDelete(modifiers);
}
if (!DeleteSelection() && caretIndex < text.Length)
{
var removedCharacters = 1;
// handle deleting /r/n
// you don't ever want to leave a dangling /r around. So, if deleting /n, check to see if
// a /r should also be deleted.
if (CaretIndex < text.Length - 1 &&
text[caretIndex + 1] == '\n' &&
text[caretIndex] == '\r')
{
removedCharacters = 2;
}
SetTextInternal(text.Substring(0, caretIndex) + text.Substring(caretIndex + removedCharacters));
}
break;
case Key.Enter:
if (AcceptsReturn)
{
HandleTextInput("\r\n");
}
break;
case Key.Tab:
if (AcceptsTab)
{
HandleTextInput("\t");
}
else
{
base.OnKeyDown(e);
handled = false;
}
break;
default:
handled = false;
break;
}
if (movement && ((modifiers & InputModifiers.Shift) != 0))
{
SelectionEnd = CaretIndex;
}
else if (movement)
{
SelectionStart = SelectionEnd = CaretIndex;
}
if (handled)
{
e.Handled = true;
}
}
protected override void OnPointerPressed(PointerPressedEventArgs e)
{
if (e.Source == _presenter)
{
var point = e.GetPosition(_presenter);
var index = CaretIndex = _presenter.GetCaretIndex(point);
var text = Text;
if (text != null)
{
switch (e.ClickCount)
{
case 1:
SelectionStart = SelectionEnd = index;
break;
case 2:
if (!StringUtils.IsStartOfWord(text, index))
{
SelectionStart = StringUtils.PreviousWord(text, index);
}
SelectionEnd = StringUtils.NextWord(text, index);
break;
case 3:
SelectionStart = 0;
SelectionEnd = text.Length;
break;
}
}
e.Device.Capture(_presenter);
e.Handled = true;
}
}
protected override void OnPointerMoved(PointerEventArgs e)
{
if (_presenter != null && e.Device.Captured == _presenter)
{
var point = e.GetPosition(_presenter);
CaretIndex = SelectionEnd = _presenter.GetCaretIndex(point);
}
}
protected override void OnPointerReleased(PointerEventArgs e)
{
if (_presenter != null && e.Device.Captured == _presenter)
{
e.Device.Capture(null);
}
}
protected override void UpdateDataValidation(AvaloniaProperty property, BindingNotification status)
{
if (property == TextProperty)
{
var classes = (IPseudoClasses)Classes;
DataValidationErrors = UnpackException(status.Error);
classes.Set(":error", DataValidationErrors != null);
}
}
private static IEnumerable<Exception> UnpackException(Exception exception)
{
if (exception != null)
{
var aggregate = exception as AggregateException;
var exceptions = aggregate == null ?
(IEnumerable<Exception>)new[] { exception } :
aggregate.InnerExceptions;
var filtered = exceptions.Where(x => !(x is BindingChainException)).ToList();
if (filtered.Count > 0)
{
return filtered;
}
}
return null;
}
private int CoerceCaretIndex(int value) => CoerceCaretIndex(value, Text?.Length ?? 0);
private int CoerceCaretIndex(int value, int length)
{
var text = Text;
if (value < 0)
{
return 0;
}
else if (value > length)
{
return length;
}
else if (value > 0 && text[value - 1] == '\r' && text[value] == '\n')
{
return value + 1;
}
else
{
return value;
}
}
private int DeleteCharacter(int index)
{
var start = index + 1;
var text = Text;
var c = text[index];
var result = 1;
if (c == '\n' && index > 0 && text[index - 1] == '\r')
{
--index;
++result;
}
else if (c == '\r' && index < text.Length - 1 && text[index + 1] == '\n')
{
++start;
++result;
}
Text = text.Substring(0, index) + text.Substring(start);
return result;
}
private void MoveHorizontal(int direction, InputModifiers modifiers)
{
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if ((modifiers & InputModifiers.Control) == 0)
{
var index = caretIndex + direction;
if (index < 0 || index > text.Length)
{
return;
}
else if (index == text.Length)
{
CaretIndex = index;
return;
}
var c = text[index];
if (direction > 0)
{
CaretIndex += (c == '\r' && index < text.Length - 1 && text[index + 1] == '\n') ? 2 : 1;
}
else
{
CaretIndex -= (c == '\n' && index > 0 && text[index - 1] == '\r') ? 2 : 1;
}
}
else
{
if (direction > 0)
{
CaretIndex += StringUtils.NextWord(text, caretIndex) - caretIndex;
}
else
{
CaretIndex += StringUtils.PreviousWord(text, caretIndex) - caretIndex;
}
}
}
private void MoveVertical(int count, InputModifiers modifiers)
{
var formattedText = _presenter.FormattedText;
var lines = formattedText.GetLines().ToList();
var caretIndex = CaretIndex;
var lineIndex = GetLine(caretIndex, lines) + count;
if (lineIndex >= 0 && lineIndex < lines.Count)
{
var line = lines[lineIndex];
var rect = formattedText.HitTestTextPosition(caretIndex);
var y = count < 0 ? rect.Y : rect.Bottom;
var point = new Point(rect.X, y + (count * (line.Height / 2)));
var hit = formattedText.HitTestPoint(point);
CaretIndex = hit.TextPosition + (hit.IsTrailing ? 1 : 0);
}
}
private void MoveHome(InputModifiers modifiers)
{
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if ((modifiers & InputModifiers.Control) != 0)
{
caretIndex = 0;
}
else
{
var lines = _presenter.FormattedText.GetLines();
var pos = 0;
foreach (var line in lines)
{
if (pos + line.Length > caretIndex || pos + line.Length == text.Length)
{
break;
}
pos += line.Length;
}
caretIndex = pos;
}
CaretIndex = caretIndex;
}
private void MoveEnd(InputModifiers modifiers)
{
var text = Text ?? string.Empty;
var caretIndex = CaretIndex;
if ((modifiers & InputModifiers.Control) != 0)
{
caretIndex = text.Length;
}
else
{
var lines = _presenter.FormattedText.GetLines();
var pos = 0;
foreach (var line in lines)
{
pos += line.Length;
if (pos > caretIndex)
{
if (pos < text.Length)
{
--pos;
if (pos > 0 && Text[pos - 1] == '\r' && Text[pos] == '\n')
{
--pos;
}
}
break;
}
}
caretIndex = pos;
}
CaretIndex = caretIndex;
}
private void SelectAll()
{
SelectionStart = 0;
SelectionEnd = Text?.Length ?? 0;
}
private bool DeleteSelection()
{
if (!IsReadOnly)
{
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
if (selectionStart != selectionEnd)
{
var start = Math.Min(selectionStart, selectionEnd);
var end = Math.Max(selectionStart, selectionEnd);
var text = Text;
SetTextInternal(text.Substring(0, start) + text.Substring(end));
SelectionStart = SelectionEnd = CaretIndex = start;
return true;
}
else
{
return false;
}
}
else
{
return true;
}
}
private string GetSelection()
{
var selectionStart = SelectionStart;
var selectionEnd = SelectionEnd;
var start = Math.Min(selectionStart, selectionEnd);
var end = Math.Max(selectionStart, selectionEnd);
if (start == end || (Text?.Length ?? 0) < end)
{
return "";
}
return Text.Substring(start, end - start);
}
private int GetLine(int caretIndex, IList<FormattedTextLine> lines)
{
int pos = 0;
int i;
for (i = 0; i < lines.Count; ++i)
{
var line = lines[i];
pos += line.Length;
if (pos > caretIndex)
{
break;
}
}
return i;
}
private void SetTextInternal(string value)
{
try
{
_ignoreTextChanges = true;
SetAndRaise(TextProperty, ref _text, value);
}
finally
{
_ignoreTextChanges = false;
}
}
private void SetSelectionForControlBackspace(InputModifiers modifiers)
{
SelectionStart = CaretIndex;
MoveHorizontal(-1, modifiers);
SelectionEnd = CaretIndex;
}
private void SetSelectionForControlDelete(InputModifiers modifiers)
{
SelectionStart = CaretIndex;
MoveHorizontal(1, modifiers);
SelectionEnd = CaretIndex;
}
UndoRedoState UndoRedoHelper<UndoRedoState>.IUndoRedoHost.UndoRedoState
{
get { return new UndoRedoState(Text, CaretIndex); }
set
{
Text = value.Text;
SelectionStart = SelectionEnd = CaretIndex = value.CaretPosition;
}
}
}
}
| |
using System;
using System.Xml.Schema;
namespace XsdDocumentation.Model
{
internal abstract class XmlSchemaSetVisitor
{
#region Traversing
public void Traverse(XmlSchemaSet schemaSet)
{
Visit(schemaSet);
}
public void Traverse(XmlSchemaObject obj)
{
if (obj != null)
Visit(obj);
}
public void Traverse(XmlSchemaObjectCollection objects)
{
foreach (var obj in objects)
Traverse(obj);
}
#endregion
#region Root
protected virtual void Visit(XmlSchemaSet schemaSet)
{
foreach (var schema in schemaSet.GetAllSchemas())
Traverse(schema);
}
protected virtual void Visit(XmlSchemaObject obj)
{
XmlSchema schema;
XmlSchemaAnnotated annotated;
XmlSchemaAnnotation annotation;
XmlSchemaAppInfo appInfo;
XmlSchemaDocumentation documentation;
XmlSchemaExternal external;
if (Casting.TryCast(obj, out schema))
Visit(schema);
else if (Casting.TryCast(obj, out annotated))
Visit(annotated);
else if (Casting.TryCast(obj, out annotation))
Visit(annotation);
else if (Casting.TryCast(obj, out appInfo))
Visit(appInfo);
else if (Casting.TryCast(obj, out documentation))
Visit(documentation);
else if (Casting.TryCast(obj, out external))
Visit(external);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(obj);
}
#endregion
#region XmlSchemaObject
protected virtual void Visit(XmlSchema schema)
{
foreach (var item in schema.Items)
Traverse(item);
}
protected virtual void Visit(XmlSchemaAnnotated annotated)
{
XmlSchemaAnyAttribute anyAttribute;
XmlSchemaAttribute attribute;
XmlSchemaAttributeGroup attributeGroup;
XmlSchemaAttributeGroupRef attributeGroupRef;
XmlSchemaContent content;
XmlSchemaContentModel contentModel;
XmlSchemaFacet facet;
XmlSchemaGroup group;
XmlSchemaIdentityConstraint constraint;
XmlSchemaNotation notation;
XmlSchemaParticle particle;
XmlSchemaSimpleTypeContent schemaSimpleTypeContent;
XmlSchemaType type;
XmlSchemaXPath xPath;
if (Casting.TryCast(annotated, out anyAttribute))
Visit(anyAttribute);
else if (Casting.TryCast(annotated, out attribute))
Visit(attribute);
else if (Casting.TryCast(annotated, out attributeGroup))
Visit(attributeGroup);
else if (Casting.TryCast(annotated, out attributeGroupRef))
Visit(attributeGroupRef);
else if (Casting.TryCast(annotated, out content))
Visit(content);
else if (Casting.TryCast(annotated, out contentModel))
Visit(contentModel);
else if (Casting.TryCast(annotated, out facet))
Visit(facet);
else if (Casting.TryCast(annotated, out group))
Visit(group);
else if (Casting.TryCast(annotated, out constraint))
Visit(constraint);
else if (Casting.TryCast(annotated, out notation))
Visit(notation);
else if (Casting.TryCast(annotated, out particle))
Visit(particle);
else if (Casting.TryCast(annotated, out schemaSimpleTypeContent))
Visit(schemaSimpleTypeContent);
else if (Casting.TryCast(annotated, out type))
Visit(type);
else if (Casting.TryCast(annotated, out xPath))
Visit(xPath);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(annotated);
}
protected virtual void Visit(XmlSchemaAnnotation annotation)
{
Traverse(annotation.Items);
}
protected virtual void Visit(XmlSchemaAppInfo appInfo)
{
}
protected virtual void Visit(XmlSchemaDocumentation documentation)
{
}
protected virtual void Visit(XmlSchemaExternal external)
{
XmlSchemaImport import;
XmlSchemaInclude include;
XmlSchemaRedefine redefine;
if (Casting.TryCast(external, out import))
Visit(import);
else if (Casting.TryCast(external, out include))
Visit(include);
else if (Casting.TryCast(external, out redefine))
Visit(redefine);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(external);
}
#endregion
#region XmlSchemaAnnotated
protected virtual void Visit(XmlSchemaAnyAttribute attribute)
{
}
protected virtual void Visit(XmlSchemaAttribute attribute)
{
if (attribute.RefName.IsEmpty && attribute.Use != XmlSchemaUse.Prohibited)
Traverse(attribute.AttributeSchemaType);
}
protected virtual void Visit(XmlSchemaAttributeGroup group)
{
Traverse(group.Attributes);
if (group.AnyAttribute != null)
Traverse(group.AnyAttribute);
}
protected virtual void Visit(XmlSchemaAttributeGroupRef groupRef)
{
}
protected virtual void Visit(XmlSchemaContent content)
{
XmlSchemaSimpleContentExtension simpleContentExtension;
XmlSchemaSimpleContentRestriction simpleContentRestriction;
XmlSchemaComplexContentExtension complexContentExtension;
XmlSchemaComplexContentRestriction complexContentRestriction;
if (Casting.TryCast(content, out simpleContentExtension))
Visit(simpleContentExtension);
else if (Casting.TryCast(content, out simpleContentRestriction))
Visit(simpleContentRestriction);
else if (Casting.TryCast(content, out complexContentExtension))
Visit(complexContentExtension);
else if (Casting.TryCast(content, out complexContentRestriction))
Visit(complexContentRestriction);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(content);
}
protected virtual void Visit(XmlSchemaContentModel model)
{
XmlSchemaSimpleContent simpleContent;
XmlSchemaComplexContent complexContent;
if (Casting.TryCast(model, out simpleContent))
Visit(simpleContent);
else if (Casting.TryCast(model, out complexContent))
Visit(complexContent);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(model);
}
protected virtual void Visit(XmlSchemaFacet facet)
{
XmlSchemaEnumerationFacet enumerationFacet;
XmlSchemaMaxExclusiveFacet maxExclusiveFacet;
XmlSchemaMaxInclusiveFacet maxInclusiveFacet;
XmlSchemaMinExclusiveFacet minExclusiveFacet;
XmlSchemaMinInclusiveFacet minInclusiveFacet;
XmlSchemaNumericFacet numericFacet;
XmlSchemaPatternFacet patternFacet;
XmlSchemaWhiteSpaceFacet whiteSpaceFacet;
if (Casting.TryCast(facet, out enumerationFacet))
Visit(enumerationFacet);
else if (Casting.TryCast(facet, out maxExclusiveFacet))
Visit(maxExclusiveFacet);
else if (Casting.TryCast(facet, out maxInclusiveFacet))
Visit(maxInclusiveFacet);
else if (Casting.TryCast(facet, out minExclusiveFacet))
Visit(minExclusiveFacet);
else if (Casting.TryCast(facet, out minInclusiveFacet))
Visit(minInclusiveFacet);
else if (Casting.TryCast(facet, out numericFacet))
Visit(numericFacet);
else if (Casting.TryCast(facet, out patternFacet))
Visit(patternFacet);
else if (Casting.TryCast(facet, out whiteSpaceFacet))
Visit(whiteSpaceFacet);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(facet);
}
protected virtual void Visit(XmlSchemaGroup group)
{
Traverse(group.Particle);
}
protected virtual void Visit(XmlSchemaIdentityConstraint constraint)
{
XmlSchemaKey key;
XmlSchemaKeyref keyref;
XmlSchemaUnique unique;
if (Casting.TryCast(constraint, out key))
Visit(key);
else if (Casting.TryCast(constraint, out keyref))
Visit(keyref);
else if (Casting.TryCast(constraint, out unique))
Visit(unique);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(constraint);
}
protected virtual void Visit(XmlSchemaNotation notation)
{
}
protected virtual void Visit(XmlSchemaParticle particle)
{
XmlSchemaAny any;
XmlSchemaGroupBase groupBase;
XmlSchemaElement element;
XmlSchemaGroupRef groupRef;
if (Casting.TryCast(particle, out any))
Visit(any);
else if (Casting.TryCast(particle, out groupBase))
Visit(groupBase);
else if (Casting.TryCast(particle, out element))
Visit(element);
else if (Casting.TryCast(particle, out groupRef))
Visit(groupRef);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(particle);
}
protected virtual void Visit(XmlSchemaSimpleTypeContent simpleTypeContent)
{
XmlSchemaSimpleTypeList list;
XmlSchemaSimpleTypeRestriction restriction;
XmlSchemaSimpleTypeUnion union;
if (Casting.TryCast(simpleTypeContent, out list))
Visit(list);
else if (Casting.TryCast(simpleTypeContent, out restriction))
Visit(restriction);
else if (Casting.TryCast(simpleTypeContent, out union))
Visit(union);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(simpleTypeContent);
}
protected virtual void Visit(XmlSchemaType type)
{
XmlSchemaComplexType complexType;
XmlSchemaSimpleType simpleType;
if (Casting.TryCast(type, out complexType))
Visit(complexType);
else if (Casting.TryCast(type, out simpleType))
Visit(simpleType);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(type);
}
protected virtual void Visit(XmlSchemaXPath xPath)
{
}
#endregion
#region XmlSchemaContent
protected virtual void Visit(XmlSchemaComplexContentExtension extension)
{
if (extension.Particle != null)
Traverse(extension.Particle);
Traverse(extension.Attributes);
if (extension.AnyAttribute != null)
Traverse(extension.AnyAttribute);
}
protected virtual void Visit(XmlSchemaComplexContentRestriction restriction)
{
if (restriction.Particle != null)
Traverse(restriction.Particle);
Traverse(restriction.Attributes);
if (restriction.AnyAttribute != null)
Traverse(restriction.AnyAttribute);
}
protected virtual void Visit(XmlSchemaSimpleContentExtension extension)
{
Traverse(extension.Attributes);
if (extension.AnyAttribute != null)
Traverse(extension.AnyAttribute);
}
protected virtual void Visit(XmlSchemaSimpleContentRestriction restriction)
{
Traverse(restriction.Facets);
Traverse(restriction.Attributes);
if (restriction.AnyAttribute != null)
Traverse(restriction.AnyAttribute);
}
#endregion
#region XmlSchemaContentModel
protected virtual void Visit(XmlSchemaComplexContent content)
{
Traverse(content.Content);
}
protected virtual void Visit(XmlSchemaSimpleContent content)
{
Traverse(content.Content);
}
#endregion
#region XmlSchemaFacet
protected virtual void Visit(XmlSchemaEnumerationFacet facet)
{
}
protected virtual void Visit(XmlSchemaMaxExclusiveFacet facet)
{
}
protected virtual void Visit(XmlSchemaMaxInclusiveFacet facet)
{
}
protected virtual void Visit(XmlSchemaMinExclusiveFacet facet)
{
}
protected virtual void Visit(XmlSchemaMinInclusiveFacet facet)
{
}
protected virtual void Visit(XmlSchemaNumericFacet facet)
{
XmlSchemaFractionDigitsFacet digitsFacet;
XmlSchemaLengthFacet lengthFacet;
XmlSchemaMaxLengthFacet maxLengthFacet;
XmlSchemaMinLengthFacet minLengthFacet;
XmlSchemaTotalDigitsFacet totalDigitsFacet;
if (Casting.TryCast(facet, out digitsFacet))
Visit(digitsFacet);
else if (Casting.TryCast(facet, out lengthFacet))
Visit(lengthFacet);
else if (Casting.TryCast(facet, out maxLengthFacet))
Visit(maxLengthFacet);
else if (Casting.TryCast(facet, out minLengthFacet))
Visit(minLengthFacet);
else if (Casting.TryCast(facet, out totalDigitsFacet))
Visit(totalDigitsFacet);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(facet);
}
protected virtual void Visit(XmlSchemaPatternFacet facet)
{
}
protected virtual void Visit(XmlSchemaWhiteSpaceFacet facet)
{
}
#endregion
#region XmlSchemaNumericFacet
protected virtual void Visit(XmlSchemaFractionDigitsFacet facet)
{
}
protected virtual void Visit(XmlSchemaLengthFacet facet)
{
}
protected virtual void Visit(XmlSchemaMaxLengthFacet facet)
{
}
protected virtual void Visit(XmlSchemaMinLengthFacet facet)
{
}
protected virtual void Visit(XmlSchemaTotalDigitsFacet facet)
{
}
#endregion
#region XmlSchemaIdentityConstraint
protected virtual void Visit(XmlSchemaKey key)
{
Traverse(key.Selector);
Traverse(key.Fields);
}
protected virtual void Visit(XmlSchemaKeyref keyref)
{
Traverse(keyref.Selector);
Traverse(keyref.Fields);
}
protected virtual void Visit(XmlSchemaUnique unique)
{
Traverse(unique.Selector);
Traverse(unique.Fields);
}
#endregion
#region XmlSchemaParticle
protected virtual void Visit(XmlSchemaAny particle)
{
}
protected virtual void Visit(XmlSchemaElement element)
{
if (!element.RefName.IsEmpty || element.MaxOccurs == 0)
return;
Traverse(element.ElementSchemaType);
foreach (XmlSchemaIdentityConstraint constraint in element.Constraints)
Traverse(constraint);
}
protected virtual void Visit(XmlSchemaGroupBase particle)
{
XmlSchemaAll all;
XmlSchemaChoice choice;
XmlSchemaSequence sequence;
if (Casting.TryCast(particle, out all))
Visit(all);
else if (Casting.TryCast(particle, out choice))
Visit(choice);
else if (Casting.TryCast(particle, out sequence))
Visit(sequence);
else
throw ExceptionBuilder.UnexpectedSchemaObjectType(particle);
}
protected virtual void Visit(XmlSchemaGroupRef groupRef)
{
}
#endregion
#region XmlSchemaGroupBase
protected virtual void Visit(XmlSchemaAll particle)
{
if (particle.MaxOccurs > 0)
Traverse(particle.Items);
}
protected virtual void Visit(XmlSchemaChoice particle)
{
if (particle.MaxOccurs > 0)
Traverse(particle.Items);
}
protected virtual void Visit(XmlSchemaSequence particle)
{
if (particle.MaxOccurs > 0)
Traverse(particle.Items);
}
#endregion
#region XmlSchemaSimpleTypeContent
protected virtual void Visit(XmlSchemaSimpleTypeList list)
{
Traverse(list.BaseItemType);
}
protected virtual void Visit(XmlSchemaSimpleTypeRestriction restriction)
{
if (restriction.BaseType != null)
Traverse(restriction.BaseType);
Traverse(restriction.Facets);
}
protected virtual void Visit(XmlSchemaSimpleTypeUnion union)
{
foreach (var simpleType in union.BaseMemberTypes)
Traverse(simpleType);
}
#endregion
#region XmlSchemaType
protected virtual void Visit(XmlSchemaComplexType type)
{
if (type.ContentModel != null)
{
Traverse(type.ContentModel);
}
else
{
if (type.Particle != null)
Traverse(type.Particle);
Traverse(type.Attributes);
if (type.AnyAttribute != null)
Traverse(type.AnyAttribute);
}
}
protected virtual void Visit(XmlSchemaSimpleType type)
{
if (type.Content != null)
Traverse(type.Content);
}
#endregion
#region XmlSchemaExternal
protected virtual void Visit(XmlSchemaImport import)
{
}
protected virtual void Visit(XmlSchemaInclude include)
{
}
protected virtual void Visit(XmlSchemaRedefine redefine)
{
}
#endregion
}
}
| |
// Copyright Bastian Eicher
// Licensed under the MIT License
using System.Runtime.InteropServices;
using System.Runtime.Versioning;
using System.Security.Principal;
using System.Text;
namespace NanoByte.Common.Native;
/// <summary>
/// Provides helper methods and API calls specific to the Windows platform.
/// </summary>
[SupportedOSPlatform("windows")]
public static partial class WindowsUtils
{
#region Win32 Error Codes
/// <summary>
/// The <see cref="Win32Exception.NativeErrorCode"/> value indicating that a file was not found.
/// </summary>
internal const int Win32ErrorFileNotFound = 2;
/// <summary>
/// The <see cref="Win32Exception.NativeErrorCode"/> value indicating that access to a resource was denied.
/// </summary>
internal const int Win32ErrorAccessDenied = 5;
/// <summary>
/// The <see cref="Win32Exception.NativeErrorCode"/> value indicating that write access to a resource failed.
/// </summary>
internal const int Win32ErrorWriteFault = 29;
/// <summary>
/// The <see cref="Win32Exception.NativeErrorCode"/> value indicating that an operation timed out.
/// </summary>
internal const int Win32ErrorSemTimeout = 121;
/// <summary>
/// The <see cref="Win32Exception.NativeErrorCode"/> value indicating that an element (e.g. a file) already exists.
/// </summary>
internal const int Win32ErrorAlreadyExists = 183;
/// <summary>
/// The <see cref="Win32Exception.NativeErrorCode"/> value indicating that more data is available and the query should be repeated with a larger output buffer/array.
/// </summary>
internal const int Win32ErrorMoreData = 234;
/// <summary>
/// The <see cref="Win32Exception.NativeErrorCode"/> value indicating that the requested application needs UAC elevation.
/// </summary>
[SupportedOSPlatformGuard("windows")]
internal const int Win32ErrorRequestedOperationRequiresElevation = 740;
/// <summary>
/// The <see cref="Win32Exception.NativeErrorCode"/> value indicating that an operation was cancelled by the user.
/// </summary>
[SupportedOSPlatformGuard("windows")]
[SuppressMessage("Microsoft.Naming", "CA1726:UsePreferredTerms", MessageId = "Cancelled", Justification = "Naming matches the Win32 docs")]
internal const int Win32ErrorCancelled = 1223;
/// <summary>
/// The file or directory is not a reparse point.
/// </summary>
internal const int Win32ErrorNotAReparsePoint = 4390;
/// <summary>
/// Builds a suitable <see cref="Exception"/> for a given <see cref="Win32Exception.NativeErrorCode"/>.
/// </summary>
internal static Exception BuildException(int error)
{
var ex = new Win32Exception(error);
return error switch
{
Win32ErrorAlreadyExists => new IOException(ex.Message, ex),
Win32ErrorWriteFault => new IOException(ex.Message, ex),
Win32ErrorFileNotFound => new FileNotFoundException(ex.Message, ex),
Win32ErrorAccessDenied => new UnauthorizedAccessException(ex.Message, ex),
Win32ErrorRequestedOperationRequiresElevation => new NotAdminException(ex.Message, ex),
Win32ErrorSemTimeout => new TimeoutException(),
Win32ErrorCancelled => new OperationCanceledException(),
_ => ex
};
}
#endregion
#region OS
/// <summary>
/// <c>true</c> if the current operating system is Windows (9x- or NT-based); <c>false</c> otherwise.
/// </summary>
[SupportedOSPlatformGuard("windows")]
public static bool IsWindows
#if NET
=> OperatingSystem.IsWindows();
#elif NET20 || NET40
=> Environment.OSVersion.Platform is PlatformID.Win32Windows or PlatformID.Win32NT;
#else
=> RuntimeInformation.IsOSPlatform(OSPlatform.Windows);
#endif
/// <summary>
/// <c>true</c> if the current operating system is a modern Windows version (NT-based); <c>false</c> otherwise.
/// </summary>
[SupportedOSPlatformGuard("windows")]
public static bool IsWindowsNT
#if NET20 || NET40
=> Environment.OSVersion.Platform is PlatformID.Win32NT;
#else
=> IsWindows;
#endif
[SupportedOSPlatformGuard("windows")]
private static bool IsWindowsNTVersion(Version version)
#if NET
=> OperatingSystem.IsWindowsVersionAtLeast(version.Major, version.Minor, version.Build, version.Revision);
#else
=> IsWindowsNT && Environment.OSVersion.Version >= version;
#endif
/// <summary>
/// <c>true</c> if the current operating system is Windows XP or newer; <c>false</c> otherwise.
/// </summary>
[SupportedOSPlatformGuard("windows5.1")]
public static bool IsWindowsXP => IsWindowsNTVersion(new(5, 1));
/// <summary>
/// <c>true</c> if the current operating system is Windows Vista or newer; <c>false</c> otherwise.
/// </summary>
[SupportedOSPlatformGuard("windows6.0")]
public static bool IsWindowsVista => IsWindowsNTVersion(new(6, 0));
/// <summary>
/// <c>true</c> if the current operating system is Windows 7 or newer; <c>false</c> otherwise.
/// </summary>
[SupportedOSPlatformGuard("windows6.1")]
public static bool IsWindows7 => IsWindowsNTVersion(new(6, 1));
/// <summary>
/// <c>true</c> if the current operating system is Windows 8 or newer; <c>false</c> otherwise.
/// </summary>
[SupportedOSPlatformGuard("windows6.2")]
public static bool IsWindows8 => IsWindowsNTVersion(new(6, 2));
/// <summary>
/// <c>true</c> if the current operating system is Windows 10 or newer; <c>false</c> otherwise.
/// </summary>
[SupportedOSPlatformGuard("windows10.0")]
public static bool IsWindows10 => IsWindowsNTVersion(new(10, 0));
/// <summary>
/// <c>true</c> if the current operating system is Windows 10 Anniversary Update (Redstone 1) or newer; <c>false</c> otherwise.
/// </summary>
[SupportedOSPlatformGuard("windows10.0.14393")]
public static bool IsWindows10Redstone => IsWindowsNTVersion(new(10, 0, 14393));
/// <summary>
/// <c>true</c> if the current operating system is Windows 11 or newer; <c>false</c> otherwise.
/// </summary>
[SupportedOSPlatformGuard("windows10.0.22000")]
public static bool IsWindows11 => IsWindowsNTVersion(new(10, 0, 22000));
/// <summary>
/// <c>true</c> if the current operating system supports UAC and it is enabled; <c>false</c> otherwise.
/// </summary>
[SupportedOSPlatformGuard("windows6.0")]
public static bool HasUac => IsWindowsVista && RegistryUtils.GetDword(@"HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Policies\System", "EnableLUA", defaultValue: 1) == 1;
/// <summary>
/// Indicates whether the current user is an administrator. Always returns <c>true</c> on non-Windows NT systems.
/// </summary>
public static bool IsAdministrator
{
get
{
if (!IsWindowsNT) return true;
try
{
return new WindowsPrincipal(WindowsIdentity.GetCurrent()).IsInRole(WindowsBuiltInRole.Administrator);
}
catch
{
return false;
}
}
}
/// <summary>
/// Indicates whether the current process is running in a GUI session (rather than, e.g., as a service or in an SSH session).
/// Always <c>false</c> on non-Windows systems.
/// </summary>
[SupportedOSPlatformGuard("windows")]
public static bool IsGuiSession { get; } = IsWindows && DetectGuiSession();
private static bool DetectGuiSession()
{
try
{
return new WindowsPrincipal(WindowsIdentity.GetCurrent())
.IsInRole(new SecurityIdentifier(WellKnownSidType.InteractiveSid, null));
}
catch
{
return true;
}
}
/// <summary>
/// Determines the path of the executable the current process was launched from.
/// </summary>
public static string CurrentProcessPath
{
get
{
var fileName = new StringBuilder(255);
SafeNativeMethods.GetModuleFileName(IntPtr.Zero, fileName, fileName.Capacity);
return fileName.ToString();
}
}
#endregion
#region .NET Framework
/// <summary>The directory version number for .NET Framework 2.0. This release includes the C# 2.0 compiler and the CLR 2.0 runtime.</summary>
public const string NetFx20 = "v2.0.50727";
/// <summary>The directory version number for .NET Framework 3.0.</summary>
public const string NetFx30 = "v3.0";
/// <summary>The directory version number for .NET Framework 3.5. This release includes the C# 3.0 compiler.</summary>
public const string NetFx35 = "v3.5";
/// <summary>The directory version number for .NET Framework 4.x. This release includes a C# 4.0+ compiler and the CLR 4.0 runtime.</summary>
public const string NetFx40 = "v4.0.30319";
/// <summary>
/// Returns the .NET Framework root directory for a specific version of the .NET Framework. Does not verify the directory actually exists!
/// </summary>
/// <param name="version">The full .NET version number including the leading "v". Use predefined constants when possible.</param>
/// <returns>The path to the .NET Framework root directory.</returns>
/// <remarks>Returns 64-bit directories if on 64-bit Windows is <c>true</c>.</remarks>
public static string GetNetFxDirectory(string version)
{
#region Sanity checks
if (string.IsNullOrEmpty(version)) throw new ArgumentNullException(nameof(version));
#endregion
string microsoftDotNetDir = Path.Combine(
Environment.GetEnvironmentVariable("windir") ?? @"C:\Windows",
"Microsoft.NET");
string framework32Dir = Path.Combine(microsoftDotNetDir, "Framework");
string framework64Dir = Path.Combine(microsoftDotNetDir, "Framework64");
return Path.Combine(
Directory.Exists(framework64Dir) ? framework64Dir : framework32Dir,
version);
}
#endregion
#region Command-line
/// <summary>
/// Tries to split a command-line into individual arguments.
/// </summary>
/// <param name="commandLine">The command-line to be split.</param>
/// <returns>
/// An array of individual arguments.
/// Will return the entire command-line as one argument when not running on Windows or if splitting failed for some other reason.
/// </returns>
public static string[] SplitArgs(string? commandLine)
{
if (string.IsNullOrEmpty(commandLine)) return new string[0];
if (!IsWindows) return new[] {commandLine};
var ptrToSplitArgs = SafeNativeMethods.CommandLineToArgvW(commandLine, out int numberOfArgs);
if (ptrToSplitArgs == IntPtr.Zero) return new[] {commandLine};
try
{
// Copy result to managed array
var splitArgs = new string[numberOfArgs];
for (int i = 0; i < numberOfArgs; i++)
splitArgs[i] = Marshal.PtrToStringUni(Marshal.ReadIntPtr(ptrToSplitArgs, i * IntPtr.Size))!;
return splitArgs;
}
finally
{
NativeMethods.LocalFree(ptrToSplitArgs);
}
}
/// <summary>
/// Tries to attach to a command-line console owned by the parent process.
/// </summary>
/// <returns><c>true</c> if the console was successfully attached; <c>false</c> if the parent process did not own a console.</returns>
public static bool AttachConsole() => IsWindowsNT && NativeMethods.AttachConsole(uint.MaxValue);
#endregion
#region Performance counter
private static long _performanceFrequency;
/// <summary>
/// A time index in seconds that continuously increases.
/// </summary>
/// <remarks>Depending on the operating system this may be the time of the system clock or the time since the system booted.</remarks>
public static double AbsoluteTime
{
get
{
if (IsWindowsNT)
{
if (_performanceFrequency == 0)
SafeNativeMethods.QueryPerformanceFrequency(out _performanceFrequency);
SafeNativeMethods.QueryPerformanceCounter(out long time);
return time / (double)_performanceFrequency;
}
else return Environment.TickCount / 1000f;
}
}
#endregion
#region File system
/// <summary>
/// Reads the entire contents of a file using the Win32 API.
/// </summary>
/// <param name="path">The path of the file to read.</param>
/// <returns>The contents of the file as a byte array; <c>null</c> if there was a problem reading the file.</returns>
/// <exception cref="PlatformNotSupportedException">This method is called on a platform other than Windows.</exception>
/// <remarks>This method works like <see cref="File.ReadAllBytes"/>, but bypasses .NET's file path validation logic.</remarks>
public static byte[]? ReadAllBytes([Localizable(false)] string path)
{
#region Sanity checks
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path));
#endregion
if (!IsWindows) throw new PlatformNotSupportedException(Resources.OnlyAvailableOnWindows);
using var handle = NativeMethods.CreateFile(path, FileAccess.Read, FileShare.Read, IntPtr.Zero, FileMode.Open, FileAttributes.Normal, IntPtr.Zero);
if (handle.IsInvalid) return null;
uint size = NativeMethods.GetFileSize(handle, IntPtr.Zero);
byte[] buffer = new byte[size];
uint read = uint.MinValue;
var lpOverlapped = new NativeOverlapped();
return NativeMethods.ReadFile(handle, buffer, size, ref read, ref lpOverlapped) ? buffer : null;
}
/// <summary>
/// Writes the entire contents of a byte array to a file using the Win32 API. Existing files with the same name are overwritten.
/// </summary>
/// <param name="path">The path of the file to write to.</param>
/// <param name="data">The data to write to the file.</param>
/// <exception cref="IOException">There was an IO problem writing the file.</exception>
/// <exception cref="UnauthorizedAccessException">Write access to the file was denied.</exception>
/// <exception cref="Win32Exception">There was a problem writing the file.</exception>
/// <exception cref="PlatformNotSupportedException">This method is called on a platform other than Windows.</exception>
/// <remarks>This method works like <see cref="File.WriteAllBytes"/>, but bypasses .NET's file path validation logic.</remarks>
public static void WriteAllBytes([Localizable(false)] string path, byte[] data)
{
#region Sanity checks
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path));
if (data == null) throw new ArgumentNullException(nameof(data));
#endregion
if (!IsWindows) throw new PlatformNotSupportedException(Resources.OnlyAvailableOnWindows);
using var handle = NativeMethods.CreateFile(path, FileAccess.Write, FileShare.Write, IntPtr.Zero, FileMode.Create, 0, IntPtr.Zero);
if (handle.IsInvalid) throw BuildException(Marshal.GetLastWin32Error());
uint bytesWritten = 0;
var lpOverlapped = new NativeOverlapped();
if (!NativeMethods.WriteFile(handle, data, (uint)data.Length, ref bytesWritten, ref lpOverlapped))
throw BuildException(Marshal.GetLastWin32Error());
}
/// <summary>
/// Creates a symbolic link for a file or directory.
/// </summary>
/// <param name="sourcePath">The path of the link to create.</param>
/// <param name="targetPath">The path of the existing file or directory to point to (relative to <paramref name="sourcePath"/>).</param>
/// <exception cref="IOException">There was an IO problem creating the symlink.</exception>
/// <exception cref="UnauthorizedAccessException">You have insufficient rights to create the symbolic link.</exception>
/// <exception cref="Win32Exception">The symbolic link creation failed.</exception>
/// <exception cref="PlatformNotSupportedException">This method is called on a platform other than Windows NT 6.0 (Vista) or newer.</exception>
public static void CreateSymlink([Localizable(false)] string sourcePath, [Localizable(false)] string targetPath)
{
#region Sanity checks
if (string.IsNullOrEmpty(sourcePath)) throw new ArgumentNullException(nameof(sourcePath));
if (string.IsNullOrEmpty(targetPath)) throw new ArgumentNullException(nameof(targetPath));
#endregion
if (!IsWindowsVista) throw new PlatformNotSupportedException(Resources.OnlyAvailableOnWindows);
var flags = IsWindows10Redstone
? NativeMethods.CreateSymbolicLinkFlags.SYMBOLIC_LINK_FLAG_ALLOW_UNPRIVILEGED_CREATE
: NativeMethods.CreateSymbolicLinkFlags.NONE;
if (Directory.Exists(Path.Combine(Path.GetDirectoryName(sourcePath) ?? Directory.GetCurrentDirectory(), targetPath)))
flags |= NativeMethods.CreateSymbolicLinkFlags.SYMBOLIC_LINK_FLAG_DIRECTORY;
if (!NativeMethods.CreateSymbolicLink(sourcePath, targetPath, flags))
throw BuildException(Marshal.GetLastWin32Error());
}
/// <summary>
/// Checks whether a file is an NTFS symbolic link.
/// </summary>
/// <param name="path">The path of the file to check.</param>
/// <returns><c>true</c> if <paramref name="path"/> points to a symbolic link; <c>false</c> otherwise.</returns>
/// <remarks>Will return <c>false</c> for non-existing files.</remarks>
/// <exception cref="IOException">There was an IO problem getting link information.</exception>
/// <exception cref="UnauthorizedAccessException">You have insufficient rights to get link information.</exception>
/// <exception cref="Win32Exception">Getting link information failed.</exception>
/// <exception cref="PlatformNotSupportedException">This method is called on a platform other than Windows NT 6.0 (Vista) or newer.</exception>
public static bool IsSymlink([Localizable(false)] string path)
=> IsSymlink(path, out _);
/// <summary>
/// Checks whether a file is an NTFS symbolic link.
/// </summary>
/// <param name="path">The path of the file to check.</param>
/// <param name="target">Returns the target the symbolic link points to if it exists.</param>
/// <returns><c>true</c> if <paramref name="path"/> points to a symbolic link; <c>false</c> otherwise.</returns>
/// <exception cref="IOException">There was an IO problem getting link information.</exception>
/// <exception cref="UnauthorizedAccessException">You have insufficient rights to get link information.</exception>
/// <exception cref="Win32Exception">Getting link information failed.</exception>
/// <exception cref="PlatformNotSupportedException">This method is called on a platform other than Windows NT 6.0 (Vista) or newer.</exception>
[SupportedOSPlatformGuard("windows6.0")]
public static bool IsSymlink(
[Localizable(false)] string path,
[MaybeNullWhen(false)] out string target)
{
#region Sanity checks
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path));
#endregion
if (!IsWindowsVista) throw new PlatformNotSupportedException(Resources.OnlyAvailableOnWindows);
using var handle = NativeMethods.CreateFile(Path.GetFullPath(path), 0, 0, IntPtr.Zero, FileMode.Open, NativeMethods.FILE_FLAG_OPEN_REPARSE_POINT | NativeMethods.FILE_FLAG_BACKUP_SEMANTICS, IntPtr.Zero);
if (handle.IsInvalid) throw BuildException(Marshal.GetLastWin32Error());
if (!NativeMethods.DeviceIoControl(handle, NativeMethods.FSCTL_GET_REPARSE_POINT, IntPtr.Zero, 0, out var buffer, Marshal.SizeOf(typeof(NativeMethods.REPARSE_DATA_BUFFER)), out _, IntPtr.Zero))
{
int error = Marshal.GetLastWin32Error();
if (error == Win32ErrorNotAReparsePoint)
{
target = null;
return false;
}
else throw BuildException(error);
}
if (buffer.ReparseTag != NativeMethods.IO_REPARSE_TAG_SYMLINK)
{
target = null;
return false;
}
target = new string(buffer.PathBuffer, buffer.SubstituteNameOffset / 2, buffer.SubstituteNameLength / 2);
return true;
}
/// <summary>
/// Creates a hard link between two files.
/// </summary>
/// <param name="sourcePath">The path of the link to create.</param>
/// <param name="targetPath">The absolute path of the existing file to point to.</param>
/// <remarks>Only available on Windows 2000 or newer.</remarks>
/// <exception cref="IOException">There was an IO problem creating the hard link.</exception>
/// <exception cref="UnauthorizedAccessException">You have insufficient rights to create the hard link.</exception>
/// <exception cref="Win32Exception">The hard link creation failed.</exception>
/// <exception cref="PlatformNotSupportedException">This method is called on a platform other than Windows NT.</exception>
public static void CreateHardlink([Localizable(false)] string sourcePath, [Localizable(false)] string targetPath)
{
#region Sanity checks
if (string.IsNullOrEmpty(sourcePath)) throw new ArgumentNullException(nameof(sourcePath));
if (string.IsNullOrEmpty(targetPath)) throw new ArgumentNullException(nameof(targetPath));
#endregion
if (!IsWindowsNT) throw new PlatformNotSupportedException(Resources.OnlyAvailableOnWindows);
if (!NativeMethods.CreateHardLink(sourcePath, targetPath, IntPtr.Zero))
throw BuildException(Marshal.GetLastWin32Error());
}
/// <summary>
/// Returns the file ID of a file.
/// </summary>
/// <param name="path">The path of the file.</param>
/// <exception cref="IOException">There was an IO problem checking the file.</exception>
/// <exception cref="UnauthorizedAccessException">You have insufficient rights to check the files.</exception>
/// <exception cref="Win32Exception">Checking the file failed.</exception>
/// <exception cref="PlatformNotSupportedException">This method is called on a platform other than Windows NT.</exception>
public static long GetFileID([Localizable(false)] string path)
{
#region Sanity checks
if (string.IsNullOrEmpty(path)) throw new ArgumentNullException(nameof(path));
#endregion
using var handle = NativeMethods.CreateFile(
path ?? throw new ArgumentNullException(nameof(path)),
FileAccess.Read, FileShare.Read, IntPtr.Zero, FileMode.Open, FileAttributes.Archive, IntPtr.Zero);
if (handle.IsInvalid) throw BuildException(Marshal.GetLastWin32Error());
if (!NativeMethods.GetFileInformationByHandle(handle, out var fileInfo))
throw BuildException(Marshal.GetLastWin32Error());
if (fileInfo.FileIndexLow is 0 or uint.MaxValue && fileInfo.FileIndexHigh is 0 or uint.MaxValue)
throw new IOException($"The file system cannot provide a unique ID for '{path}'.");
unchecked
{
return fileInfo.FileIndexLow + ((long)fileInfo.FileIndexHigh << 32);
}
}
/// <summary>
/// Moves a file on the next reboot of the OS. Replaces existing files.
/// </summary>
/// <param name="sourcePath">The source path to move the file from.</param>
/// <param name="destinationPath">The destination path to move the file to. <c>null</c> to delete the file instead of moving it.</param>
/// <remarks>Useful for replacing in-use files.</remarks>
public static void MoveFileOnReboot(string sourcePath, string? destinationPath)
{
#region Sanity checks
if (string.IsNullOrEmpty(sourcePath)) throw new ArgumentNullException(nameof(sourcePath));
#endregion
if (!NativeMethods.MoveFileEx(sourcePath, destinationPath, NativeMethods.MoveFileFlags.MOVEFILE_REPLACE_EXISTING | NativeMethods.MoveFileFlags.MOVEFILE_DELAY_UNTIL_REBOOT))
throw BuildException(Marshal.GetLastWin32Error());
}
#endregion
#region Shell
/// <summary>
/// Sets the current process' explicit application user model ID.
/// </summary>
/// <param name="appID">The application ID to set.</param>
/// <remarks>The application ID is used to group related windows in the taskbar.</remarks>
[SupportedOSPlatformGuard("windows6.1")]
public static void SetCurrentProcessAppID(string appID)
{
#region Sanity checks
if (string.IsNullOrEmpty(appID)) throw new ArgumentNullException(nameof(appID));
#endregion
if (!IsWindows7) return;
NativeMethods.SetCurrentProcessExplicitAppUserModelID(appID);
}
/// <summary>
/// Informs the Windows shell that changes were made to the file association data in the registry.
/// </summary>
/// <remarks>This should be called immediately after the changes in order to trigger a refresh of the Explorer UI.</remarks>
[SuppressMessage("ReSharper", "InconsistentNaming")]
public static void NotifyAssocChanged()
{
if (!IsWindows) return;
NativeMethods.SHChangeNotify(NativeMethods.SHCNE_ASSOCCHANGED, NativeMethods.SHCNF_IDLIST, IntPtr.Zero, IntPtr.Zero);
}
/// <summary>
/// Informs all GUI applications that changes where made to the environment variables (e.g. PATH) and that they should re-pull them.
/// </summary>
[SuppressMessage("ReSharper", "InconsistentNaming")]
public static void NotifyEnvironmentChanged()
{
if (!IsWindows) return;
NativeMethods.SendMessageTimeout(NativeMethods.HWND_BROADCAST, NativeMethods.WM_SETTINGCHANGE, IntPtr.Zero, "Environment", NativeMethods.SendMessageTimeoutFlags.SMTO_ABORTIFHUNG, 5000, out _);
}
#endregion
#region Window messages
/// <summary>
/// Registers a new message type that can be sent to windows.
/// </summary>
/// <param name="message">A unique string used to identify the message type session-wide.</param>
/// <returns>A unique ID number used to identify the message type session-wide.</returns>
public static int RegisterWindowMessage([Localizable(false)] string message) => IsWindows ? NativeMethods.RegisterWindowMessage(message) : 0;
/// <summary>
/// Sends a message of a specific type to all windows in the current session.
/// </summary>
/// <param name="messageID">A unique ID number used to identify the message type session-wide.</param>
public static void BroadcastMessage(int messageID)
{
if (!IsWindows) return;
NativeMethods.PostMessage(NativeMethods.HWND_BROADCAST, messageID, IntPtr.Zero, IntPtr.Zero);
}
#endregion
#region Restart Manager
/// <summary>
/// Registers the current application for automatic restart after updates or crashes.
/// </summary>
/// <param name="arguments">The command-line arguments to pass to the application on restart. Must not be empty!</param>
public static void RegisterApplicationRestart(string arguments)
{
#region Sanity checks
if (string.IsNullOrEmpty(arguments)) throw new ArgumentNullException(nameof(arguments));
#endregion
if (!IsWindowsVista) return;
int ret = NativeMethods.RegisterApplicationRestart(arguments, NativeMethods.RestartFlags.NONE);
if (ret != 0) Log.Warn("Failed to register application for restart with arguments: " + arguments);
}
/// <summary>
/// Unregisters the current application for automatic restart after updates or crashes.
/// </summary>
public static void UnregisterApplicationRestart()
{
if (!IsWindowsVista) return;
NativeMethods.UnregisterApplicationRestart();
}
#endregion
}
| |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.IO;
using Dbg = System.Management.Automation.Diagnostics;
namespace System.Management.Automation.Remoting
{
///<summary>
/// This is the object used by Runspace,pipeline,host to send data
/// to remote end. Transport layer owns breaking this into fragments
/// and sending to other end
///</summary>
internal class RemoteDataObject<T>
{
#region Private Members
private const int destinationOffset = 0;
private const int dataTypeOffset = 4;
private const int rsPoolIdOffset = 8;
private const int psIdOffset = 24;
private const int headerLength = 4 + 4 + 16 + 16;
private const int SessionMask = 0x00010000;
private const int RunspacePoolMask = 0x00021000;
private const int PowerShellMask = 0x00041000;
#endregion Private Members
#region Constructors
/// <summary>
/// Constructs a RemoteDataObject from its
/// individual components.
/// </summary>
/// <param name="destination">
/// Destination this object is going to.
/// </param>
/// <param name="dataType">
/// Payload type this object represents.
/// </param>
/// <param name="runspacePoolId">
/// Runspace id this object belongs to.
/// </param>
/// <param name="powerShellId">
/// PowerShell (pipeline) id this object belongs to.
/// This may be null if the payload belongs to runspace.
/// </param>
/// <param name="data">
/// Actual payload.
/// </param>
protected RemoteDataObject(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
T data)
{
Destination = destination;
DataType = dataType;
RunspacePoolId = runspacePoolId;
PowerShellId = powerShellId;
Data = data;
}
#endregion Constructors
#region Properties
internal RemotingDestination Destination { get; }
/// <summary>
/// Gets the target (Runspace / Pipeline / Powershell / Host)
/// the payload belongs to.
/// </summary>
internal RemotingTargetInterface TargetInterface
{
get
{
int dt = (int)DataType;
// get the most used ones in the top.
if ((dt & PowerShellMask) == PowerShellMask)
{
return RemotingTargetInterface.PowerShell;
}
if ((dt & RunspacePoolMask) == RunspacePoolMask)
{
return RemotingTargetInterface.RunspacePool;
}
if ((dt & SessionMask) == SessionMask)
{
return RemotingTargetInterface.Session;
}
return RemotingTargetInterface.InvalidTargetInterface;
}
}
internal RemotingDataType DataType { get; }
internal Guid RunspacePoolId { get; }
internal Guid PowerShellId { get; }
internal T Data { get; }
#endregion Properties
/// <summary>
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
/// <returns></returns>
internal static RemoteDataObject<T> CreateFrom(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
T data)
{
return new RemoteDataObject<T>(destination, dataType, runspacePoolId, powerShellId, data);
}
/// <summary>
/// Creates a RemoteDataObject by deserializing <paramref name="data"/>.
/// </summary>
/// <param name="serializedDataStream"></param>
/// <param name="defragmentor">
/// Defragmentor used to deserialize an object.
/// </param>
/// <returns></returns>
internal static RemoteDataObject<T> CreateFrom(Stream serializedDataStream, Fragmentor defragmentor)
{
Dbg.Assert(serializedDataStream != null, "cannot construct a RemoteDataObject from null data");
Dbg.Assert(defragmentor != null, "defragmentor cannot be null.");
if ((serializedDataStream.Length - serializedDataStream.Position) < headerLength)
{
PSRemotingTransportException e =
new PSRemotingTransportException(PSRemotingErrorId.NotEnoughHeaderForRemoteDataObject,
RemotingErrorIdStrings.NotEnoughHeaderForRemoteDataObject,
headerLength + FragmentedRemoteObject.HeaderLength);
throw e;
}
RemotingDestination destination = (RemotingDestination)DeserializeUInt(serializedDataStream);
RemotingDataType dataType = (RemotingDataType)DeserializeUInt(serializedDataStream);
Guid runspacePoolId = DeserializeGuid(serializedDataStream);
Guid powerShellId = DeserializeGuid(serializedDataStream);
object actualData = null;
if ((serializedDataStream.Length - headerLength) > 0)
{
actualData = defragmentor.DeserializeToPSObject(serializedDataStream);
}
T deserializedObject = (T)LanguagePrimitives.ConvertTo(actualData, typeof(T),
System.Globalization.CultureInfo.CurrentCulture);
return new RemoteDataObject<T>(destination, dataType, runspacePoolId, powerShellId, deserializedObject);
}
#region Serialize / Deserialize
/// <summary>
/// Serializes the object into the stream specified. The serialization mechanism uses
/// UTF8 encoding to encode data.
/// </summary>
/// <param name="streamToWriteTo"></param>
/// <param name="fragmentor">
/// fragmentor used to serialize and fragment the object.
/// </param>
internal virtual void Serialize(Stream streamToWriteTo, Fragmentor fragmentor)
{
Dbg.Assert(streamToWriteTo != null, "Stream to write to cannot be null.");
Dbg.Assert(fragmentor != null, "Fragmentor cannot be null.");
SerializeHeader(streamToWriteTo);
if (Data != null)
{
fragmentor.SerializeToBytes(Data, streamToWriteTo);
}
return;
}
/// <summary>
/// Serializes only the header portion of the object. ie., runspaceId,
/// powerShellId, destination and dataType.
/// </summary>
/// <param name="streamToWriteTo">
/// place where the serialized data is stored into.
/// </param>
/// <returns></returns>
private void SerializeHeader(Stream streamToWriteTo)
{
Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null");
// Serialize destination
SerializeUInt((uint)Destination, streamToWriteTo);
// Serialize data type
SerializeUInt((uint)DataType, streamToWriteTo);
// Serialize runspace guid
SerializeGuid(RunspacePoolId, streamToWriteTo);
// Serialize powershell guid
SerializeGuid(PowerShellId, streamToWriteTo);
return;
}
private static void SerializeUInt(uint data, Stream streamToWriteTo)
{
Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null");
byte[] result = new byte[4]; // size of int
int idx = 0;
result[idx++] = (byte)(data & 0xFF);
result[idx++] = (byte)((data >> 8) & 0xFF);
result[idx++] = (byte)((data >> (2 * 8)) & 0xFF);
result[idx++] = (byte)((data >> (3 * 8)) & 0xFF);
streamToWriteTo.Write(result, 0, 4);
}
private static uint DeserializeUInt(Stream serializedDataStream)
{
Dbg.Assert(serializedDataStream.Length >= 4, "Not enough data to get Int.");
uint result = 0;
result |= (((uint)(serializedDataStream.ReadByte())) & 0xFF);
result |= (((uint)(serializedDataStream.ReadByte() << 8)) & 0xFF00);
result |= (((uint)(serializedDataStream.ReadByte() << (2 * 8))) & 0xFF0000);
result |= (((uint)(serializedDataStream.ReadByte() << (3 * 8))) & 0xFF000000);
return result;
}
private static void SerializeGuid(Guid guid, Stream streamToWriteTo)
{
Dbg.Assert(streamToWriteTo != null, "stream to write to cannot be null");
byte[] guidArray = guid.ToByteArray();
streamToWriteTo.Write(guidArray, 0, guidArray.Length);
}
private static Guid DeserializeGuid(Stream serializedDataStream)
{
Dbg.Assert(serializedDataStream.Length >= 16, "Not enough data to get Guid.");
byte[] guidarray = new byte[16]; // Size of GUID.
for (int idx = 0; idx < 16; idx++)
{
guidarray[idx] = (byte)serializedDataStream.ReadByte();
}
return new Guid(guidarray);
}
#endregion
}
internal sealed class RemoteDataObject : RemoteDataObject<object>
{
#region Constructors / Factory
/// <summary>
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
private RemoteDataObject(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
object data) : base(destination, dataType, runspacePoolId, powerShellId, data)
{
}
/// <summary>
/// </summary>
/// <param name="destination"></param>
/// <param name="dataType"></param>
/// <param name="runspacePoolId"></param>
/// <param name="powerShellId"></param>
/// <param name="data"></param>
/// <returns></returns>
internal static new RemoteDataObject CreateFrom(RemotingDestination destination,
RemotingDataType dataType,
Guid runspacePoolId,
Guid powerShellId,
object data)
{
return new RemoteDataObject(destination, dataType, runspacePoolId,
powerShellId, data);
}
#endregion Constructors
}
}
| |
namespace iControl {
using System.Xml.Serialization;
using System.Web.Services;
using System.ComponentModel;
using System.Web.Services.Protocols;
using System;
using System.Diagnostics;
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Web.Services.WebServiceBindingAttribute(Name="LocalLB.PoolMemberBinding", Namespace="urn:iControl")]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberStatistics))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberConnectionLimit))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberDynamicRatio))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberMonitorAssociation))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberMonitorInstanceState))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberMonitorStatus))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberObjectStatus))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberPriority))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberRatio))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberSessionState))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberSessionStatus))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(CommonIPPortDefinition))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberMonitorAssociationRemoval))]
[System.Xml.Serialization.SoapIncludeAttribute(typeof(LocalLBPoolMemberMemberMonitorState))]
public partial class LocalLBPoolMember : iControlInterface {
public LocalLBPoolMember() {
this.Url = "https://url_to_service";
}
//=======================================================================
// Operations
//=======================================================================
//-----------------------------------------------------------------------
// get_all_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberStatistics [] get_all_statistics(
string [] pool_names
) {
object [] results = this.Invoke("get_all_statistics", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberStatistics [])(results[0]));
}
public System.IAsyncResult Beginget_all_statistics(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_all_statistics", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberStatistics [] Endget_all_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberStatistics [])(results[0]));
}
//-----------------------------------------------------------------------
// get_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberConnectionLimit [] [] get_connection_limit(
string [] pool_names
) {
object [] results = this.Invoke("get_connection_limit", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberConnectionLimit [] [])(results[0]));
}
public System.IAsyncResult Beginget_connection_limit(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_connection_limit", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberConnectionLimit [] [] Endget_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberConnectionLimit [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_dynamic_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberDynamicRatio [] [] get_dynamic_ratio(
string [] pool_names
) {
object [] results = this.Invoke("get_dynamic_ratio", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberDynamicRatio [] [])(results[0]));
}
public System.IAsyncResult Beginget_dynamic_ratio(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_dynamic_ratio", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberDynamicRatio [] [] Endget_dynamic_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberDynamicRatio [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_monitor_association
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberMonitorAssociation [] [] get_monitor_association(
string [] pool_names
) {
object [] results = this.Invoke("get_monitor_association", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberMonitorAssociation [] [])(results[0]));
}
public System.IAsyncResult Beginget_monitor_association(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_monitor_association", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberMonitorAssociation [] [] Endget_monitor_association(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberMonitorAssociation [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_monitor_instance
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberMonitorInstanceState [] [] get_monitor_instance(
string [] pool_names
) {
object [] results = this.Invoke("get_monitor_instance", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberMonitorInstanceState [] [])(results[0]));
}
public System.IAsyncResult Beginget_monitor_instance(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_monitor_instance", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberMonitorInstanceState [] [] Endget_monitor_instance(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberMonitorInstanceState [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_monitor_status
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberMonitorStatus [] [] get_monitor_status(
string [] pool_names
) {
object [] results = this.Invoke("get_monitor_status", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberMonitorStatus [] [])(results[0]));
}
public System.IAsyncResult Beginget_monitor_status(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_monitor_status", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberMonitorStatus [] [] Endget_monitor_status(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberMonitorStatus [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_object_status
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberObjectStatus [] [] get_object_status(
string [] pool_names
) {
object [] results = this.Invoke("get_object_status", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberObjectStatus [] [])(results[0]));
}
public System.IAsyncResult Beginget_object_status(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_object_status", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberObjectStatus [] [] Endget_object_status(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberObjectStatus [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_priority
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberPriority [] [] get_priority(
string [] pool_names
) {
object [] results = this.Invoke("get_priority", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberPriority [] [])(results[0]));
}
public System.IAsyncResult Beginget_priority(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_priority", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberPriority [] [] Endget_priority(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberPriority [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberRatio [] [] get_ratio(
string [] pool_names
) {
object [] results = this.Invoke("get_ratio", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberRatio [] [])(results[0]));
}
public System.IAsyncResult Beginget_ratio(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_ratio", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberRatio [] [] Endget_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberRatio [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_session_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberSessionState [] [] get_session_enabled_state(
string [] pool_names
) {
object [] results = this.Invoke("get_session_enabled_state", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberSessionState [] [])(results[0]));
}
public System.IAsyncResult Beginget_session_enabled_state(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_session_enabled_state", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberSessionState [] [] Endget_session_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberSessionState [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_session_status
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberSessionStatus [] [] get_session_status(
string [] pool_names
) {
object [] results = this.Invoke("get_session_status", new object [] {
pool_names});
return ((LocalLBPoolMemberMemberSessionStatus [] [])(results[0]));
}
public System.IAsyncResult Beginget_session_status(string [] pool_names, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_session_status", new object[] {
pool_names}, callback, asyncState);
}
public LocalLBPoolMemberMemberSessionStatus [] [] Endget_session_status(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberSessionStatus [] [])(results[0]));
}
//-----------------------------------------------------------------------
// get_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public LocalLBPoolMemberMemberStatistics [] get_statistics(
string [] pool_names,
CommonIPPortDefinition [] [] members
) {
object [] results = this.Invoke("get_statistics", new object [] {
pool_names,
members});
return ((LocalLBPoolMemberMemberStatistics [])(results[0]));
}
public System.IAsyncResult Beginget_statistics(string [] pool_names,CommonIPPortDefinition [] [] members, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_statistics", new object[] {
pool_names,
members}, callback, asyncState);
}
public LocalLBPoolMemberMemberStatistics [] Endget_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((LocalLBPoolMemberMemberStatistics [])(results[0]));
}
//-----------------------------------------------------------------------
// get_version
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
[return: System.Xml.Serialization.SoapElementAttribute("return")]
public string get_version(
) {
object [] results = this.Invoke("get_version", new object [] {
});
return ((string)(results[0]));
}
public System.IAsyncResult Beginget_version(System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("get_version", new object[] {
}, callback, asyncState);
}
public string Endget_version(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
return ((string)(results[0]));
}
//-----------------------------------------------------------------------
// remove_monitor_association
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
public void remove_monitor_association(
string [] pool_names,
LocalLBPoolMemberMemberMonitorAssociationRemoval [] [] monitor_associations
) {
this.Invoke("remove_monitor_association", new object [] {
pool_names,
monitor_associations});
}
public System.IAsyncResult Beginremove_monitor_association(string [] pool_names,LocalLBPoolMemberMemberMonitorAssociationRemoval [] [] monitor_associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("remove_monitor_association", new object[] {
pool_names,
monitor_associations}, callback, asyncState);
}
public void Endremove_monitor_association(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// reset_statistics
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
public void reset_statistics(
string [] pool_names,
CommonIPPortDefinition [] [] members
) {
this.Invoke("reset_statistics", new object [] {
pool_names,
members});
}
public System.IAsyncResult Beginreset_statistics(string [] pool_names,CommonIPPortDefinition [] [] members, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("reset_statistics", new object[] {
pool_names,
members}, callback, asyncState);
}
public void Endreset_statistics(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_connection_limit
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
public void set_connection_limit(
string [] pool_names,
LocalLBPoolMemberMemberConnectionLimit [] [] limits
) {
this.Invoke("set_connection_limit", new object [] {
pool_names,
limits});
}
public System.IAsyncResult Beginset_connection_limit(string [] pool_names,LocalLBPoolMemberMemberConnectionLimit [] [] limits, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_connection_limit", new object[] {
pool_names,
limits}, callback, asyncState);
}
public void Endset_connection_limit(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_dynamic_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
public void set_dynamic_ratio(
string [] pool_names,
LocalLBPoolMemberMemberDynamicRatio [] [] dynamic_ratios
) {
this.Invoke("set_dynamic_ratio", new object [] {
pool_names,
dynamic_ratios});
}
public System.IAsyncResult Beginset_dynamic_ratio(string [] pool_names,LocalLBPoolMemberMemberDynamicRatio [] [] dynamic_ratios, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_dynamic_ratio", new object[] {
pool_names,
dynamic_ratios}, callback, asyncState);
}
public void Endset_dynamic_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_monitor_association
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
public void set_monitor_association(
string [] pool_names,
LocalLBPoolMemberMemberMonitorAssociation [] [] monitor_associations
) {
this.Invoke("set_monitor_association", new object [] {
pool_names,
monitor_associations});
}
public System.IAsyncResult Beginset_monitor_association(string [] pool_names,LocalLBPoolMemberMemberMonitorAssociation [] [] monitor_associations, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_monitor_association", new object[] {
pool_names,
monitor_associations}, callback, asyncState);
}
public void Endset_monitor_association(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_monitor_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
public void set_monitor_state(
string [] pool_names,
LocalLBPoolMemberMemberMonitorState [] [] monitor_states
) {
this.Invoke("set_monitor_state", new object [] {
pool_names,
monitor_states});
}
public System.IAsyncResult Beginset_monitor_state(string [] pool_names,LocalLBPoolMemberMemberMonitorState [] [] monitor_states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_monitor_state", new object[] {
pool_names,
monitor_states}, callback, asyncState);
}
public void Endset_monitor_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_priority
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
public void set_priority(
string [] pool_names,
LocalLBPoolMemberMemberPriority [] [] priorities
) {
this.Invoke("set_priority", new object [] {
pool_names,
priorities});
}
public System.IAsyncResult Beginset_priority(string [] pool_names,LocalLBPoolMemberMemberPriority [] [] priorities, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_priority", new object[] {
pool_names,
priorities}, callback, asyncState);
}
public void Endset_priority(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_ratio
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
public void set_ratio(
string [] pool_names,
LocalLBPoolMemberMemberRatio [] [] ratios
) {
this.Invoke("set_ratio", new object [] {
pool_names,
ratios});
}
public System.IAsyncResult Beginset_ratio(string [] pool_names,LocalLBPoolMemberMemberRatio [] [] ratios, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_ratio", new object[] {
pool_names,
ratios}, callback, asyncState);
}
public void Endset_ratio(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
//-----------------------------------------------------------------------
// set_session_enabled_state
//-----------------------------------------------------------------------
[System.Web.Services.Protocols.SoapRpcMethodAttribute("urn:iControl:LocalLB/PoolMember",
RequestNamespace="urn:iControl:LocalLB/PoolMember", ResponseNamespace="urn:iControl:LocalLB/PoolMember")]
public void set_session_enabled_state(
string [] pool_names,
LocalLBPoolMemberMemberSessionState [] [] session_states
) {
this.Invoke("set_session_enabled_state", new object [] {
pool_names,
session_states});
}
public System.IAsyncResult Beginset_session_enabled_state(string [] pool_names,LocalLBPoolMemberMemberSessionState [] [] session_states, System.AsyncCallback callback, object asyncState) {
return this.BeginInvoke("set_session_enabled_state", new object[] {
pool_names,
session_states}, callback, asyncState);
}
public void Endset_session_enabled_state(System.IAsyncResult asyncResult) {
object [] results = this.EndInvoke(asyncResult);
}
}
//=======================================================================
// Enums
//=======================================================================
//=======================================================================
// Structs
//=======================================================================
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberConnectionLimit", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberConnectionLimit
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private long connection_limitField;
public long connection_limit
{
get { return this.connection_limitField; }
set { this.connection_limitField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberDynamicRatio", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberDynamicRatio
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private long dynamic_ratioField;
public long dynamic_ratio
{
get { return this.dynamic_ratioField; }
set { this.dynamic_ratioField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberMonitorAssociation", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberMonitorAssociation
{
private LocalLBMonitorIPPort memberField;
public LocalLBMonitorIPPort member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private LocalLBMonitorRule monitor_ruleField;
public LocalLBMonitorRule monitor_rule
{
get { return this.monitor_ruleField; }
set { this.monitor_ruleField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberMonitorAssociationRemoval", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberMonitorAssociationRemoval
{
private LocalLBMonitorIPPort memberField;
public LocalLBMonitorIPPort member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private LocalLBMonitorAssociationRemovalRule removal_ruleField;
public LocalLBMonitorAssociationRemovalRule removal_rule
{
get { return this.removal_ruleField; }
set { this.removal_ruleField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberMonitorInstanceState", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberMonitorInstanceState
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private LocalLBMonitorInstanceState [] monitor_instancesField;
public LocalLBMonitorInstanceState [] monitor_instances
{
get { return this.monitor_instancesField; }
set { this.monitor_instancesField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberMonitorState", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberMonitorState
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private CommonEnabledState monitor_stateField;
public CommonEnabledState monitor_state
{
get { return this.monitor_stateField; }
set { this.monitor_stateField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberMonitorStatus", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberMonitorStatus
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private LocalLBMonitorStatus monitor_statusField;
public LocalLBMonitorStatus monitor_status
{
get { return this.monitor_statusField; }
set { this.monitor_statusField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberObjectStatus", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberObjectStatus
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private LocalLBObjectStatus object_statusField;
public LocalLBObjectStatus object_status
{
get { return this.object_statusField; }
set { this.object_statusField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberPriority", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberPriority
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private long priorityField;
public long priority
{
get { return this.priorityField; }
set { this.priorityField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberRatio", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberRatio
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private long ratioField;
public long ratio
{
get { return this.ratioField; }
set { this.ratioField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberSessionState", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberSessionState
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private CommonEnabledState session_stateField;
public CommonEnabledState session_state
{
get { return this.session_stateField; }
set { this.session_stateField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberSessionStatus", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberSessionStatus
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private LocalLBSessionStatus session_statusField;
public LocalLBSessionStatus session_status
{
get { return this.session_statusField; }
set { this.session_statusField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberStatisticEntry", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberStatisticEntry
{
private CommonIPPortDefinition memberField;
public CommonIPPortDefinition member
{
get { return this.memberField; }
set { this.memberField = value; }
}
private CommonStatistic [] statisticsField;
public CommonStatistic [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
};
/// <remarks/>
[System.CodeDom.Compiler.GeneratedCodeAttribute("wsdl", "2.0.50727.3038")]
[System.SerializableAttribute()]
[System.Diagnostics.DebuggerStepThroughAttribute()]
[System.ComponentModel.DesignerCategoryAttribute("code")]
[System.Xml.Serialization.SoapTypeAttribute(TypeName = "LocalLB.PoolMember.MemberStatistics", Namespace = "urn:iControl")]
public partial class LocalLBPoolMemberMemberStatistics
{
private LocalLBPoolMemberMemberStatisticEntry [] statisticsField;
public LocalLBPoolMemberMemberStatisticEntry [] statistics
{
get { return this.statisticsField; }
set { this.statisticsField = value; }
}
private CommonTimeStamp time_stampField;
public CommonTimeStamp time_stamp
{
get { return this.time_stampField; }
set { this.time_stampField = value; }
}
};
}
| |
#region License
// Copyright (c) 2010-2019, Mark Final
// 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 BuildAMation nor the names of its
// contributors may be used to endorse or promote products derived from
// this software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
// DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
// SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
// CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
// OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#endregion // License
using System.Linq;
namespace C
{
/// <summary>
/// Utility class offering support for Xcode project generation
/// </summary>
static partial class XcodeSupport
{
/// <summary>
/// Generate an Xcode Target that has been the result of a link or an archive
/// </summary>
/// <param name="outTarget">Generated Target</param>
/// <param name="outConfiguration">Generated Configuration</param>
/// <param name="module">Module represented</param>
/// <param name="fileType">Filetype of the output</param>
/// <param name="productType">Product type of the output</param>
/// <param name="productName">Product name of the output</param>
/// <param name="outputPath">Path to the output</param>
/// <param name="headerFiles">Any header files to be included</param>
public static void
LinkOrArchive(
out XcodeBuilder.Target outTarget,
out XcodeBuilder.Configuration outConfiguration,
CModule module,
XcodeBuilder.FileReference.EFileType fileType,
XcodeBuilder.Target.EProductType productType,
Bam.Core.TokenizedString productName,
Bam.Core.TokenizedString outputPath,
System.Collections.Generic.IEnumerable<Bam.Core.Module> headerFiles)
{
if (module.IsPrebuilt || !module.InputModulePaths.Any())
{
outTarget = null;
outConfiguration = null;
return;
}
var workspace = Bam.Core.Graph.Instance.MetaData as XcodeBuilder.WorkspaceMeta;
var target = workspace.EnsureTargetExists(module);
var output_filename = module.CreateTokenizedString(
"@filename($(0))",
outputPath
);
output_filename.Parse();
target.EnsureOutputFileReferenceExists(
output_filename,
fileType,
productType
);
var configuration = target.GetConfiguration(module);
lock (productName)
{
if (!productName.IsParsed)
{
productName.Parse();
}
}
configuration.SetProductName(productName);
// there are settings explicitly for prefix and suffix
if (module is C.Plugin || module is C.Cxx.Plugin)
{
var prefix = module.CreateTokenizedString("$(pluginprefix)");
if (!prefix.IsParsed)
{
prefix.Parse();
}
configuration["EXECUTABLE_PREFIX"] = new XcodeBuilder.UniqueConfigurationValue(prefix.ToString());
var suffix = module.CreateTokenizedString("$(pluginext)");
if (!suffix.IsParsed)
{
suffix.Parse();
}
configuration["EXECUTABLE_EXTENSION"] = new XcodeBuilder.UniqueConfigurationValue(suffix.ToString().TrimStart(new[] { '.' }));
}
else if (module is C.DynamicLibrary || module is C.Cxx.DynamicLibrary)
{
var prefix = module.CreateTokenizedString("$(dynamicprefix)");
if (!prefix.IsParsed)
{
prefix.Parse();
}
configuration["EXECUTABLE_PREFIX"] = new XcodeBuilder.UniqueConfigurationValue(prefix.ToString());
var suffix = module.CreateTokenizedString("$(dynamicextonly)");
if (!suffix.IsParsed)
{
suffix.Parse();
}
configuration["EXECUTABLE_EXTENSION"] = new XcodeBuilder.UniqueConfigurationValue(suffix.ToString().TrimStart(new[] { '.' }));
}
else if (module is C.ConsoleApplication || module is C.Cxx.ConsoleApplication)
{
var prefix = string.Empty;
configuration["EXECUTABLE_PREFIX"] = new XcodeBuilder.UniqueConfigurationValue(prefix);
var suffix = module.CreateTokenizedString("$(exeext)");
if (!suffix.IsParsed)
{
suffix.Parse();
}
configuration["EXECUTABLE_EXTENSION"] = new XcodeBuilder.UniqueConfigurationValue(suffix.ToString().TrimStart(new[] { '.' }));
}
else if (module is C.StaticLibrary)
{
// nothing to set
}
else
{
throw new Bam.Core.Exception(
$"Unknown type of executable is being processed: {module.ToString()}"
);
}
foreach (var header in headerFiles)
{
target.EnsureHeaderFileExists((header as HeaderFile).InputPath);
}
var excludedSource = new XcodeBuilder.MultiConfigurationValue();
var realObjectFiles = module.InputModulePaths.Select(item => item.module).Where(item => item is ObjectFile); // C,C++,ObjC,ObjC++
if (realObjectFiles.Any())
{
var sharedSettings = C.SettingsBase.SharedSettings(
realObjectFiles
);
XcodeSharedSettings.Tweak(sharedSettings, realObjectFiles.Count() != module.InputModulePaths.Count());
XcodeProjectProcessor.XcodeConversion.Convert(
sharedSettings,
module,
configuration,
settingsTypeOverride: realObjectFiles.First().Settings.GetType()
);
foreach (var objFile in realObjectFiles)
{
var asObjFileBase = objFile as C.ObjectFileBase;
if (!asObjFileBase.PerformCompilation)
{
excludedSource.Add((asObjFileBase as C.IRequiresSourceModule).Source.InputPath.ToString());
}
var buildFile = objFile.MetaData as XcodeBuilder.BuildFile;
var deltaSettings = (objFile.Settings as C.SettingsBase).CreateDeltaSettings(sharedSettings, objFile);
if (null != deltaSettings)
{
if (deltaSettings is C.ICommonPreprocessorSettings preprocessor)
{
// this happens for mixed C language source files, e.g. C++ and ObjC++,
// 1) the target language is already encoded in the file type
// 2) Xcode 10's build system seems to ignore some C++ language settings if -x c++ appears on C++ source files
preprocessor.TargetLanguage = null;
}
var commandLine = CommandLineProcessor.NativeConversion.Convert(
deltaSettings,
objFile,
createDelta: true
);
if (commandLine.Any())
{
// Cannot set per-file-per-configuration settings, so blend them together
if (null == buildFile.Settings)
{
buildFile.Settings = commandLine;
}
else
{
buildFile.Settings.AddRangeUnique(commandLine);
}
}
}
configuration.BuildFiles.Add(buildFile);
}
// now deal with other object file types
var assembledObjectFiles = module.InputModulePaths.Select(item => item.module).Where(item => item is AssembledObjectFile);
foreach (var asmObj in assembledObjectFiles)
{
var buildFile = asmObj.MetaData as XcodeBuilder.BuildFile;
configuration.BuildFiles.Add(buildFile);
}
}
else
{
var firstInputModuleSettings = module.InputModulePaths.First().module.Settings;
XcodeProjectProcessor.XcodeConversion.Convert(
firstInputModuleSettings,
module,
configuration
);
foreach (var objFile in module.InputModulePaths.Select(item => item.module))
{
var asObjFileBase = objFile as C.ObjectFileBase;
if (!asObjFileBase.PerformCompilation)
{
excludedSource.Add((asObjFileBase as C.IRequiresSourceModule).Source.InputPath.ToString());
}
var buildFile = objFile.MetaData as XcodeBuilder.BuildFile;
configuration.BuildFiles.Add(buildFile);
}
}
configuration["EXCLUDED_SOURCE_FILE_NAMES"] = excludedSource;
outTarget = target;
outConfiguration = configuration;
}
/// <summary>
/// Process all library dependencies on a module
/// </summary>
/// <param name="module">Module with dependencies</param>
/// <param name="target">Target to add dependencies on.</param>
public static void
ProcessLibraryDependencies(
ConsoleApplication module,
XcodeBuilder.Target target)
{
// add library search paths prior to converting linker settings
var linker = module.Settings as C.ICommonLinkerSettings;
foreach (var library in module.Libraries)
{
if (library is C.StaticLibrary)
{
foreach (var dir in library.OutputDirectories)
{
linker.LibraryPaths.AddUnique(dir);
}
}
else if (library is C.IDynamicLibrary)
{
foreach (var dir in library.OutputDirectories)
{
linker.LibraryPaths.AddUnique(dir);
}
}
else if (library is C.CSDKModule)
{
// SDK modules are collections of libraries, not one in particular
// thus do nothing as they are undefined at this point, and may yet be pulled in automatically
}
else if (library is C.HeaderLibrary)
{
// no library
}
else if (library is OSXFramework)
{
// frameworks are dealt with elsewhere
}
else
{
throw new Bam.Core.Exception(
$"Don't know how to handle this module type, {library.ToString()}"
);
}
}
foreach (var library in module.Libraries)
{
var libAsCModule = library as C.CModule;
if (null == libAsCModule)
{
throw new Bam.Core.Exception(
$"Don't know how to handle library module of type '{library.GetType().ToString()}'"
);
}
if (libAsCModule.IsPrebuilt)
{
if (library is OSXFramework)
{
// frameworks are dealt with elsewhere
}
else if (library is C.StaticLibrary)
{
(module.Tool as C.LinkerTool).ProcessLibraryDependency(module as CModule, libAsCModule);
}
else
{
throw new Bam.Core.Exception(
$"Don't know how to handle this prebuilt module dependency, '{library.GetType().ToString()}'"
);
}
}
else
{
if (library is C.StaticLibrary)
{
target.DependsOn(library.MetaData as XcodeBuilder.Target);
}
else if (library is C.IDynamicLibrary)
{
target.DependsOn(library.MetaData as XcodeBuilder.Target);
}
else if (library is C.CSDKModule)
{
// do nothing, just an area for external
}
else if (library is C.HeaderLibrary)
{
// no library
}
else if (library is OSXFramework)
{
// frameworks are dealt with elsewhere
}
else
{
throw new Bam.Core.Exception("Don't know how to handle this module type");
}
}
}
}
/// <summary>
/// Add order only dependencies from a module
/// </summary>
/// <param name="module">Module containing order only dependencies</param>
/// <param name="target">Target to add dependencies on</param>
public static void
AddOrderOnlyDependentProjects(
C.CModule module,
XcodeBuilder.Target target)
{
// the target for a HeaderLibrary has no FileReference output, and thus cannot be an order only dependency
var order_only_targets =
module.OrderOnlyDependents().
Distinct().
Where(item => item.MetaData != null && item.MetaData is XcodeBuilder.Target && !(item is HeaderLibrary)).
Select(item => item.MetaData as XcodeBuilder.Target);
foreach (var required_target in order_only_targets)
{
target.Requires(required_target);
}
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Threading;
using System.Diagnostics;
using System.Collections.Generic;
using System.Diagnostics.Tracing;
using System.Runtime.CompilerServices;
// TODO when we upgrade to C# V6 you can remove this.
// warning CS0420: 'P.x': a reference to a volatile field will not be treated as volatile
// This happens when you pass a _subcribers (a volatile field) to interlocked operations (which are byref).
// This was fixed in C# V6.
#pragma warning disable 0420
namespace System.Diagnostics
{
/// <summary>
/// A DiagnosticListener is something that forwards on events written with DiagnosticSource.
/// It is an IObservable (has Subscribe method), and it also has a Subscribe overload that
/// lets you specify a 'IsEnabled' predicate that users of DiagnosticSource will use for
/// 'quick checks'.
///
/// The item in the stream is a KeyValuePair[string, object] where the string is the name
/// of the diagnostic item and the object is the payload (typically an anonymous type).
///
/// There may be many DiagnosticListeners in the system, but we encourage the use of
/// The DiagnosticSource.DefaultSource which goes to the DiagnosticListener.DefaultListener.
///
/// If you need to see 'everything' you can subscribe to the 'AllListeners' event that
/// will fire for every live DiagnosticListener in the appdomain (past or present).
///
/// Please See the DiagnosticSource Users Guide
/// https://github.com/dotnet/corefx/blob/master/src/System.Diagnostics.DiagnosticSource/src/DiagnosticSourceUsersGuide.md
/// for instructions on its use.
/// </summary>
public class DiagnosticListener : DiagnosticSource, IObservable<KeyValuePair<string, object>>, IDisposable
{
/// <summary>
/// When you subscribe to this you get callbacks for all NotificationListeners in the appdomain
/// as well as those that occurred in the past, and all future Listeners created in the future.
/// </summary>
public static IObservable<DiagnosticListener> AllListeners
{
get
{
if (s_allListenerObservable == null)
{
s_allListenerObservable = new AllListenerObservable();
}
return s_allListenerObservable;
}
}
// Subscription implementation
/// <summary>
/// Add a subscriber (Observer). If 'IsEnabled' == null (or not present), then the Source's IsEnabled
/// will always return true.
/// </summary>
virtual public IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer, Predicate<string> isEnabled)
{
// If we have been disposed, we silently ignore any subscriptions.
if (_disposed)
{
return new DiagnosticSubscription() { Owner = this };
}
DiagnosticSubscription newSubscription = new DiagnosticSubscription() { Observer = observer, IsEnabled = isEnabled, Owner = this, Next = _subscriptions };
while (Interlocked.CompareExchange(ref _subscriptions, newSubscription, newSubscription.Next) != newSubscription.Next)
newSubscription.Next = _subscriptions;
return newSubscription;
}
/// <summary>
/// Same as other Subscribe overload where the predicate is assumed to always return true.
/// </summary>
public IDisposable Subscribe(IObserver<KeyValuePair<string, object>> observer)
{
return Subscribe(observer, null);
}
/// <summary>
/// Make a new DiagnosticListener, it is a NotificationSource, which means the returned result can be used to
/// log notifications, but it also has a Subscribe method so notifications can be forwarded
/// arbitrarily. Thus its job is to forward things from the producer to all the listeners
/// (multi-casting). Generally you should not be making your own DiagnosticListener but use the
/// DiagnosticListener.Default, so that notifications are as 'public' as possible.
/// </summary>
public DiagnosticListener(string name)
{
Name = name;
// Insert myself into the list of all Listeners.
lock (s_lock)
{
// Issue the callback for this new diagnostic listener.
var allListenerObservable = s_allListenerObservable;
if (allListenerObservable != null)
allListenerObservable.OnNewDiagnosticListener(this);
// And add it to the list of all past listeners.
_next = s_allListeners;
s_allListeners = this;
}
// Call IsEnabled just so we insure that the DiagnosticSourceEventSource has been
// constructed (and thus is responsive to ETW requests to be enabled).
DiagnosticSourceEventSource.Logger.IsEnabled();
}
/// <summary>
/// Clean up the NotificationListeners. Notification listeners do NOT DIE ON THEIR OWN
/// because they are in a global list (for discoverability). You must dispose them explicitly.
/// Note that we do not do the Dispose(bool) pattern because we frankly don't want to support
/// subclasses that have non-managed state.
/// </summary>
virtual public void Dispose()
{
// Remove myself from the list of all listeners.
lock (s_lock)
{
if (_disposed)
{
return;
}
_disposed = true;
if (s_allListeners == this)
s_allListeners = s_allListeners._next;
else
{
var cur = s_allListeners;
while (cur != null)
{
if (cur._next == this)
{
cur._next = _next;
break;
}
cur = cur._next;
}
}
_next = null;
}
// Indicate completion to all subscribers.
DiagnosticSubscription subscriber = null;
Interlocked.Exchange(ref subscriber, _subscriptions);
while (subscriber != null)
{
subscriber.Observer.OnCompleted();
subscriber = subscriber.Next;
}
// The code above also nulled out all subscriptions.
}
/// <summary>
/// When a DiagnosticListener is created it is given a name. Return this.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// Return the name for the ToString() to aid in debugging.
/// </summary>
/// <returns></returns>
public override string ToString()
{
return Name;
}
#region private
// NotificationSource implementation
/// <summary>
/// Override abstract method
/// </summary>
public override bool IsEnabled(string name)
{
for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
{
if (curSubscription.IsEnabled == null || curSubscription.IsEnabled(name))
return true;
}
return false;
}
/// <summary>
/// Override abstract method
/// </summary>
public override void Write(string name, object value)
{
for (DiagnosticSubscription curSubscription = _subscriptions; curSubscription != null; curSubscription = curSubscription.Next)
curSubscription.Observer.OnNext(new KeyValuePair<string, object>(name, value));
}
// Note that Subscriptions are READ ONLY. This means you never update any fields (even on removal!)
private class DiagnosticSubscription : IDisposable
{
internal IObserver<KeyValuePair<string, object>> Observer;
internal Predicate<string> IsEnabled;
internal DiagnosticListener Owner; // The DiagnosticListener this is a subscription for.
internal DiagnosticSubscription Next; // Linked list of subscribers
public void Dispose()
{
// TO keep this lock free and easy to analyze, the linked list is READ ONLY. Thus we copy
for (;;)
{
DiagnosticSubscription subscriptions = Owner._subscriptions;
DiagnosticSubscription newSubscriptions = Remove(subscriptions, this); // Make a new list, with myself removed.
// try to update, but if someone beat us to it, then retry.
if (Interlocked.CompareExchange(ref Owner._subscriptions, newSubscriptions, subscriptions) == subscriptions)
{
#if DEBUG
var cur = newSubscriptions;
while (cur != null)
{
Debug.Assert(!(cur.Observer == Observer && cur.IsEnabled == IsEnabled), "Did not remove subscription!");
cur = cur.Next;
}
#endif
break;
}
}
}
// Create a new linked list where 'subscription has been removed from the linked list of 'subscriptions'.
private static DiagnosticSubscription Remove(DiagnosticSubscription subscriptions, DiagnosticSubscription subscription)
{
if (subscriptions == null)
{
// May happen if the IDisposable returned from Subscribe is Dispose'd again
return null;
}
if (subscriptions.Observer == subscription.Observer && subscriptions.IsEnabled == subscription.IsEnabled)
return subscriptions.Next;
#if DEBUG
// Delay a bit. This makes it more likely that races will happen.
for (int i = 0; i < 100; i++)
GC.KeepAlive("");
#endif
return new DiagnosticSubscription() { Observer = subscriptions.Observer, Owner = subscriptions.Owner, IsEnabled = subscriptions.IsEnabled, Next = Remove(subscriptions.Next, subscription) };
}
}
#region AllListenerObservable
/// <summary>
/// Logically AllListenerObservable has a very simple task. It has a linked list of subscribers that want
/// a callback when a new listener gets created. When a new DiagnosticListener gets created it should call
/// OnNewDiagnosticListener so that AllListenerObservable can forward it on to all the subscribers.
/// </summary>
private class AllListenerObservable : IObservable<DiagnosticListener>
{
public IDisposable Subscribe(IObserver<DiagnosticListener> observer)
{
lock (s_lock)
{
// Call back for each existing listener on the new callback (catch-up).
for (DiagnosticListener cur = s_allListeners; cur != null; cur = cur._next)
observer.OnNext(cur);
// Add the observer to the list of subscribers.
_subscriptions = new AllListenerSubscription(this, observer, _subscriptions);
return _subscriptions;
}
}
/// <summary>
/// Called when a new DiagnosticListener gets created to tell anyone who subscribed that this happened.
/// </summary>
/// <param name="diagnosticListener"></param>
internal void OnNewDiagnosticListener(DiagnosticListener diagnosticListener)
{
Debug.Assert(Monitor.IsEntered(s_lock)); // We should only be called when we hold this lock
// Simply send a callback to every subscriber that we have a new listener
for (var cur = _subscriptions; cur != null; cur = cur.Next)
cur.Subscriber.OnNext(diagnosticListener);
}
#region private
/// <summary>
/// Remove 'subscription from the list of subscriptions that the observable has. Called when
/// subscriptions are disposed. Returns true if the subscription was removed.
/// </summary>
private bool Remove(AllListenerSubscription subscription)
{
lock (s_lock)
{
if (_subscriptions == subscription)
{
_subscriptions = subscription.Next;
return true;
}
else if (_subscriptions != null)
{
for (var cur = _subscriptions; cur.Next != null; cur = cur.Next)
{
if (cur.Next == subscription)
{
cur.Next = cur.Next.Next;
return true;
}
}
}
// Subscriber likely disposed multiple times
return false;
}
}
/// <summary>
/// One node in the linked list of subscriptions that AllListenerObservable keeps. It is
/// IDisposable, and when that is called it removes itself from the list.
/// </summary>
internal class AllListenerSubscription : IDisposable
{
internal AllListenerSubscription(AllListenerObservable owner, IObserver<DiagnosticListener> subscriber, AllListenerSubscription next)
{
this._owner = owner;
this.Subscriber = subscriber;
this.Next = next;
}
public void Dispose()
{
if (_owner.Remove(this))
{
Subscriber.OnCompleted(); // Called outside of a lock
}
}
private readonly AllListenerObservable _owner; // the list this is a member of.
internal readonly IObserver<DiagnosticListener> Subscriber;
internal AllListenerSubscription Next;
}
private AllListenerSubscription _subscriptions;
#endregion
}
#endregion
private volatile DiagnosticSubscription _subscriptions;
private DiagnosticListener _next; // We keep a linked list of all NotificationListeners (s_allListeners)
private bool _disposed; // Has Dispose been called?
private static DiagnosticListener s_allListeners; // linked list of all instances of DiagnosticListeners.
private static AllListenerObservable s_allListenerObservable; // to make callbacks to this object when listeners come into existence.
private static object s_lock = new object(); // A lock for
#if false
private static readonly DiagnosticListener s_default = new DiagnosticListener("DiagnosticListener.DefaultListener");
#endif
#endregion
}
}
| |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Xml.Linq;
using Microsoft.CodeAnalysis;
namespace IxMilia.Dxf.Generator
{
[Generator]
public class TableGenerator : GeneratorBase, ISourceGenerator
{
private XElement _xml;
private string _xmlns;
private IEnumerable<XElement> _tables;
public const string TableNamespace = "IxMilia.Dxf.Tables";
public void Initialize(GeneratorInitializationContext context)
{
}
public void Execute(GeneratorExecutionContext context)
{
var specText = context.AdditionalFiles.Single(f => Path.GetFileName(f.Path) == "TableSpec.xml").GetText().ToString();
_xml = XDocument.Parse(specText).Root;
_xmlns = _xml.Name.NamespaceName;
_tables = _xml.Elements(XName.Get("Table", _xmlns));
OutputTables(context);
OutputTableItems(context);
}
private void OutputTables(GeneratorExecutionContext context)
{
foreach (var table in _tables)
{
var tableItem = Name(table.Element(XName.Get("TableItem", _xmlns)));
var className = "Dxf" + Type(table) + "Table";
CreateNewFile(TableNamespace, "System.Linq", "System.Collections.Generic", "IxMilia.Dxf.Collections", "IxMilia.Dxf.Sections");
IncreaseIndent();
AppendLine($"public partial class {className} : DxfTable");
AppendLine("{");
IncreaseIndent();
AppendLine($"internal override DxfTableType TableType {{ get {{ return DxfTableType.{Type(table)}; }} }}");
var tableClassName = TableClassName(table);
if (tableClassName != null)
{
AppendLine($"internal override string TableClassName {{ get {{ return \"{tableClassName}\"; }} }}");
}
AppendLine();
AppendLine($"public IList<{tableItem}> Items {{ get; private set; }}");
AppendLine();
AppendLine("protected override IEnumerable<DxfSymbolTableFlags> GetSymbolItems()");
AppendLine("{");
AppendLine(" return Items.Cast<DxfSymbolTableFlags>();");
AppendLine("}");
//
// Constructor
//
AppendLine();
AppendLine($"public {className}()");
AppendLine("{");
AppendLine($" Items = new ListNonNull<{tableItem}>();");
AppendLine(" Normalize();");
AppendLine("}");
//
// ReadFromBuffer
//
AppendLine();
AppendLine("internal static DxfTable ReadFromBuffer(DxfCodePairBufferReader buffer)");
AppendLine("{");
AppendLine($" var table = new {className}();");
AppendLine(" table.Items.Clear();");
AppendLine(" while (buffer.ItemsRemain)");
AppendLine(" {");
AppendLine(" var pair = buffer.Peek();");
AppendLine(" buffer.Advance();");
AppendLine(" if (DxfTablesSection.IsTableEnd(pair))");
AppendLine(" {");
AppendLine(" break;");
AppendLine(" }");
AppendLine();
AppendLine($" if (pair.Code == 0 && pair.StringValue == DxfTable.{TypeStringVariable(table)})");
AppendLine(" {");
AppendLine($" var item = {tableItem}.FromBuffer(buffer);");
AppendLine(" table.Items.Add(item);");
AppendLine(" }");
AppendLine(" }"); // end while
AppendLine();
AppendLine(" return table;");
AppendLine("}"); // end method
DecreaseIndent();
AppendLine("}"); // end class
DecreaseIndent();
FinishFile();
WriteFile(context, $"{className}Generated.cs");
}
}
private void OutputTableItems(GeneratorExecutionContext context)
{
foreach (var table in _tables)
{
var tableItem = table.Element(XName.Get("TableItem", _xmlns));
var properties = tableItem.Elements(XName.Get("Property", _xmlns));
CreateNewFile("IxMilia.Dxf", "System", "System.Linq", "System.Collections.Generic", "IxMilia.Dxf.Collections", "IxMilia.Dxf.Sections", "IxMilia.Dxf.Tables");
IncreaseIndent();
AppendLine($"public partial class {Name(tableItem)} : DxfSymbolTableFlags");
AppendLine("{");
IncreaseIndent();
AppendLine($"internal const string AcDbText = \"{ClassName(tableItem)}\";");
AppendLine();
AppendLine($"protected override DxfTableType TableType {{ get {{ return DxfTableType.{Type(table)}; }} }}");
//
// Properties
//
if (properties.Any())
{
AppendLine();
}
var seenProperties = new HashSet<string>();
foreach (var property in properties)
{
var name = Name(property);
if (!seenProperties.Contains(name))
{
seenProperties.Add(name);
var propertyType = Type(property);
if (AllowMultiples(property))
{
propertyType = $"IList<{propertyType}>";
}
var getset = $"{{ get; {SetterAccessibility(property)}set; }}";
var comment = Comment(property);
var headerVar = ExpandCommentOrNull(HeaderVariable(property), "Corresponds to header variable {0}.");
var minVersion = ExpandCommentOrNull(MinVersion(property), "Minimum drawing version {0}.");
var maxVersion = ExpandCommentOrNull(MaxVersion(property), "Maximum drawing version {0}.");
var commentParts = new[] { comment, headerVar, minVersion, maxVersion }.Where(x => x != null).ToList();
AppendLine();
if (commentParts.Count > 0)
{
AppendLine("/// <summary>");
AppendLine("/// " + string.Join(" ", commentParts));
AppendLine("/// </summary>");
}
AppendLine($"{Accessibility(property)} {propertyType} {name} {getset}");
}
}
AppendLine();
AppendLine("public IDictionary<string, DxfXDataApplicationItemCollection> XData { get; } = new DictionaryWithPredicate<string, DxfXDataApplicationItemCollection>((_key, value) => value != null);");
//
// Constructors
//
AppendLine();
AppendLine($"public {Name(tableItem)}(string name)");
AppendLine(" : this()");
AppendLine("{");
AppendLine(" if (string.IsNullOrEmpty(name))");
AppendLine(" {");
AppendLine(" throw new ArgumentException(nameof(name), $\"Parameter '{nameof(name)}' must have a value.\");");
AppendLine(" }");
AppendLine();
AppendLine(" Name = name;");
AppendLine("}");
AppendLine();
AppendLine($"internal {Name(tableItem)}()");
AppendLine(" : base()");
AppendLine("{");
IncreaseIndent();
foreach (var property in properties)
{
var defaultValue = DefaultValue(property);
if (AllowMultiples(property))
{
defaultValue = $"new ListNonNull<{Type(property)}>()";
}
AppendLine($"{Name(property)} = {defaultValue};");
}
DecreaseIndent();
AppendLine("}"); // end constructor
//
// AddValuePairs
//
if (GenerateWriterFunction(tableItem))
{
AppendLine();
AppendLine("internal override void AddValuePairs(List<DxfCodePair> pairs, DxfAcadVersion version, bool outputHandles)");
AppendLine("{");
IncreaseIndent();
AppendLine("if (version >= DxfAcadVersion.R13)");
AppendLine("{");
AppendLine(" pairs.Add(new DxfCodePair(100, AcDbText));");
AppendLine("}");
AppendLine();
AppendLine("pairs.Add(new DxfCodePair(2, Name));");
if (HasFlags(tableItem))
{
AppendLine("pairs.Add(new DxfCodePair(70, (short)StandardFlags));");
}
foreach (var property in properties)
{
var disableWritingDefault = DisableWritingDefault(property);
var writeCondition = WriteCondition(property);
var minVersion = MinVersion(property);
var maxVersion = MaxVersion(property);
var hasPredicate = disableWritingDefault || writeCondition != null || minVersion != null || maxVersion != null;
string predicate = null;
if (hasPredicate)
{
var parts = new List<string>();
if (disableWritingDefault)
{
parts.Add(string.Format("{0} != {1}", Name(property), DefaultValue(property)));
}
if (writeCondition != null)
{
parts.Add(writeCondition);
}
if ((minVersion != null || maxVersion != null) && minVersion == maxVersion)
{
parts.Add("version == DxfAcadVersion." + minVersion);
}
else
{
if (minVersion != null)
{
parts.Add("version >= DxfAcadVersion." + minVersion);
}
if (maxVersion != null)
{
parts.Add("version <= DxfAcadVersion." + maxVersion);
}
}
predicate = string.Join(" && ", parts);
}
if (AllowMultiples(property))
{
if (hasPredicate)
{
AppendLine($"if ({predicate})");
AppendLine("{");
IncreaseIndent();
}
AppendLine($"pairs.AddRange({Name(property)}.Select(value => new DxfCodePair({Code(property)}, value)));");
if (hasPredicate)
{
DecreaseIndent();
AppendLine("}");
AppendLine();
}
}
else
{
var codeOverrides = CodeOverrides(property);
var writeConverter = WriteConverter(property);
if (Code(property) < 0 && codeOverrides != null)
{
char prop = 'X';
for (int i = 0; i < codeOverrides.Length; i++, prop++)
{
if (hasPredicate)
{
AppendLine($"if ({predicate})");
AppendLine("{");
IncreaseIndent();
}
AppendLine($"pairs.Add(new DxfCodePair({codeOverrides[i]}, {string.Format(writeConverter, $"{Name(property)}.{prop}")}));");
if (hasPredicate)
{
DecreaseIndent();
AppendLine("}");
AppendLine();
}
}
}
else
{
if (hasPredicate)
{
AppendLine($"if ({predicate})");
AppendLine("{");
IncreaseIndent();
}
AppendLine($"pairs.Add(new DxfCodePair({Code(property)}, {string.Format(writeConverter, $"{Name(property)}")}));");
if (hasPredicate)
{
DecreaseIndent();
AppendLine("}");
AppendLine();
}
}
}
}
AppendLine("DxfXData.AddValuePairs(XData, pairs, version, outputHandles);");
DecreaseIndent();
AppendLine("}"); // end method
}
//
// Reader
//
if (GenerateReaderFunction(tableItem))
{
//
// FromBuffer
//
AppendLine();
AppendLine($"internal static {Name(tableItem)} FromBuffer(DxfCodePairBufferReader buffer)");
AppendLine("{");
IncreaseIndent();
AppendLine($"var item = new {Name(tableItem)}();");
AppendLine("while (buffer.ItemsRemain)");
AppendLine("{");
IncreaseIndent();
AppendLine("var pair = buffer.Peek();");
AppendLine("if (pair.Code == 0)");
AppendLine("{");
AppendLine(" break;");
AppendLine("}");
AppendLine();
AppendLine("buffer.Advance();");
AppendLine("switch (pair.Code)");
AppendLine("{");
IncreaseIndent();
AppendLine("case DxfCodePairGroup.GroupCodeNumber:");
AppendLine(" var groupName = DxfCodePairGroup.GetGroupName(pair.StringValue);");
AppendLine(" item.ExtensionDataGroups.Add(DxfCodePairGroup.FromBuffer(buffer, groupName));");
AppendLine(" break;");
AppendLine("case (int)DxfXDataType.ApplicationName:");
AppendLine(" DxfXData.PopulateFromBuffer(buffer, item.XData, pair.StringValue);");
AppendLine(" break;");
AppendLine("default:");
AppendLine(" item.ApplyCodePair(pair);");
AppendLine(" break;");
DecreaseIndent();
AppendLine("}"); // end switch
DecreaseIndent();
AppendLine("}"); // end while
AppendLine();
AppendLine("return item;");
DecreaseIndent();
AppendLine("}");// end method
//
// ApplyCodePair
//
AppendLine();
AppendLine("private void ApplyCodePair(DxfCodePair pair)");
AppendLine("{");
IncreaseIndent();
AppendLine("switch (pair.Code)");
AppendLine("{");
IncreaseIndent();
if (HasFlags(tableItem))
{
AppendLine("case 70:");
AppendLine(" StandardFlags = (int)pair.ShortValue;");
AppendLine(" break;");
}
foreach (var property in properties)
{
var codeOverrides = CodeOverrides(property);
if (Code(property) < 0 && codeOverrides != null)
{
char prop = 'X';
for (int i = 0; i < codeOverrides.Length; i++, prop++)
{
var codeType = DxfCodePair.ExpectedType(codeOverrides[i]);
var codeTypeValue = TypeToString(codeType);
AppendLine($"case {codeOverrides[i]}:");
AppendLine($" {Name(property)} = {Name(property)}.WithUpdated{prop}(pair.{codeTypeValue});");
AppendLine(" break;");
}
}
else
{
var code = Code(property);
var codeType = DxfCodePair.ExpectedType(code);
var codeTypeValue = TypeToString(codeType);
var readConverter = ReadConverter(property);
AppendLine($"case {Code(property)}:");
if (AllowMultiples(property))
{
AppendLine($" {Name(property)}.Add({string.Format(readConverter, $"pair.{codeTypeValue}")});");
}
else
{
AppendLine($" {Name(property)} = {string.Format(readConverter, $"pair.{codeTypeValue}")};");
}
AppendLine(" break;");
}
}
AppendLine("default:");
AppendLine(" TrySetPair(pair);");
AppendLine(" break;");
DecreaseIndent();
AppendLine("}"); // end switch
DecreaseIndent();
AppendLine("}"); // end method
}
//
// Clone
//
AppendLine();
AppendLine($"public {Name(tableItem)} Clone()");
AppendLine("{");
IncreaseIndent();
AppendLine($"return ({Name(tableItem)})this.MemberwiseClone();");
DecreaseIndent();
AppendLine("}");
if (Name(tableItem) == "DxfDimStyle")
{
//
// DxfDimStyle.SetVariable
//
AppendLine();
AppendLine("public void SetVariable(string name, object value)");
AppendLine("{");
IncreaseIndent();
AppendLine("switch (name?.ToUpper())");
AppendLine("{");
IncreaseIndent();
var setProperties = new HashSet<string>();
foreach (var property in properties)
{
if (setProperties.Add(HeaderVariable(property)))
{
AppendLine($"case \"{HeaderVariable(property)}\":");
AppendLine($" {Name(property)} = ({Type(property)})value;");
AppendLine(" break;");
}
}
DecreaseIndent();
AppendLine("}"); // end switch
DecreaseIndent();
AppendLine("}"); // end method
//
// DxfDimStyle.GetVariable
//
AppendLine();
AppendLine("public object GetVariable(string name)");
AppendLine("{");
IncreaseIndent();
AppendLine("switch (name?.ToUpper())");
AppendLine("{");
IncreaseIndent();
var getProperties = new HashSet<string>();
foreach (var property in properties)
{
if (getProperties.Add(HeaderVariable(property)))
{
AppendLine($"case \"{HeaderVariable(property)}\":");
AppendLine($" return {Name(property)};");
}
}
AppendLine("default:");
AppendLine(" return null;");
DecreaseIndent();
AppendLine("}"); // end switch
DecreaseIndent();
AppendLine("}"); // end method
//
// DxfDimStyle.GenerateStyleDifferenceAsXData
//
AppendLine();
AppendLine("/// <summary>Generates <see cref=\"DxfXDataApplicationItemCollection\"/> of the difference between the styles. Result may be <see langword=\"null\"/>.</summary>");
AppendLine("public static DxfXDataApplicationItemCollection GenerateStyleDifferenceAsXData(DxfDimStyle primaryStyle, DxfDimStyle modifiedStyle)");
AppendLine("{");
IncreaseIndent();
AppendLine("var itemList = new DxfXDataItemList();");
AppendLine();
foreach (var property in properties)
{
AppendLine($"if (primaryStyle.{Name(property)} != modifiedStyle.{Name(property)})");
AppendLine("{");
AppendLine($" itemList.Items.Add(new DxfXDataInteger({Code(property)}));");
AppendLine($" itemList.Items.Add({XDataValueFromProperty(property, "modifiedStyle")});");
AppendLine("}");
AppendLine();
}
AppendLine("return itemList.Items.Count > 0");
AppendLine(" ? new DxfXDataApplicationItemCollection(new DxfXDataString(XDataStyleName), itemList)");
AppendLine(" : null;");
DecreaseIndent();
AppendLine("}");
}
DecreaseIndent();
AppendLine("}"); // end class
DecreaseIndent();
FinishFile();
WriteFile(context, $"{Name(tableItem)}Generated.cs");
}
}
private string XDataValueFromProperty(XElement property, string itemName)
{
var ctor = XDataConstructorFromCode(Code(property));
var writeConverter = WriteConverter(property);
var convertedValue = string.Format(writeConverter, $"{itemName}.{Name(property)}");
return $"new {ctor}({convertedValue})";
}
private static string XDataConstructorFromCode(int code)
{
var expectedType = DxfCodePair.ExpectedType(code);
if (expectedType == typeof(string))
{
return "DxfXDataString";
}
if (expectedType == typeof(double))
{
return "DxfXDataReal";
}
if (expectedType == typeof(short))
{
return "DxfXDataInteger";
}
if (expectedType == typeof(int) ||
expectedType == typeof(long))
{
return "DxfXDataLong";
}
if (expectedType == typeof(bool))
{
return "DxfXDataInteger";
}
throw new NotSupportedException($"Unable to generate XData from code {code}");
}
}
}
| |
using System;
#if ! V1
using System.Collections.Generic;
using IList_ServiceElement = System.Collections.Generic.IList<InTheHand.Net.Bluetooth.ServiceElement>;
using List_ServiceElement = System.Collections.Generic.List<InTheHand.Net.Bluetooth.ServiceElement>;
using IEnumerator_ServiceElement = System.Collections.Generic.IEnumerator<InTheHand.Net.Bluetooth.ServiceElement>;
#else
using System.Collections;
using IList_ServiceElement = System.Collections.IList;
using List_ServiceElement = System.Collections.ArrayList;
using IEnumerator_ServiceElement = System.Collections.IEnumerator;
#endif
using System.Text;
using System.Diagnostics;
using InTheHand.Net.Bluetooth.AttributeIds;
using System.Globalization;
namespace InTheHand.Net.Bluetooth
{
/// <summary>
/// Some useful methods for working with a SDP <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>
/// including creating and accessing the <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// for an RFCOMM service.
/// </summary>
public
#if ! V1
static
#endif
class ServiceRecordHelper
{
#if V1
private ServiceRecordHelper() { }
#endif
//--------------------------------------------------------------
/// <summary>
/// Reads the RFCOMM Channel Number element from the service record.
/// </summary>
/// -
/// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>
/// to search for the element.
/// </param>
/// -
/// <returns>The <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>
/// holding the Channel Number.
/// or <see langword="null"/> if at the <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// attribute is missing or contains invalid elements.
/// </returns>
public static ServiceElement GetRfcommChannelElement(ServiceRecord record)
{
return GetChannelElement(record, BluetoothProtocolDescriptorType.Rfcomm);
}
/// <summary>
/// Reads the L2CAP Channel Number element from the service record.
/// </summary>
/// -
/// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>
/// to search for the element.
/// </param>
/// -
/// <returns>The <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>
/// holding the Channel Number.
/// or <see langword="null"/> if at the <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// attribute is missing or contains invalid elements.
/// </returns>
public static ServiceElement GetL2CapChannelElement(ServiceRecord record)
{
return GetChannelElement(record, BluetoothProtocolDescriptorType.L2Cap);
}
static ServiceElement GetChannelElement(ServiceRecord record, BluetoothProtocolDescriptorType proto)
{
if (!record.Contains(UniversalAttributeId.ProtocolDescriptorList)) {
goto NotFound;
}
ServiceAttribute attr = record.GetAttributeById(UniversalAttributeId.ProtocolDescriptorList);
#if !V1
bool? isSimpleRfcomm;
#else
object isSimpleRfcomm;
#endif
return GetChannelElement(attr, proto, out isSimpleRfcomm);
NotFound:
return null;
}
// TODO GetRfcommChannelElement(ServiceAttribute attr) Could be public -> Tests!
internal static ServiceElement GetChannelElement(ServiceAttribute attr,
BluetoothProtocolDescriptorType proto,
#if !V1
out bool? isSimpleRfcomm
#else
out object isSimpleRfcomm
#endif
)
{
if (proto != BluetoothProtocolDescriptorType.L2Cap
&& proto != BluetoothProtocolDescriptorType.Rfcomm)
throw new ArgumentException("Can only fetch RFCOMM or L2CAP element.");
//
isSimpleRfcomm = true;
Debug.Assert(attr != null, "attr != null");
ServiceElement e0 = attr.Value;
if (e0.ElementType == ElementType.ElementAlternative) {
#if ! WinCE
Trace.WriteLine("Don't support ElementAlternative ProtocolDescriptorList values.");
#endif
goto NotFound;
} else if (e0.ElementType != ElementType.ElementSequence) {
#if ! WinCE
Trace.WriteLine("Bad ProtocolDescriptorList base element.");
#endif
goto NotFound;
}
IList_ServiceElement protoStack = e0.GetValueAsElementList();
IEnumerator_ServiceElement etor = protoStack.GetEnumerator();
ServiceElement layer;
IList_ServiceElement layerContent;
ServiceElement channelElement;
// -- L2CAP Layer --
if (!etor.MoveNext()) {
#if ! WinCE
Trace.WriteLine(string.Format(CultureInfo.InvariantCulture,
"Protocol stack truncated before {0}.", "L2CAP"));
#endif
goto NotFound;
}
layer = (ServiceElement)etor.Current; //cast here are for non-Generic version.
layerContent = layer.GetValueAsElementList();
if (((ServiceElement)layerContent[0]).GetValueAsUuid() != BluetoothService.L2CapProtocol) {
#if ! WinCE
Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
"Bad protocol stack, layer {0} is not {1}.", 1, "L2CAP"));
#endif
goto NotFound;
}
bool hasPsmEtc = layerContent.Count != 1;
// Cast for FX1.1 object
isSimpleRfcomm = (bool)isSimpleRfcomm && !hasPsmEtc;
if (proto == BluetoothProtocolDescriptorType.L2Cap) {
if (layerContent.Count < 2) {
#if ! WinCE
Trace.WriteLine("L2CAP PSM element was requested but the L2CAP layer in this case hasn't a second element.");
#endif
goto NotFound;
}
channelElement = (ServiceElement)layerContent[1];
goto Success;
}
//
// -- RFCOMM Layer --
if (!etor.MoveNext()) {
#if ! WinCE
Trace.WriteLine(string.Format(CultureInfo.InvariantCulture,
"Protocol stack truncated before {0}.", "RFCOMM"));
#endif
goto NotFound;
}
layer = (ServiceElement)etor.Current;
layerContent = layer.GetValueAsElementList();
if (((ServiceElement)layerContent[0]).GetValueAsUuid() != BluetoothService.RFCommProtocol) {
#if ! WinCE
Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
"Bad protocol stack, layer {0} is not {1}.", 2, "RFCOMM"));
#endif
goto NotFound;
}
//
if (layerContent.Count < 2) {
#if ! WinCE
Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
"Bad protocol stack, layer {0} hasn't a second element.", 2));
#endif
goto NotFound;
}
channelElement = (ServiceElement)layerContent[1];
if (channelElement.ElementType != ElementType.UInt8) {
#if ! WinCE
Trace.WriteLine(String.Format(CultureInfo.InvariantCulture,
"Bad protocol stack, layer {0} is not UInt8.", 2));
#endif
goto NotFound;
}
// Success
//
// -- Any remaining layer(s) --
bool extraLayers = etor.MoveNext();
isSimpleRfcomm = (bool)isSimpleRfcomm && !extraLayers;
Success:
//
return channelElement;
NotFound:
isSimpleRfcomm = null;
return null;
}
/// <summary>
/// Reads the RFCOMM Channel Number value from the service record,
/// or returns -1 if the element is not present.
/// </summary>
/// -
/// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>
/// to search for the element.
/// </param>
/// -
/// <returns>The Channel Number as an unsigned byte cast to an Int32,
/// or -1 if at the <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// attribute is missing or contains invalid elements.
/// </returns>
public static Int32 GetRfcommChannelNumber(ServiceRecord record)
{
ServiceElement channelElement = GetRfcommChannelElement(record);
if (channelElement == null) {
return -1;
}
return GetRfcommChannelNumber(channelElement);
}
internal static Int32 GetRfcommChannelNumber(ServiceElement channelElement)
{
Debug.Assert(channelElement != null, "channelElement != null");
System.Diagnostics.Debug.Assert(channelElement.ElementType == ElementType.UInt8);
byte value = (byte)channelElement.Value;
return value;
}
/// <summary>
/// Reads the L2CAP Channel Number value from the service record,
/// or returns -1 if the element is not present.
/// </summary>
/// -
/// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>
/// to search for the element.
/// </param>
/// -
/// <returns>The PSM number as an uint16 cast to an Int32,
/// or -1 if at the <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// attribute is missing or contains invalid elements.
/// </returns>
public static Int32 GetL2CapChannelNumber(ServiceRecord record)
{
ServiceElement channelElement = GetL2CapChannelElement(record);
if (channelElement == null) {
return -1;
}
return GetL2CapChannelNumber(channelElement);
}
internal static Int32 GetL2CapChannelNumber(ServiceElement channelElement)
{
Debug.Assert(channelElement != null, "channelElement != null");
System.Diagnostics.Debug.Assert(channelElement.ElementType == ElementType.UInt16);
var value = (UInt16)channelElement.Value;
return value;
}
/// <summary>
/// Sets the RFCOMM Channel Number value in the service record.
/// </summary>
/// -
/// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>
/// in which to set the RFCOMM Channel number.
/// </param>
/// <param name="channelNumber">The Channel number to set in the record.
/// </param>
/// -
/// <exception cref="T:System.InvalidOperationException">The
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// attribute is missing or contains invalid elements.
/// </exception>
public static void SetRfcommChannelNumber(ServiceRecord record, Byte channelNumber)
{
ServiceElement channelElement = GetRfcommChannelElement(record);
if (channelElement == null) {
throw new InvalidOperationException("ProtocolDescriptorList element does not exist or is not in the RFCOMM format.");
}
System.Diagnostics.Debug.Assert(channelElement.ElementType == ElementType.UInt8);
channelElement.SetValue(channelNumber);
}
/// <summary>
/// Sets the RFCOMM Channel Number value in the service record.
/// </summary>
/// -
/// <remarks>
/// <para>Note: We use an <see cref="T:System.Int32"/> for the
/// <paramref name="psm"/> parameter as its natural type <see cref="T:System.UInt16"/>
/// in not usable in CLS Compliant interfaces.
/// </para>
/// </remarks>
/// -
/// <param name="record">The <see cref="T:InTheHand.Net.Bluetooth.ServiceRecord"/>
/// in which to set the L2CAP PSM value.
/// </param>
/// <param name="psm">The PSM value to set in the record.
/// Note that although the parameter is of type <see cref="T:System.Int32"/>
/// the value must actually be in the range of a <see cref="T:System.UInt16"/>,
/// see the remarks for more information.
/// </param>
/// -
/// <exception cref="T:System.InvalidOperationException">The
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// attribute is missing or contains invalid elements.
/// </exception>
/// <exception cref="T:System.ArgumentOutOfRangeException">
/// The PSM must fit in a 16-bit unsigned integer.
/// </exception>
public static void SetL2CapPsmNumber(ServiceRecord record, int psm)
{
if (psm < 0 || psm > UInt16.MaxValue)
throw new ArgumentOutOfRangeException("psm", "A PSM is a UInt16 value.");
var psm16 = checked((UInt16)psm);
ServiceElement rfcommElement = GetRfcommChannelElement(record);
if (rfcommElement != null) {
Debug.WriteLine("Setting L2CAP PSM for a PDL that includes RFCOMM.");
}
ServiceElement channelElement = GetChannelElement(record, BluetoothProtocolDescriptorType.L2Cap);
if (channelElement == null
|| channelElement.ElementType != ElementType.UInt16) {
throw new InvalidOperationException("ProtocolDescriptorList element does not exist, is not in the L2CAP format, or it the L2CAP layer has no PSM element.");
}
channelElement.SetValue(psm16);
}
//--------------------------------------------------------------
/// <summary>
/// Creates the data element for the
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// attribute in an L2CAP service
/// </summary>
/// -
/// <returns>The new <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.</returns>
/// -
/// <remarks>Thus is the following structure:
/// <code lang="none">
/// ElementSequence
/// ElementSequence
/// Uuid16 = L2CAP
/// UInt16 = 0 -- The L2CAP PSM Number.
/// </code>
/// </remarks>
public static ServiceElement CreateL2CapProtocolDescriptorList()
{
return CreateL2CapProtocolDescriptorListWithUpperLayers();
}
/// <summary>
/// Creates the data element for the
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// attribute in an RFCOMM service
/// </summary>
/// -
/// <returns>The new <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.</returns>
/// -
/// <remarks>Thus is the following structure:
/// <code lang="none">
/// ElementSequence
/// ElementSequence
/// Uuid16 = L2CAP
/// ElementSequence
/// Uuid16 = RFCOMM
/// UInt8 = 0 -- The RFCOMM Channel Number.
/// </code>
/// </remarks>
public static ServiceElement CreateRfcommProtocolDescriptorList()
{
return CreateRfcommProtocolDescriptorListWithUpperLayers();
}
/// <summary>
/// Creates the data element for the
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// attribute in an GOEP (i.e. OBEX) service
/// </summary>
/// -
/// <returns>The new <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.</returns>
/// -
/// <remarks>Thus is the following structure:
/// <code lang="none">
/// ElementSequence
/// ElementSequence
/// Uuid16 = L2CAP
/// ElementSequence
/// Uuid16 = RFCOMM
/// UInt8 = 0 -- The RFCOMM Channel Number.
/// ElementSequence
/// Uuid16 = GOEP
/// </code>
/// </remarks>
public static ServiceElement CreateGoepProtocolDescriptorList()
{
return CreateRfcommProtocolDescriptorListWithUpperLayers(
CreatePdlLayer((UInt16)ServiceRecordUtilities.HackProtocolId.Obex));
}
private static ServiceElement CreateRfcommProtocolDescriptorListWithUpperLayers(params ServiceElement[] upperLayers)
{
IList_ServiceElement baseChildren = new List_ServiceElement();
baseChildren.Add(CreatePdlLayer((UInt16)ServiceRecordUtilities.HackProtocolId.L2Cap));
baseChildren.Add(CreatePdlLayer((UInt16)ServiceRecordUtilities.HackProtocolId.Rfcomm,
new ServiceElement(ElementType.UInt8, (byte)0)));
foreach (ServiceElement nextLayer in upperLayers) {
if (nextLayer.ElementType != ElementType.ElementSequence) {
throw new ArgumentException("Each layer in a ProtocolDescriptorList must be an ElementSequence.");
}
baseChildren.Add(nextLayer);
}//for
ServiceElement baseElement = new ServiceElement(ElementType.ElementSequence, baseChildren);
return baseElement;
}
/// <summary>
/// Creates the data element for the
/// <see cref="F:InTheHand.Net.Bluetooth.AttributeIds.UniversalAttributeId.ProtocolDescriptorList"/>
/// attribute in an L2CAP service,
/// with upper layer entries.
/// </summary>
/// -
/// <returns>The new <see cref="T:InTheHand.Net.Bluetooth.ServiceElement"/>.</returns>
/// -
/// <remarks>Thus is the following structure at the first layer:
/// <code lang="none">
/// ElementSequence
/// ElementSequence
/// Uuid16 = L2CAP
/// UInt16 = 0 -- The L2CAP PSM Number.
/// </code>
/// One can add layers above that; remember that all layers are formed
/// of an ElementSequence. See the example below.
/// </remarks>
/// -
/// <example>
/// <code>
/// var netProtoList = new ServiceElement(ElementType.ElementSequence,
/// ServiceElement.CreateNumericalServiceElement(ElementType.UInt16, 0x0800),
/// ServiceElement.CreateNumericalServiceElement(ElementType.UInt16, 0x0806)
/// );
/// var layer1 = new ServiceElement(ElementType.ElementSequence,
/// new ServiceElement(ElementType.Uuid16, Uuid16_BnepProto),
/// ServiceElement.CreateNumericalServiceElement(ElementType.UInt16, 0x0100), //v1.0
/// netProtoList
/// );
/// ServiceElement element = ServiceRecordHelper.CreateL2CapProtocolDescriptorListWithUpperLayers(
/// layer1);
/// </code>
/// </example>
/// -
/// <param name="upperLayers">The list of upper layer elements, one per layer.
/// As an array.
/// </param>
public static ServiceElement CreateL2CapProtocolDescriptorListWithUpperLayers(params ServiceElement[] upperLayers)
{
IList_ServiceElement baseChildren = new List_ServiceElement();
baseChildren.Add(CreatePdlLayer((UInt16)ServiceRecordUtilities.HackProtocolId.L2Cap,
new ServiceElement(ElementType.UInt16, (UInt16)0)));
foreach (ServiceElement nextLayer in upperLayers) {
if (nextLayer.ElementType != ElementType.ElementSequence) {
throw new ArgumentException("Each layer in a ProtocolDescriptorList must be an ElementSequence.");
}
baseChildren.Add(nextLayer);
}//for
ServiceElement baseElement = new ServiceElement(ElementType.ElementSequence, baseChildren);
return baseElement;
}
private static ServiceElement CreatePdlLayer(UInt16 uuid, params ServiceElement[] data)
{
IList_ServiceElement curSeqChildren;
ServiceElement curValueElmt, curSeqElmt;
//
curSeqChildren = new List_ServiceElement();
curValueElmt = new ServiceElement(ElementType.Uuid16, uuid);
curSeqChildren.Add(curValueElmt);
foreach (ServiceElement element in data) {
curSeqChildren.Add(element);
}
curSeqElmt = new ServiceElement(ElementType.ElementSequence, curSeqChildren);
return curSeqElmt;
}
//--------------------------------------------------------------
internal
static Guid _GetPrimaryServiceClassId(ServiceRecord sr)
{
var a = sr.GetAttributeById(UniversalAttributeId.ServiceClassIdList);
var eL = a.Value;
var eClassList = eL.GetValueAsElementList();
var e0 = eClassList[0];
var classId = e0.GetValueAsUuid();
return classId;
}
}//class
}
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.ObjectModel;
using System.Reflection;
using System.Runtime.CompilerServices;
namespace System.Linq.Expressions
{
public partial class Expression
{
internal class BinaryExpressionProxy
{
private readonly BinaryExpression _node;
public BinaryExpressionProxy(BinaryExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public LambdaExpression Conversion { get { return _node.Conversion; } }
public String DebugView { get { return _node.DebugView; } }
public Boolean IsLifted { get { return _node.IsLifted; } }
public Boolean IsLiftedToNull { get { return _node.IsLiftedToNull; } }
public Expression Left { get { return _node.Left; } }
public MethodInfo Method { get { return _node.Method; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Expression Right { get { return _node.Right; } }
public Type Type { get { return _node.Type; } }
}
internal class BlockExpressionProxy
{
private readonly BlockExpression _node;
public BlockExpressionProxy(BlockExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public ReadOnlyCollection<Expression> Expressions { get { return _node.Expressions; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Expression Result { get { return _node.Result; } }
public Type Type { get { return _node.Type; } }
public ReadOnlyCollection<ParameterExpression> Variables { get { return _node.Variables; } }
}
internal class CatchBlockProxy
{
private readonly CatchBlock _node;
public CatchBlockProxy(CatchBlock node)
{
_node = node;
}
public Expression Body { get { return _node.Body; } }
public Expression Filter { get { return _node.Filter; } }
public Type Test { get { return _node.Test; } }
public ParameterExpression Variable { get { return _node.Variable; } }
}
internal class ConditionalExpressionProxy
{
private readonly ConditionalExpression _node;
public ConditionalExpressionProxy(ConditionalExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public Expression IfFalse { get { return _node.IfFalse; } }
public Expression IfTrue { get { return _node.IfTrue; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Expression Test { get { return _node.Test; } }
public Type Type { get { return _node.Type; } }
}
internal class ConstantExpressionProxy
{
private readonly ConstantExpression _node;
public ConstantExpressionProxy(ConstantExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
public Object Value { get { return _node.Value; } }
}
internal class DebugInfoExpressionProxy
{
private readonly DebugInfoExpression _node;
public DebugInfoExpressionProxy(DebugInfoExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public SymbolDocumentInfo Document { get { return _node.Document; } }
public Int32 EndColumn { get { return _node.EndColumn; } }
public Int32 EndLine { get { return _node.EndLine; } }
public Boolean IsClear { get { return _node.IsClear; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Int32 StartColumn { get { return _node.StartColumn; } }
public Int32 StartLine { get { return _node.StartLine; } }
public Type Type { get { return _node.Type; } }
}
internal class DefaultExpressionProxy
{
private readonly DefaultExpression _node;
public DefaultExpressionProxy(DefaultExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
}
internal class GotoExpressionProxy
{
private readonly GotoExpression _node;
public GotoExpressionProxy(GotoExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public GotoExpressionKind Kind { get { return _node.Kind; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public LabelTarget Target { get { return _node.Target; } }
public Type Type { get { return _node.Type; } }
public Expression Value { get { return _node.Value; } }
}
internal class IndexExpressionProxy
{
private readonly IndexExpression _node;
public IndexExpressionProxy(IndexExpression node)
{
_node = node;
}
public ReadOnlyCollection<Expression> Arguments { get { return _node.Arguments; } }
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public PropertyInfo Indexer { get { return _node.Indexer; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Expression Object { get { return _node.Object; } }
public Type Type { get { return _node.Type; } }
}
internal class InvocationExpressionProxy
{
private readonly InvocationExpression _node;
public InvocationExpressionProxy(InvocationExpression node)
{
_node = node;
}
public ReadOnlyCollection<Expression> Arguments { get { return _node.Arguments; } }
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public Expression Expression { get { return _node.Expression; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
}
internal class LabelExpressionProxy
{
private readonly LabelExpression _node;
public LabelExpressionProxy(LabelExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public Expression DefaultValue { get { return _node.DefaultValue; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public LabelTarget Target { get { return _node.Target; } }
public Type Type { get { return _node.Type; } }
}
internal class LambdaExpressionProxy
{
private readonly LambdaExpression _node;
public LambdaExpressionProxy(LambdaExpression node)
{
_node = node;
}
public Expression Body { get { return _node.Body; } }
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public String Name { get { return _node.Name; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public ReadOnlyCollection<ParameterExpression> Parameters { get { return _node.Parameters; } }
public Type ReturnType { get { return _node.ReturnType; } }
public Boolean TailCall { get { return _node.TailCall; } }
public Type Type { get { return _node.Type; } }
}
internal class ListInitExpressionProxy
{
private readonly ListInitExpression _node;
public ListInitExpressionProxy(ListInitExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public ReadOnlyCollection<ElementInit> Initializers { get { return _node.Initializers; } }
public NewExpression NewExpression { get { return _node.NewExpression; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
}
internal class LoopExpressionProxy
{
private readonly LoopExpression _node;
public LoopExpressionProxy(LoopExpression node)
{
_node = node;
}
public Expression Body { get { return _node.Body; } }
public LabelTarget BreakLabel { get { return _node.BreakLabel; } }
public Boolean CanReduce { get { return _node.CanReduce; } }
public LabelTarget ContinueLabel { get { return _node.ContinueLabel; } }
public String DebugView { get { return _node.DebugView; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
}
internal class MemberExpressionProxy
{
private readonly MemberExpression _node;
public MemberExpressionProxy(MemberExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public Expression Expression { get { return _node.Expression; } }
public MemberInfo Member { get { return _node.Member; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
}
internal class MemberInitExpressionProxy
{
private readonly MemberInitExpression _node;
public MemberInitExpressionProxy(MemberInitExpression node)
{
_node = node;
}
public ReadOnlyCollection<MemberBinding> Bindings { get { return _node.Bindings; } }
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public NewExpression NewExpression { get { return _node.NewExpression; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
}
internal class MethodCallExpressionProxy
{
private readonly MethodCallExpression _node;
public MethodCallExpressionProxy(MethodCallExpression node)
{
_node = node;
}
public ReadOnlyCollection<Expression> Arguments { get { return _node.Arguments; } }
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public MethodInfo Method { get { return _node.Method; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Expression Object { get { return _node.Object; } }
public Type Type { get { return _node.Type; } }
}
internal class NewArrayExpressionProxy
{
private readonly NewArrayExpression _node;
public NewArrayExpressionProxy(NewArrayExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public ReadOnlyCollection<Expression> Expressions { get { return _node.Expressions; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
}
internal class NewExpressionProxy
{
private readonly NewExpression _node;
public NewExpressionProxy(NewExpression node)
{
_node = node;
}
public ReadOnlyCollection<Expression> Arguments { get { return _node.Arguments; } }
public Boolean CanReduce { get { return _node.CanReduce; } }
public ConstructorInfo Constructor { get { return _node.Constructor; } }
public String DebugView { get { return _node.DebugView; } }
public ReadOnlyCollection<MemberInfo> Members { get { return _node.Members; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
}
internal class ParameterExpressionProxy
{
private readonly ParameterExpression _node;
public ParameterExpressionProxy(ParameterExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public Boolean IsByRef { get { return _node.IsByRef; } }
public String Name { get { return _node.Name; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
}
internal class RuntimeVariablesExpressionProxy
{
private readonly RuntimeVariablesExpression _node;
public RuntimeVariablesExpressionProxy(RuntimeVariablesExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
public ReadOnlyCollection<ParameterExpression> Variables { get { return _node.Variables; } }
}
internal class SwitchCaseProxy
{
private readonly SwitchCase _node;
public SwitchCaseProxy(SwitchCase node)
{
_node = node;
}
public Expression Body { get { return _node.Body; } }
public ReadOnlyCollection<Expression> TestValues { get { return _node.TestValues; } }
}
internal class SwitchExpressionProxy
{
private readonly SwitchExpression _node;
public SwitchExpressionProxy(SwitchExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public ReadOnlyCollection<SwitchCase> Cases { get { return _node.Cases; } }
public MethodInfo Comparison { get { return _node.Comparison; } }
public String DebugView { get { return _node.DebugView; } }
public Expression DefaultBody { get { return _node.DefaultBody; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Expression SwitchValue { get { return _node.SwitchValue; } }
public Type Type { get { return _node.Type; } }
}
internal class TryExpressionProxy
{
private readonly TryExpression _node;
public TryExpressionProxy(TryExpression node)
{
_node = node;
}
public Expression Body { get { return _node.Body; } }
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public Expression Fault { get { return _node.Fault; } }
public Expression Finally { get { return _node.Finally; } }
public ReadOnlyCollection<CatchBlock> Handlers { get { return _node.Handlers; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
}
internal class TypeBinaryExpressionProxy
{
private readonly TypeBinaryExpression _node;
public TypeBinaryExpressionProxy(TypeBinaryExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public Expression Expression { get { return _node.Expression; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Type Type { get { return _node.Type; } }
public Type TypeOperand { get { return _node.TypeOperand; } }
}
internal class UnaryExpressionProxy
{
private readonly UnaryExpression _node;
public UnaryExpressionProxy(UnaryExpression node)
{
_node = node;
}
public Boolean CanReduce { get { return _node.CanReduce; } }
public String DebugView { get { return _node.DebugView; } }
public Boolean IsLifted { get { return _node.IsLifted; } }
public Boolean IsLiftedToNull { get { return _node.IsLiftedToNull; } }
public MethodInfo Method { get { return _node.Method; } }
public ExpressionType NodeType { get { return _node.NodeType; } }
public Expression Operand { get { return _node.Operand; } }
public Type Type { get { return _node.Type; } }
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace ColourList.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);
}
}
}
}
| |
// (c) Copyright Esri, 2010 - 2013
// This source is subject to the Apache 2.0 License.
// Please see http://www.apache.org/licenses/LICENSE-2.0.html for details.
// All other rights reserved.
using System;
using System.Collections.Generic;
using System.Text;
using System.Linq;
using System.Runtime.InteropServices;
using System.Resources;
using ESRI.ArcGIS.Geoprocessing;
using ESRI.ArcGIS.Geometry;
using ESRI.ArcGIS.Geodatabase;
using ESRI.ArcGIS.esriSystem;
using System.Xml.Serialization;
using ESRI.ArcGIS.DataSourcesFile;
using System.Globalization;
using System.Collections;
using ESRI.ArcGIS.Display;
using ESRI.ArcGIS.OSM.OSMClassExtension;
using ESRI.ArcGIS.OSM.OSMUtilities;
namespace ESRI.ArcGIS.OSM.GeoProcessing
{
[Guid("86211e63-2dbb-4d56-95ca-25b3d2a0a0ac")]
[ClassInterface(ClassInterfaceType.None)]
[ProgId("OSMEditor.OSMGPFileLoader")]
public class OSMGPFileLoader : ESRI.ArcGIS.Geoprocessing.IGPFunction2
{
Dictionary<string, OSMToolHelper.simplePointRef> osmNodeDictionary = null;
string m_DisplayName = String.Empty;
int in_osmFileNumber, in_conserveMemoryNumber, in_attributeSelector, out_targetDatasetNumber, out_osmPointsNumber, out_osmLinesNumber, out_osmPolygonsNumber, out_RelationTableNumber, out_RevTableNumber;
ResourceManager resourceManager = null;
OSMGPFactory osmGPFactory = null;
Dictionary<string, string> m_editorConfigurationSettings = null;
public OSMGPFileLoader()
{
resourceManager = new ResourceManager("ESRI.ArcGIS.OSM.GeoProcessing.OSMGPToolsStrings", this.GetType().Assembly);
osmGPFactory = new OSMGPFactory();
m_editorConfigurationSettings = OSMGPFactory.ReadOSMEditorSettings();
}
#region "IGPFunction2 Implementations"
public ESRI.ArcGIS.esriSystem.UID DialogCLSID
{
get
{
return null;
}
}
public string DisplayName
{
get
{
if (String.IsNullOrEmpty(m_DisplayName))
{
m_DisplayName = osmGPFactory.GetFunctionName(OSMGPFactory.m_FileLoaderName).DisplayName;
}
return m_DisplayName;
}
}
public void Execute(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.esriSystem.ITrackCancel TrackCancel, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr, ESRI.ArcGIS.Geodatabase.IGPMessages message)
{
IFeatureClass osmPointFeatureClass = null;
IFeatureClass osmLineFeatureClass = null;
IFeatureClass osmPolygonFeatureClass = null;
OSMToolHelper osmToolHelper = null;
try
{
DateTime syncTime = DateTime.Now;
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
osmToolHelper = new OSMToolHelper();
if (TrackCancel == null)
{
TrackCancel = new CancelTrackerClass();
}
IGPParameter osmFileParameter = paramvalues.get_Element(in_osmFileNumber) as IGPParameter;
IGPValue osmFileLocationString = gpUtilities3.UnpackGPValue(osmFileParameter) as IGPValue;
// ensure that the specified file does exist
bool osmFileExists = false;
try
{
osmFileExists = System.IO.File.Exists(osmFileLocationString.GetAsText());
}
catch (Exception ex)
{
message.AddError(120029, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_problemaccessingfile"), ex.Message));
return;
}
if (osmFileExists == false)
{
message.AddError(120030, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_osmfiledoesnotexist"), osmFileLocationString.GetAsText()));
return;
}
IGPParameter conserveMemoryParameter = paramvalues.get_Element(in_conserveMemoryNumber) as IGPParameter;
IGPBoolean conserveMemoryGPValue = gpUtilities3.UnpackGPValue(conserveMemoryParameter) as IGPBoolean;
if (conserveMemoryGPValue == null)
{
message.AddError(120031, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), conserveMemoryParameter.Name));
return;
}
message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_countingNodes"));
long nodeCapacity = 0;
long wayCapacity = 0;
long relationCapacity = 0;
Dictionary<esriGeometryType, List<string>> attributeTags = new Dictionary<esriGeometryType, List<string>>();
IGPParameter tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter;
IGPMultiValue tagCollectionGPValue = gpUtilities3.UnpackGPValue(tagCollectionParameter) as IGPMultiValue;
List<String> tagstoExtract = null;
if (tagCollectionGPValue.Count > 0)
{
tagstoExtract = new List<string>();
for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++)
{
string nameOfTag = tagCollectionGPValue.get_Value(valueIndex).GetAsText();
if (nameOfTag.ToUpper().Equals("ALL"))
{
tagstoExtract = new List<string>();
break;
}
else
{
tagstoExtract.Add(nameOfTag);
}
}
}
// if there is an "ALL" keyword then we scan for all tags, otherwise we only add the desired tags to the feature classes and do a 'quick'
// count scan
if (tagstoExtract != null)
{
if (tagstoExtract.Count > 0)
{
// if the number of tags is > 0 then do a simple feature count and take name tags names from the gp value
osmToolHelper.countOSMStuff(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel);
attributeTags.Add(esriGeometryType.esriGeometryPoint, tagstoExtract);
attributeTags.Add(esriGeometryType.esriGeometryPolyline, tagstoExtract);
attributeTags.Add(esriGeometryType.esriGeometryPolygon, tagstoExtract);
}
else
{
// the count should be zero if we encountered the "ALL" keyword
// in this case count the features and create a list of unique tags
attributeTags = osmToolHelper.countOSMCapacityAndTags(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel);
}
}
else
{
// no tags we defined, hence we do a simple count and create an empty list indicating that no additional fields
// need to be created
osmToolHelper.countOSMStuff(osmFileLocationString.GetAsText(), ref nodeCapacity, ref wayCapacity, ref relationCapacity, ref TrackCancel);
attributeTags.Add(esriGeometryType.esriGeometryPoint, new List<string>());
attributeTags.Add(esriGeometryType.esriGeometryPolyline, new List<string>());
attributeTags.Add(esriGeometryType.esriGeometryPolygon, new List<string>());
}
if (nodeCapacity == 0 && wayCapacity == 0 && relationCapacity == 0)
{
return;
}
if (conserveMemoryGPValue.Value == false)
{
osmNodeDictionary = new Dictionary<string, OSMToolHelper.simplePointRef>(Convert.ToInt32(nodeCapacity));
}
message.AddMessage(String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_countedElements"), nodeCapacity, wayCapacity, relationCapacity));
// prepare the feature dataset and classes
IGPParameter targetDatasetParameter = paramvalues.get_Element(out_targetDatasetNumber) as IGPParameter;
IGPValue targetDatasetGPValue = gpUtilities3.UnpackGPValue(targetDatasetParameter);
IDEDataset2 targetDEDataset2 = targetDatasetGPValue as IDEDataset2;
if (targetDEDataset2 == null)
{
message.AddError(120048, string.Format(resourceManager.GetString("GPTools_NullPointerParameterType"), targetDatasetParameter.Name));
return;
}
string targetDatasetName = ((IGPValue)targetDEDataset2).GetAsText();
IDataElement targetDataElement = targetDEDataset2 as IDataElement;
IDataset targetDataset = gpUtilities3.OpenDatasetFromLocation(targetDataElement.CatalogPath);
IName parentName = null;
try
{
parentName = gpUtilities3.CreateParentFromCatalogPath(targetDataElement.CatalogPath);
}
catch
{
message.AddError(120033, resourceManager.GetString("GPTools_OSMGPFileReader_unable_to_create_fd"));
return;
}
// test if the feature classes already exists,
// if they do and the environments settings are such that an overwrite is not allowed we need to abort at this point
IGeoProcessorSettings gpSettings = (IGeoProcessorSettings)envMgr;
if (gpSettings.OverwriteOutput == true)
{
}
else
{
if (gpUtilities3.Exists((IGPValue)targetDEDataset2) == true)
{
message.AddError(120032, String.Format(resourceManager.GetString("GPTools_OSMGPFileReader_basenamealreadyexists"), targetDataElement.Name));
return;
}
}
// load the descriptions from which to derive the domain values
OSMDomains availableDomains = null;
// Reading the XML document requires a FileStream.
System.Xml.XmlTextReader reader = null;
string xmlDomainFile = "";
m_editorConfigurationSettings.TryGetValue("osmdomainsfilepath", out xmlDomainFile);
if (System.IO.File.Exists(xmlDomainFile))
{
reader = new System.Xml.XmlTextReader(xmlDomainFile);
}
if (reader == null)
{
message.AddError(120033, resourceManager.GetString("GPTools_OSMGPDownload_NoDomainConfigFile"));
return;
}
System.Xml.Serialization.XmlSerializer domainSerializer = null;
try
{
domainSerializer = new XmlSerializer(typeof(OSMDomains));
availableDomains = domainSerializer.Deserialize(reader) as OSMDomains;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
System.Diagnostics.Debug.WriteLine(ex.StackTrace);
message.AddError(120034, ex.Message);
return;
}
reader.Close();
message.AddMessage(resourceManager.GetString("GPTools_preparedb"));
Dictionary<string, IDomain> codedValueDomains = new Dictionary<string, IDomain>();
foreach (var domain in availableDomains.domain)
{
ICodedValueDomain pointCodedValueDomain = new CodedValueDomainClass();
((IDomain)pointCodedValueDomain).Name = domain.name + "_pt";
((IDomain)pointCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString;
ICodedValueDomain lineCodedValueDomain = new CodedValueDomainClass();
((IDomain)lineCodedValueDomain).Name = domain.name + "_ln";
((IDomain)lineCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString;
ICodedValueDomain polygonCodedValueDomain = new CodedValueDomainClass();
((IDomain)polygonCodedValueDomain).Name = domain.name + "_ply";
((IDomain)polygonCodedValueDomain).FieldType = esriFieldType.esriFieldTypeString;
for (int i = 0; i < domain.domainvalue.Length; i++)
{
for (int domainGeometryIndex = 0; domainGeometryIndex < domain.domainvalue[i].geometrytype.Length; domainGeometryIndex++)
{
switch (domain.domainvalue[i].geometrytype[domainGeometryIndex])
{
case geometrytype.point:
pointCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value);
break;
case geometrytype.line:
lineCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value);
break;
case geometrytype.polygon:
polygonCodedValueDomain.AddCode(domain.domainvalue[i].value, domain.domainvalue[i].value);
break;
default:
break;
}
}
}
// add the domain tables to the domains collection
codedValueDomains.Add(((IDomain)pointCodedValueDomain).Name, (IDomain)pointCodedValueDomain);
codedValueDomains.Add(((IDomain)lineCodedValueDomain).Name, (IDomain)lineCodedValueDomain);
codedValueDomains.Add(((IDomain)polygonCodedValueDomain).Name, (IDomain)polygonCodedValueDomain);
}
IWorkspaceDomains workspaceDomain = null;
IFeatureWorkspace featureWorkspace = null;
// if the target dataset already exists we can go ahead and QI to it directly
if (targetDataset != null)
{
workspaceDomain = targetDataset.Workspace as IWorkspaceDomains;
featureWorkspace = targetDataset.Workspace as IFeatureWorkspace;
}
else
{
// in case it doesn't exist yet we will open the parent (the workspace - geodatabase- itself) and
// use it as a reference to create the feature dataset and the feature classes in it.
IWorkspace newWorkspace = ((IName)parentName).Open() as IWorkspace;
workspaceDomain = newWorkspace as IWorkspaceDomains;
featureWorkspace = newWorkspace as IFeatureWorkspace;
}
foreach (var domain in codedValueDomains.Values)
{
IDomain testDomain = null;
try
{
testDomain = workspaceDomain.get_DomainByName(domain.Name);
}
catch { }
if (testDomain == null)
{
workspaceDomain.AddDomain(domain);
}
}
// this determines the spatial reference as defined from the gp environment settings and the initial wgs84 SR
ISpatialReferenceFactory spatialReferenceFactory = new SpatialReferenceEnvironmentClass() as ISpatialReferenceFactory;
ISpatialReference wgs84 = spatialReferenceFactory.CreateGeographicCoordinateSystem((int)esriSRGeoCSType.esriSRGeoCS_WGS1984) as ISpatialReference;
ISpatialReference downloadSpatialReference = gpUtilities3.GetGPSpRefEnv(envMgr, wgs84, null, 0, 0, 0, 0, null);
Marshal.ReleaseComObject(wgs84);
Marshal.ReleaseComObject(spatialReferenceFactory);
IGPEnvironment configKeyword = OSMGPDownload.getEnvironment(envMgr, "configKeyword");
IGPString gpString = configKeyword.Value as IGPString;
string storageKeyword = String.Empty;
if (gpString != null)
{
storageKeyword = gpString.Value;
}
IFeatureDataset targetFeatureDataset = null;
if (gpUtilities3.Exists((IGPValue)targetDEDataset2))
{
targetFeatureDataset = gpUtilities3.OpenDataset((IGPValue)targetDEDataset2) as IFeatureDataset;
}
else
{
targetFeatureDataset = featureWorkspace.CreateFeatureDataset(targetDataElement.Name, downloadSpatialReference);
}
downloadSpatialReference = ((IGeoDataset)targetFeatureDataset).SpatialReference;
string metadataAbstract = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_abstract");
string metadataPurpose = resourceManager.GetString("GPTools_OSMGPFileReader_metadata_purpose");
// assign the custom class extension for use with the OSM feature inspector
UID osmClassUID = new UIDClass();
osmClassUID.Value = "{65CA4847-8661-45eb-8E1E-B2985CA17C78}";
// points
try
{
osmPointFeatureClass = osmToolHelper.CreatePointFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_pt", null, null, null, storageKeyword, availableDomains, metadataAbstract, metadataPurpose, attributeTags[esriGeometryType.esriGeometryPoint]);
}
catch (Exception ex)
{
message.AddError(120035, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpointfeatureclass"), ex.Message));
return;
}
if (osmPointFeatureClass == null)
{
return;
}
// change the property set of the osm class extension to skip any change detection during the initial data load
osmPointFeatureClass.RemoveOSMClassExtension();
int osmPointIDFieldIndex = osmPointFeatureClass.FindField("OSMID");
Dictionary<string, int> osmPointDomainAttributeFieldIndices = new Dictionary<string, int>();
foreach (var domains in availableDomains.domain)
{
int currentFieldIndex = osmPointFeatureClass.FindField(domains.name);
if (currentFieldIndex != -1)
{
osmPointDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
}
}
int tagCollectionPointFieldIndex = osmPointFeatureClass.FindField("osmTags");
int osmUserPointFieldIndex = osmPointFeatureClass.FindField("osmuser");
int osmUIDPointFieldIndex = osmPointFeatureClass.FindField("osmuid");
int osmVisiblePointFieldIndex = osmPointFeatureClass.FindField("osmvisible");
int osmVersionPointFieldIndex = osmPointFeatureClass.FindField("osmversion");
int osmChangesetPointFieldIndex = osmPointFeatureClass.FindField("osmchangeset");
int osmTimeStampPointFieldIndex = osmPointFeatureClass.FindField("osmtimestamp");
int osmMemberOfPointFieldIndex = osmPointFeatureClass.FindField("osmMemberOf");
int osmSupportingElementPointFieldIndex = osmPointFeatureClass.FindField("osmSupportingElement");
int osmWayRefCountFieldIndex = osmPointFeatureClass.FindField("wayRefCount");
// lines
try
{
osmLineFeatureClass = osmToolHelper.CreateLineFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_ln", null, null, null, storageKeyword, availableDomains, metadataAbstract, metadataPurpose, attributeTags[esriGeometryType.esriGeometryPolyline]);
}
catch (Exception ex)
{
message.AddError(120036, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nulllinefeatureclass"), ex.Message));
return;
}
if (osmLineFeatureClass == null)
{
return;
}
// change the property set of the osm class extension to skip any change detection during the initial data load
osmLineFeatureClass.RemoveOSMClassExtension();
int osmLineIDFieldIndex = osmLineFeatureClass.FindField("OSMID");
Dictionary<string, int> osmLineDomainAttributeFieldIndices = new Dictionary<string, int>();
foreach (var domains in availableDomains.domain)
{
int currentFieldIndex = osmLineFeatureClass.FindField(domains.name);
if (currentFieldIndex != -1)
{
osmLineDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
}
}
int tagCollectionPolylineFieldIndex = osmLineFeatureClass.FindField("osmTags");
int osmUserPolylineFieldIndex = osmLineFeatureClass.FindField("osmuser");
int osmUIDPolylineFieldIndex = osmLineFeatureClass.FindField("osmuid");
int osmVisiblePolylineFieldIndex = osmLineFeatureClass.FindField("osmvisible");
int osmVersionPolylineFieldIndex = osmLineFeatureClass.FindField("osmversion");
int osmChangesetPolylineFieldIndex = osmLineFeatureClass.FindField("osmchangeset");
int osmTimeStampPolylineFieldIndex = osmLineFeatureClass.FindField("osmtimestamp");
int osmMemberOfPolylineFieldIndex = osmLineFeatureClass.FindField("osmMemberOf");
int osmMembersPolylineFieldIndex = osmLineFeatureClass.FindField("osmMembers");
int osmSupportingElementPolylineFieldIndex = osmLineFeatureClass.FindField("osmSupportingElement");
// polygons
try
{
osmPolygonFeatureClass = osmToolHelper.CreatePolygonFeatureClass((IWorkspace2)featureWorkspace, targetFeatureDataset, targetDataElement.Name + "_osm_ply", null, null, null, storageKeyword, availableDomains, metadataAbstract, metadataPurpose, attributeTags[esriGeometryType.esriGeometryPolygon]);
}
catch (Exception ex)
{
message.AddError(120037, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullpolygonfeatureclass"), ex.Message));
return;
}
if (osmPolygonFeatureClass == null)
{
return;
}
// change the property set of the osm class extension to skip any change detection during the initial data load
osmPolygonFeatureClass.RemoveOSMClassExtension();
int osmPolygonIDFieldIndex = osmPolygonFeatureClass.FindField("OSMID");
Dictionary<string, int> osmPolygonDomainAttributeFieldIndices = new Dictionary<string, int>();
foreach (var domains in availableDomains.domain)
{
int currentFieldIndex = osmPolygonFeatureClass.FindField(domains.name);
if (currentFieldIndex != -1)
{
osmPolygonDomainAttributeFieldIndices.Add(domains.name, currentFieldIndex);
}
}
int tagCollectionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmTags");
int osmUserPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuser");
int osmUIDPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmuid");
int osmVisiblePolygonFieldIndex = osmPolygonFeatureClass.FindField("osmvisible");
int osmVersionPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmversion");
int osmChangesetPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmchangeset");
int osmTimeStampPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmtimestamp");
int osmMemberOfPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMemberOf");
int osmMembersPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmMembers");
int osmSupportingElementPolygonFieldIndex = osmPolygonFeatureClass.FindField("osmSupportingElement");
// relation table
ITable relationTable = null;
try
{
relationTable = osmToolHelper.CreateRelationTable((IWorkspace2)featureWorkspace, targetDataElement.Name + "_osm_relation", null, storageKeyword, metadataAbstract, metadataPurpose);
}
catch (Exception ex)
{
message.AddError(120038, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullrelationtable"), ex.Message));
return;
}
if (relationTable == null)
{
return;
}
int osmRelationIDFieldIndex = relationTable.FindField("OSMID");
int tagCollectionRelationFieldIndex = relationTable.FindField("osmTags");
int osmUserRelationFieldIndex = relationTable.FindField("osmuser");
int osmUIDRelationFieldIndex = relationTable.FindField("osmuid");
int osmVisibleRelationFieldIndex = relationTable.FindField("osmvisible");
int osmVersionRelationFieldIndex = relationTable.FindField("osmversion");
int osmChangesetRelationFieldIndex = relationTable.FindField("osmchangeset");
int osmTimeStampRelationFieldIndex = relationTable.FindField("osmtimestamp");
int osmMemberOfRelationFieldIndex = relationTable.FindField("osmMemberOf");
int osmMembersRelationFieldIndex = relationTable.FindField("osmMembers");
int osmSupportingElementRelationFieldIndex = relationTable.FindField("osmSupportingElement");
// revision table
ITable revisionTable = null;
try
{
revisionTable = osmToolHelper.CreateRevisionTable((IWorkspace2)featureWorkspace, targetDataElement.Name + "_osm_revision", null, storageKeyword);
}
catch (Exception ex)
{
message.AddError(120039, String.Format(resourceManager.GetString("GPTools_OSMGPDownload_nullrevisiontable"), ex.Message));
return;
}
if (revisionTable == null)
{
return;
}
#region clean any existing data from loading targets
ESRI.ArcGIS.Geoprocessing.IGeoProcessor2 gp = new ESRI.ArcGIS.Geoprocessing.GeoProcessorClass();
IGeoProcessorResult gpResult = new GeoProcessorResultClass();
try
{
IVariantArray truncateParameters = new VarArrayClass();
truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_pt");
gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel);
truncateParameters = new VarArrayClass();
truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ln");
gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel);
truncateParameters = new VarArrayClass();
truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "\\" + targetDataElement.Name + "_osm_ply");
gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel);
truncateParameters = new VarArrayClass();
truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "_osm_relation");
gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel);
truncateParameters = new VarArrayClass();
truncateParameters.Add(((IWorkspace)featureWorkspace).PathName + "\\" + targetDataElement.Name + "_osm_revision");
gpResult = gp.Execute("TruncateTable_management", truncateParameters, TrackCancel);
}
catch (Exception ex)
{
message.AddWarning(ex.Message);
}
#endregion
bool fastLoad = false;
//// check for user interruption
//if (TrackCancel.Continue() == false)
//{
// message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
// return;
//}
//IFeatureCursor deleteCursor = null;
//using (ComReleaser comReleaser = new ComReleaser())
//{
// // let's make sure that we clean out any old data that might have existed in the feature classes
// deleteCursor = osmPointFeatureClass.Update(null, false);
// comReleaser.ManageLifetime(deleteCursor);
// for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature())
// {
// feature.Delete();
// // check for user interruption
// if (TrackCancel.Continue() == false)
// {
// message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
// return;
// }
// }
//}
//using (ComReleaser comReleaser = new ComReleaser())
//{
// deleteCursor = osmLineFeatureClass.Update(null, false);
// comReleaser.ManageLifetime(deleteCursor);
// for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature())
// {
// feature.Delete();
// // check for user interruption
// if (TrackCancel.Continue() == false)
// {
// message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
// return;
// }
// }
//}
//using (ComReleaser comReleaser = new ComReleaser())
//{
// deleteCursor = osmPolygonFeatureClass.Update(null, false);
// comReleaser.ManageLifetime(deleteCursor);
// for (IFeature feature = deleteCursor.NextFeature(); feature != null; feature = deleteCursor.NextFeature())
// {
// feature.Delete();
// // check for user interruption
// if (TrackCancel.Continue() == false)
// {
// message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
// return;
// }
// }
//}
//ICursor tableCursor = null;
//using (ComReleaser comReleaser = new ComReleaser())
//{
// tableCursor = relationTable.Update(null, false);
// comReleaser.ManageLifetime(tableCursor);
// for (IRow row = tableCursor.NextRow(); row != null; row = tableCursor.NextRow())
// {
// row.Delete();
// // check for user interruption
// if (TrackCancel.Continue() == false)
// {
// message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
// return;
// }
// }
//}
//using (ComReleaser comReleaser = new ComReleaser())
//{
// tableCursor = revisionTable.Update(null, false);
// comReleaser.ManageLifetime(tableCursor);
// for (IRow row = tableCursor.NextRow(); row != null; row = tableCursor.NextRow())
// {
// row.Delete();
// // check for user interruption
// if (TrackCancel.Continue() == false)
// {
// message.AddAbort(resourceManager.GetString("GPTools_toolabort"));
// return;
// }
// }
//}
// define variables helping to invoke core tools for data management
IGeoProcessorResult2 gpResults2 = null;
IGeoProcessor2 geoProcessor = new GeoProcessorClass();
#region load points
osmToolHelper.loadOSMNodes(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, conserveMemoryGPValue.Value, fastLoad, Convert.ToInt32(nodeCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false);
#endregion
if (TrackCancel.Continue() == false)
{
return;
}
#region load ways
List<string> missingWays = osmToolHelper.loadOSMWays(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, conserveMemoryGPValue.Value, fastLoad, Convert.ToInt32(wayCapacity), ref osmNodeDictionary, featureWorkspace, downloadSpatialReference, availableDomains, false);
#endregion
if (downloadSpatialReference != null)
Marshal.ReleaseComObject(downloadSpatialReference);
#region for local geodatabases enforce spatial integrity
bool storedOriginalLocal = geoProcessor.AddOutputsToMap;
geoProcessor.AddOutputsToMap = false;
if (osmLineFeatureClass != null)
{
if (((IDataset)osmLineFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
{
gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;
IGPParameter outLinesParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter;
IGPValue lineFeatureClass = gpUtilities3.UnpackGPValue(outLinesParameter);
DataManagementTools.RepairGeometry repairlineGeometry = new DataManagementTools.RepairGeometry(osmLineFeatureClass);
IVariantArray repairGeometryParameterArray = new VarArrayClass();
repairGeometryParameterArray.Add(lineFeatureClass.GetAsText());
repairGeometryParameterArray.Add("DELETE_NULL");
gpResults2 = geoProcessor.Execute(repairlineGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2;
message.AddMessages(gpResults2.GetResultMessages());
ComReleaser.ReleaseCOMObject(gpUtilities3);
}
}
if (osmPolygonFeatureClass != null)
{
if (((IDataset)osmPolygonFeatureClass).Workspace.Type == esriWorkspaceType.esriLocalDatabaseWorkspace)
{
gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;
IGPParameter outPolygonParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter;
IGPValue polygonFeatureClass = gpUtilities3.UnpackGPValue(outPolygonParameter);
DataManagementTools.RepairGeometry repairpolygonGeometry = new DataManagementTools.RepairGeometry(osmPolygonFeatureClass);
IVariantArray repairGeometryParameterArray = new VarArrayClass();
repairGeometryParameterArray.Add(polygonFeatureClass.GetAsText());
repairGeometryParameterArray.Add("DELETE_NULL");
gpResults2 = geoProcessor.Execute(repairpolygonGeometry.ToolName, repairGeometryParameterArray, TrackCancel) as IGeoProcessorResult2;
message.AddMessages(gpResults2.GetResultMessages());
ComReleaser.ReleaseCOMObject(gpUtilities3);
}
}
geoProcessor.AddOutputsToMap = storedOriginalLocal;
#endregion
if (TrackCancel.Continue() == false)
{
return;
}
#region load relations
List<string> missingRelations = osmToolHelper.loadOSMRelations(osmFileLocationString.GetAsText(), ref TrackCancel, ref message, targetDatasetGPValue, osmPointFeatureClass, osmLineFeatureClass, osmPolygonFeatureClass, Convert.ToInt32(relationCapacity), relationTable, availableDomains, fastLoad, false);
#endregion
// check for user interruption
if (TrackCancel.Continue() == false)
{
return;
}
//storedOriginalLocal = geoProcessor.AddOutputsToMap;
//try
//{
// geoProcessor.AddOutputsToMap = false;
// // add indexes for revisions
// //IGPValue revisionTableGPValue = gpUtilities3.MakeGPValueFromObject(revisionTable);
// string revisionTableString = targetDatasetGPValue.GetAsText() + System.IO.Path.DirectorySeparatorChar + ((IDataset)revisionTable).BrowseName;
// IVariantArray parameterArrary2 = osmToolHelper.CreateAddIndexParameterArray(revisionTableString, "osmoldid;osmnewid", "osmID_IDX", "", "");
// gpResults2 = geoProcessor.Execute("AddIndex_management", parameterArrary2, TrackCancel) as IGeoProcessorResult2;
// message.AddMessages(gpResults2.GetResultMessages());
//}
//catch (Exception ex)
//{
// message.AddWarning(ex.Message);
//}
//finally
//{
// geoProcessor.AddOutputsToMap = storedOriginalLocal;
//}
#region update the references counts and member lists for nodes
message.AddMessage(resourceManager.GetString("GPTools_OSMGPFileReader_updatereferences"));
IFeatureCursor pointUpdateCursor = null;
IQueryFilter pointQueryFilter = new QueryFilterClass();
// adjust of number of all other reference counter from 0 to 1
if (conserveMemoryGPValue.Value == true)
{
pointQueryFilter.WhereClause = osmPointFeatureClass.SqlIdentifier("wayRefCount") + " = 0";
pointQueryFilter.SubFields = osmPointFeatureClass.OIDFieldName + ",wayRefCount";
}
using (SchemaLockManager ptLockManager = new SchemaLockManager(osmPointFeatureClass as ITable))
{
using (ComReleaser comReleaser = new ComReleaser())
{
int updateCount = 0;
if (conserveMemoryGPValue.Value == true)
{
pointUpdateCursor = osmPointFeatureClass.Update(pointQueryFilter, false);
updateCount = ((ITable)osmPointFeatureClass).RowCount(pointQueryFilter);
}
else
{
pointUpdateCursor = osmPointFeatureClass.Update(null, false);
updateCount = ((ITable)osmPointFeatureClass).RowCount(null);
}
IStepProgressor stepProgressor = TrackCancel as IStepProgressor;
if (stepProgressor != null)
{
stepProgressor.MinRange = 0;
stepProgressor.MaxRange = updateCount;
stepProgressor.Position = 0;
stepProgressor.Message = resourceManager.GetString("GPTools_OSMGPFileReader_updatepointrefcount");
stepProgressor.StepValue = 1;
stepProgressor.Show();
}
comReleaser.ManageLifetime(pointUpdateCursor);
IFeature pointFeature = pointUpdateCursor.NextFeature();
int positionCounter = 0;
while (pointFeature != null)
{
positionCounter++;
string nodeID = Convert.ToString(pointFeature.get_Value(osmPointIDFieldIndex));
if (conserveMemoryGPValue.Value == false)
{
// let get the reference counter from the internal node dictionary
if (osmNodeDictionary[nodeID].RefCounter == 0)
{
pointFeature.set_Value(osmWayRefCountFieldIndex, 1);
}
else
{
pointFeature.set_Value(osmWayRefCountFieldIndex, osmNodeDictionary[nodeID].RefCounter);
}
}
else
{
// in the case of memory conservation let's go change the 0s to 1s
pointFeature.set_Value(osmWayRefCountFieldIndex, 1);
}
pointUpdateCursor.UpdateFeature(pointFeature);
if (pointFeature != null)
Marshal.ReleaseComObject(pointFeature);
pointFeature = pointUpdateCursor.NextFeature();
if (stepProgressor != null)
{
stepProgressor.Position = positionCounter;
}
}
if (stepProgressor != null)
{
stepProgressor.Hide();
}
Marshal.ReleaseComObject(pointQueryFilter);
}
}
#endregion
if (osmNodeDictionary != null)
{
// clear outstanding resources potentially holding points
osmNodeDictionary = null;
System.GC.Collect(2, GCCollectionMode.Forced);
}
if (missingRelations.Count > 0)
{
missingRelations.Clear();
missingRelations = null;
}
if (missingWays.Count > 0)
{
missingWays.Clear();
missingWays = null;
}
SyncState.StoreLastSyncTime(targetDatasetName, syncTime);
gpUtilities3 = new GPUtilitiesClass() as IGPUtilities3;
// repackage the feature class into their respective gp values
IGPParameter pointFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter;
IGPValue pointFeatureClassGPValue = gpUtilities3.UnpackGPValue(pointFeatureClassParameter);
gpUtilities3.PackGPValue(pointFeatureClassGPValue, pointFeatureClassParameter);
IGPParameter lineFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter;
IGPValue line1FeatureClassGPValue = gpUtilities3.UnpackGPValue(lineFeatureClassParameter);
gpUtilities3.PackGPValue(line1FeatureClassGPValue, lineFeatureClassParameter);
IGPParameter polygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter;
IGPValue polygon1FeatureClassGPValue = gpUtilities3.UnpackGPValue(polygonFeatureClassParameter);
gpUtilities3.PackGPValue(polygon1FeatureClassGPValue, polygonFeatureClassParameter);
ComReleaser.ReleaseCOMObject(relationTable);
ComReleaser.ReleaseCOMObject(revisionTable);
ComReleaser.ReleaseCOMObject(targetFeatureDataset);
ComReleaser.ReleaseCOMObject(featureWorkspace);
ComReleaser.ReleaseCOMObject(osmFileLocationString);
ComReleaser.ReleaseCOMObject(conserveMemoryGPValue);
ComReleaser.ReleaseCOMObject(targetDataset);
gpUtilities3.ReleaseInternals();
ComReleaser.ReleaseCOMObject(gpUtilities3);
}
catch (Exception ex)
{
message.AddError(120055, ex.Message);
message.AddError(120055, ex.StackTrace);
}
finally
{
try
{
// TE -- 1/7/2015
// this is a 'breaking' change as the default loader won't no longer enable the edit extension
// the reasoning here is that most users would like the OSM in a 'read-only' fashion, and don't need to track
// changes to be properly transmitted back to the OSM server
//if (osmPointFeatureClass != null)
//{
// osmPointFeatureClass.ApplyOSMClassExtension();
// ComReleaser.ReleaseCOMObject(osmPointFeatureClass);
//}
//if (osmLineFeatureClass != null)
//{
// osmLineFeatureClass.ApplyOSMClassExtension();
// ComReleaser.ReleaseCOMObject(osmLineFeatureClass);
//}
//if (osmPolygonFeatureClass != null)
//{
// osmPolygonFeatureClass.ApplyOSMClassExtension();
// ComReleaser.ReleaseCOMObject(osmPolygonFeatureClass);
//}
osmToolHelper = null;
System.GC.Collect();
System.GC.WaitForPendingFinalizers();
}
catch (Exception ex)
{
message.AddError(120056, ex.ToString());
}
}
}
public ESRI.ArcGIS.esriSystem.IName FullName
{
get
{
IName fullName = null;
if (osmGPFactory != null)
{
fullName = osmGPFactory.GetFunctionName(OSMGPFactory.m_FileLoaderName) as IName;
}
return fullName;
}
}
public object GetRenderer(ESRI.ArcGIS.Geoprocessing.IGPParameter pParam)
{
return null;
}
public int HelpContext
{
get
{
return 0;
}
}
public string HelpFile
{
get
{
return "";
}
}
public bool IsLicensed()
{
return true;
}
public string MetadataFile
{
get
{
string metadafile = "osmgpfileloader.xml";
try
{
string[] languageid = System.Threading.Thread.CurrentThread.CurrentUICulture.Name.Split("-".ToCharArray());
string ArcGISInstallationLocation = OSMGPFactory.GetArcGIS10InstallLocation();
string localizedMetaDataFileShort = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpfileloader_" + languageid[0] + ".xml";
string localizedMetaDataFileLong = ArcGISInstallationLocation + System.IO.Path.DirectorySeparatorChar.ToString() + "help" + System.IO.Path.DirectorySeparatorChar.ToString() + "gp" + System.IO.Path.DirectorySeparatorChar.ToString() + "osmgpfileloader_" + System.Threading.Thread.CurrentThread.CurrentUICulture.Name + ".xml";
if (System.IO.File.Exists(localizedMetaDataFileShort))
{
metadafile = localizedMetaDataFileShort;
}
else if (System.IO.File.Exists(localizedMetaDataFileLong))
{
metadafile = localizedMetaDataFileLong;
}
}
catch { }
return metadafile;
}
}
public string Name
{
get
{
return OSMGPFactory.m_FileLoaderName;
}
}
public ESRI.ArcGIS.esriSystem.IArray ParameterInfo
{
get
{
//
IArray parameterArray = new ArrayClass();
// osm file to load (required)
IGPParameterEdit3 osmLoadFile = new GPParameterClass() as IGPParameterEdit3;
osmLoadFile.DataType = new DEFileTypeClass();
osmLoadFile.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
osmLoadFile.DisplayName = resourceManager.GetString("GPTools_OSMGPFileReader_osmfile_desc");
osmLoadFile.Name = "in_osmFile";
osmLoadFile.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
IGPParameterEdit3 conserveMemory = new GPParameterClass() as IGPParameterEdit3;
IGPCodedValueDomain conserveMemoryDomain = new GPCodedValueDomainClass();
IGPBoolean conserveTrue = new GPBooleanClass();
conserveTrue.Value = true;
IGPBoolean conserveFalse = new GPBooleanClass();
conserveFalse.Value = false;
conserveMemoryDomain.AddCode((IGPValue)conserveTrue, "CONSERVE_MEMORY");
conserveMemoryDomain.AddCode((IGPValue)conserveFalse, "DO_NOT_CONSERVE_MEMORY");
conserveMemory.Domain = (IGPDomain)conserveMemoryDomain;
conserveMemory.Value = (IGPValue)conserveTrue;
conserveMemory.DataType = new GPBooleanTypeClass();
conserveMemory.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
conserveMemory.DisplayName = resourceManager.GetString("GPTools_OSMGPFileReader_conserveMemory_desc");
conserveMemory.Name = "in_conserveMemory";
// attribute multi select parameter
IGPParameterEdit3 attributeSelect = new GPParameterClass() as IGPParameterEdit3;
IGPDataType tagKeyDataType = new GPStringTypeClass();
IGPMultiValue tagKeysMultiValue = new GPMultiValueClass();
tagKeysMultiValue.MemberDataType = tagKeyDataType;
IGPCodedValueDomain tagKeyDomains = new GPCodedValueDomainClass();
tagKeyDomains.AddStringCode("ALL", "ALL");
IGPMultiValueType tagKeyDataType2 = new GPMultiValueTypeClass();
tagKeyDataType2.MemberDataType = tagKeyDataType;
attributeSelect.Name = "in_attributeselect";
attributeSelect.DisplayName = resourceManager.GetString("GPTools_OSMFileLoader_attributeSchemaSelection");
attributeSelect.Category = resourceManager.GetString("GPTools_OSMFileLoader_schemaCategory");
attributeSelect.ParameterType = esriGPParameterType.esriGPParameterTypeOptional;
attributeSelect.Direction = esriGPParameterDirection.esriGPParameterDirectionInput;
attributeSelect.Domain = (IGPDomain)tagKeyDomains;
attributeSelect.DataType = (IGPDataType)tagKeyDataType2;
attributeSelect.Value = (IGPValue)tagKeysMultiValue;
// target dataset (required)
IGPParameterEdit3 targetDataset = new GPParameterClass() as IGPParameterEdit3;
targetDataset.DataType = new DEFeatureDatasetTypeClass();
targetDataset.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
targetDataset.DisplayName = resourceManager.GetString("GPTools_OSMGPFileReader_targetDataset_desc");
targetDataset.Name = "out_targetdataset";
IGPDatasetDomain datasetDomain = new GPDatasetDomainClass();
datasetDomain.AddType(esriDatasetType.esriDTFeatureDataset);
targetDataset.Domain = datasetDomain as IGPDomain;
IGPParameterEdit3 osmPoints = new GPParameterClass() as IGPParameterEdit3;
osmPoints.DataType = new DEFeatureClassTypeClass();
osmPoints.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
osmPoints.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
osmPoints.Enabled = false;
osmPoints.Category = resourceManager.GetString("GPTools_OSMGPFileReader_outputCategory");
osmPoints.DisplayName = resourceManager.GetString("GPTools_OSMGPFileReader_osmPoints_desc");
osmPoints.Name = "out_osmPoints";
IGPFeatureClassDomain osmPointFeatureClassDomain = new GPFeatureClassDomainClass();
osmPointFeatureClassDomain.AddFeatureType(esriFeatureType.esriFTSimple);
osmPointFeatureClassDomain.AddType(ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPoint);
osmPoints.Domain = osmPointFeatureClassDomain as IGPDomain;
IGPParameterEdit3 osmLines = new GPParameterClass() as IGPParameterEdit3;
osmLines.DataType = new DEFeatureClassTypeClass();
osmLines.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
osmLines.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
osmLines.Category = resourceManager.GetString("GPTools_OSMGPFileReader_outputCategory");
osmLines.Enabled = false;
osmLines.DisplayName = resourceManager.GetString("GPTools_OSMGPFileReader_osmLine_desc");
osmLines.Name = "out_osmLines";
IGPFeatureClassDomain osmPolylineFeatureClassDomain = new GPFeatureClassDomainClass();
osmPolylineFeatureClassDomain.AddFeatureType(esriFeatureType.esriFTSimple);
osmPolylineFeatureClassDomain.AddType(ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolyline);
osmLines.Domain = osmPolylineFeatureClassDomain as IGPDomain;
IGPParameterEdit3 osmPolygons = new GPParameterClass() as IGPParameterEdit3;
osmPolygons.DataType = new DEFeatureClassTypeClass();
osmPolygons.Direction = esriGPParameterDirection.esriGPParameterDirectionOutput;
osmPolygons.ParameterType = esriGPParameterType.esriGPParameterTypeRequired;
osmPolygons.Category = resourceManager.GetString("GPTools_OSMGPFileReader_outputCategory");
osmPolygons.Enabled = false;
osmPolygons.DisplayName = resourceManager.GetString("GPTools_OSMGPFileReader_osmPolygon_desc");
osmPolygons.Name = "out_osmPolygons";
IGPFeatureClassDomain osmPolygonFeatureClassDomain = new GPFeatureClassDomainClass();
osmPolygonFeatureClassDomain.AddFeatureType(esriFeatureType.esriFTSimple);
osmPolygonFeatureClassDomain.AddType(ESRI.ArcGIS.Geometry.esriGeometryType.esriGeometryPolygon);
osmPolygons.Domain = osmPolygonFeatureClassDomain as IGPDomain;
parameterArray.Add(osmLoadFile);
in_osmFileNumber = 0;
parameterArray.Add(conserveMemory);
in_conserveMemoryNumber = 1;
in_attributeSelector = 2;
parameterArray.Add(attributeSelect);
parameterArray.Add(targetDataset);
out_targetDatasetNumber = 3;
parameterArray.Add(osmPoints);
out_osmPointsNumber = 4;
parameterArray.Add(osmLines);
out_osmLinesNumber = 5;
parameterArray.Add(osmPolygons);
out_osmPolygonsNumber = 6;
return parameterArray;
}
}
public void UpdateMessages(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr, ESRI.ArcGIS.Geodatabase.IGPMessages Messages)
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
IGPParameter targetDatasetParameter = paramvalues.get_Element(out_targetDatasetNumber) as IGPParameter;
try
{
gpUtilities3.QualifyOutputDataElement(gpUtilities3.UnpackGPValue(targetDatasetParameter));
}
catch
{
Messages.ReplaceError(out_targetDatasetNumber, -2, resourceManager.GetString("GPTools_OSMGPFileReader_targetDataset_notexist"));
}
// check for valid geodatabase path
// if the user is pointing to a valid directory on disk, flag it as an error
IGPValue targetDatasetGPValue = gpUtilities3.UnpackGPValue(targetDatasetParameter);
if (targetDatasetGPValue.IsEmpty() == false)
{
if (System.IO.Directory.Exists(targetDatasetGPValue.GetAsText()))
{
Messages.ReplaceError(out_targetDatasetNumber, -4, resourceManager.GetString("GPTools_OSMGPDownload_directory_is_not_target_dataset"));
}
}
// check one of the output feature classes for version compatibility
IGPParameter pointFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter;
IDEFeatureClass pointDEFeatureClass = gpUtilities3.UnpackGPValue(pointFeatureClassParameter) as IDEFeatureClass;
if (pointDEFeatureClass != null)
{
if (((IGPValue)pointDEFeatureClass).IsEmpty() == false)
{
if (gpUtilities3.Exists((IGPValue)pointDEFeatureClass))
{
IFeatureClass ptfc = gpUtilities3.Open(gpUtilities3.UnpackGPValue(pointFeatureClassParameter)) as IFeatureClass;
IPropertySet osmExtensionPropertySet = ptfc.ExtensionProperties;
if (osmExtensionPropertySet == null)
{
Messages.ReplaceError(out_targetDatasetNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
Messages.ReplaceError(out_osmPointsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
Messages.ReplaceError(out_osmLinesNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
Messages.ReplaceError(out_osmPolygonsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
}
else
{
try
{
int extensionVersion = Convert.ToInt32(osmExtensionPropertySet.GetProperty("VERSION"));
if (extensionVersion != OSMClassExtensionManager.Version)
{
Messages.ReplaceError(out_targetDatasetNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), extensionVersion, OSMClassExtensionManager.Version));
Messages.ReplaceError(out_osmPointsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), extensionVersion, OSMClassExtensionManager.Version));
Messages.ReplaceError(out_osmLinesNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), extensionVersion, OSMClassExtensionManager.Version));
Messages.ReplaceError(out_osmPolygonsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), extensionVersion, OSMClassExtensionManager.Version));
}
}
catch
{
Messages.ReplaceError(out_targetDatasetNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
Messages.ReplaceError(out_osmPointsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
Messages.ReplaceError(out_osmLinesNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
Messages.ReplaceError(out_osmPolygonsNumber, -5, string.Format(resourceManager.GetString("GPTools_IncompatibleExtensionVersion"), 1, OSMClassExtensionManager.Version));
}
}
}
}
}
gpUtilities3.ReleaseInternals();
if (gpUtilities3 != null)
ComReleaser.ReleaseCOMObject(gpUtilities3);
}
public void UpdateParameters(ESRI.ArcGIS.esriSystem.IArray paramvalues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager pEnvMgr)
{
IGPUtilities3 gpUtilities3 = new GPUtilitiesClass();
IGPParameter targetDatasetParameter = paramvalues.get_Element(out_targetDatasetNumber) as IGPParameter;
IGPValue targetDatasetGPValue = gpUtilities3.UnpackGPValue(targetDatasetParameter);
IDEFeatureDataset targetDEFeatureDataset = targetDatasetGPValue as IDEFeatureDataset;
IGPParameter3 outPointsFeatureClassParameter = null;
IGPValue outPointsFeatureClass = null;
string outpointsPath = String.Empty;
IGPParameter3 outLinesFeatureClassParameter = null;
IGPValue outLinesFeatureClass = null;
string outlinesPath = String.Empty;
IGPParameter3 outPolygonFeatureClassParameter = null;
IGPValue outPolygonFeatureClass = null;
string outpolygonsPath = String.Empty;
if (((IGPValue)targetDEFeatureDataset).GetAsText().Length != 0)
{
IDataElement dataElement = targetDEFeatureDataset as IDataElement;
try
{
gpUtilities3.QualifyOutputDataElement(gpUtilities3.UnpackGPValue(targetDatasetParameter));
}
catch
{
return;
}
string nameOfPointFeatureClass = dataElement.GetBaseName() + "_osm_pt";
string nameOfLineFeatureClass = dataElement.GetBaseName() + "_osm_ln";
string nameOfPolygonFeatureClass = dataElement.GetBaseName() + "_osm_ply";
try
{
outpointsPath = dataElement.CatalogPath + System.IO.Path.DirectorySeparatorChar + nameOfPointFeatureClass;
}
catch (Exception ex)
{
System.Diagnostics.Debug.WriteLine(ex.Message);
}
outPointsFeatureClassParameter = paramvalues.get_Element(out_osmPointsNumber) as IGPParameter3;
outPointsFeatureClass = gpUtilities3.UnpackGPValue(outPointsFeatureClassParameter);
outlinesPath = dataElement.CatalogPath + System.IO.Path.DirectorySeparatorChar + nameOfLineFeatureClass;
outLinesFeatureClassParameter = paramvalues.get_Element(out_osmLinesNumber) as IGPParameter3;
outLinesFeatureClass = gpUtilities3.UnpackGPValue(outLinesFeatureClassParameter);
outpolygonsPath = dataElement.CatalogPath + System.IO.Path.DirectorySeparatorChar + nameOfPolygonFeatureClass;
outPolygonFeatureClassParameter = paramvalues.get_Element(out_osmPolygonsNumber) as IGPParameter3;
outPolygonFeatureClass = gpUtilities3.UnpackGPValue(outPolygonFeatureClassParameter);
}
// TE - 10/20/2014
if (((IGPParameter)paramvalues.get_Element(in_attributeSelector)).Altered)
{
IGPParameter tagCollectionParameter = paramvalues.get_Element(in_attributeSelector) as IGPParameter;
IGPMultiValue tagCollectionGPValue = gpUtilities3.UnpackGPValue(tagCollectionParameter) as IGPMultiValue;
IGPCodedValueDomain codedTagDomain = tagCollectionParameter.Domain as IGPCodedValueDomain;
for (int attributeValueIndex = 0; attributeValueIndex < tagCollectionGPValue.Count; attributeValueIndex++)
{
string valueString = tagCollectionGPValue.get_Value(attributeValueIndex).GetAsText();
IGPValue testFieldValue = codedTagDomain.FindValue(valueString);
if (testFieldValue == null)
{
codedTagDomain.AddStringCode(valueString, valueString);
}
}
string illegalCharacters = "`~@#$%^&()-+=,{}.![];";
IFieldsEdit fieldsEdit = new FieldsClass();
for (int valueIndex = 0; valueIndex < tagCollectionGPValue.Count; valueIndex++)
{
string tagString = tagCollectionGPValue.get_Value(valueIndex).GetAsText();
if (tagString != "ALL")
{
// Check if the input field already exists.
string cleanedTagKey = OSMToolHelper.convert2AttributeFieldName(tagString, illegalCharacters);
IFieldEdit fieldEdit = new FieldClass();
fieldEdit.Name_2 = cleanedTagKey;
fieldEdit.AliasName_2 = tagCollectionGPValue.get_Value(valueIndex).GetAsText();
fieldEdit.Type_2 = esriFieldType.esriFieldTypeString;
fieldEdit.Length_2 = 100;
fieldsEdit.AddField(fieldEdit);
}
}
IFields fields = fieldsEdit as IFields;
// Get the derived output feature class schema and empty the additional fields. This ensures
// that you don't get dublicate entries.
if (outPointsFeatureClassParameter != null)
{
IGPFeatureSchema polySchema = outPolygonFeatureClassParameter.Schema as IGPFeatureSchema;
if (polySchema != null)
{
// Add the additional field to the polygon output.
polySchema.AdditionalFields = fields;
}
else
{
polySchema = new GPFeatureSchemaClass();
polySchema.AdditionalFields = fields;
polySchema.GeometryType = esriGeometryType.esriGeometryPolygon;
polySchema.FeatureType = esriFeatureType.esriFTSimple;
}
}
if (outLinesFeatureClassParameter != null)
{
IGPFeatureSchema lineSchema = outLinesFeatureClassParameter.Schema as IGPFeatureSchema;
if (lineSchema != null)
{
// Add the additional field to the line output.
lineSchema.AdditionalFields = fields;
}
else
{
lineSchema = new GPFeatureSchemaClass();
lineSchema.AdditionalFields = fields;
lineSchema.GeometryType = esriGeometryType.esriGeometryPolyline;
lineSchema.FeatureType = esriFeatureType.esriFTSimple;
}
}
if (outPointsFeatureClassParameter != null)
{
IGPFeatureSchema pointSchema = outPointsFeatureClassParameter.Schema as IGPFeatureSchema;
if (pointSchema != null)
{
// Add the additional field to the point output.
pointSchema.AdditionalFields = fields;
}
else
{
pointSchema = new GPFeatureSchemaClass();
pointSchema.AdditionalFields = fields;
pointSchema.GeometryType = esriGeometryType.esriGeometryPoint;
pointSchema.FeatureType = esriFeatureType.esriFTSimple;
}
}
}
if (outPointsFeatureClassParameter != null)
{
outPointsFeatureClass.SetAsText(outpointsPath);
gpUtilities3.PackGPValue(outPointsFeatureClass, outPointsFeatureClassParameter);
}
if (outLinesFeatureClassParameter != null)
{
outLinesFeatureClass.SetAsText(outlinesPath);
gpUtilities3.PackGPValue(outLinesFeatureClass, outLinesFeatureClassParameter);
}
if (outPolygonFeatureClassParameter != null)
{
outPolygonFeatureClass.SetAsText(outpolygonsPath);
gpUtilities3.PackGPValue(outPolygonFeatureClass, outPolygonFeatureClassParameter);
}
gpUtilities3.ReleaseInternals();
if (gpUtilities3 != null)
ComReleaser.ReleaseCOMObject(gpUtilities3);
}
public ESRI.ArcGIS.Geodatabase.IGPMessages Validate(ESRI.ArcGIS.esriSystem.IArray paramvalues, bool updateValues, ESRI.ArcGIS.Geoprocessing.IGPEnvironmentManager envMgr)
{
return default(ESRI.ArcGIS.Geodatabase.IGPMessages);
}
#endregion
}
}
| |
#region Apache License
//
// 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.
//
#endregion
using System;
using System.Collections;
using log4net.Util;
using log4net.Core;
namespace log4net.Appender
{
/// <summary>
/// Abstract base class implementation of <see cref="IAppender"/> that
/// buffers events in a fixed size buffer.
/// </summary>
/// <remarks>
/// <para>
/// This base class should be used by appenders that need to buffer a
/// number of events before logging them. For example the <see cref="AdoNetAppender"/>
/// buffers events and then submits the entire contents of the buffer to
/// the underlying database in one go.
/// </para>
/// <para>
/// Subclasses should override the <see cref="SendBuffer(LoggingEvent[])"/>
/// method to deliver the buffered events.
/// </para>
/// <para>The BufferingAppenderSkeleton maintains a fixed size cyclic
/// buffer of events. The size of the buffer is set using
/// the <see cref="BufferSize"/> property.
/// </para>
/// <para>A <see cref="ITriggeringEventEvaluator"/> is used to inspect
/// each event as it arrives in the appender. If the <see cref="Evaluator"/>
/// triggers, then the current buffer is sent immediately
/// (see <see cref="SendBuffer(LoggingEvent[])"/>). Otherwise the event
/// is stored in the buffer. For example, an evaluator can be used to
/// deliver the events immediately when an ERROR event arrives.
/// </para>
/// <para>
/// The buffering appender can be configured in a <see cref="Lossy"/> mode.
/// By default the appender is NOT lossy. When the buffer is full all
/// the buffered events are sent with <see cref="SendBuffer(LoggingEvent[])"/>.
/// If the <see cref="Lossy"/> property is set to <c>true</c> then the
/// buffer will not be sent when it is full, and new events arriving
/// in the appender will overwrite the oldest event in the buffer.
/// In lossy mode the buffer will only be sent when the <see cref="Evaluator"/>
/// triggers. This can be useful behavior when you need to know about
/// ERROR events but not about events with a lower level, configure an
/// evaluator that will trigger when an ERROR event arrives, the whole
/// buffer will be sent which gives a history of events leading up to
/// the ERROR event.
/// </para>
/// </remarks>
/// <author>Nicko Cadell</author>
/// <author>Gert Driesen</author>
public abstract class BufferingAppenderSkeleton : AppenderSkeleton
{
#region Protected Instance Constructors
/// <summary>
/// Initializes a new instance of the <see cref="BufferingAppenderSkeleton" /> class.
/// </summary>
/// <remarks>
/// <para>
/// Protected default constructor to allow subclassing.
/// </para>
/// </remarks>
protected BufferingAppenderSkeleton() : this(true)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="BufferingAppenderSkeleton" /> class.
/// </summary>
/// <param name="eventMustBeFixed">the events passed through this appender must be
/// fixed by the time that they arrive in the derived class' <c>SendBuffer</c> method.</param>
/// <remarks>
/// <para>
/// Protected constructor to allow subclassing.
/// </para>
/// <para>
/// The <paramref name="eventMustBeFixed"/> should be set if the subclass
/// expects the events delivered to be fixed even if the
/// <see cref="BufferSize"/> is set to zero, i.e. when no buffering occurs.
/// </para>
/// </remarks>
protected BufferingAppenderSkeleton(bool eventMustBeFixed) : base()
{
m_eventMustBeFixed = eventMustBeFixed;
}
#endregion Protected Instance Constructors
#region Public Instance Properties
/// <summary>
/// Gets or sets a value that indicates whether the appender is lossy.
/// </summary>
/// <value>
/// <c>true</c> if the appender is lossy, otherwise <c>false</c>. The default is <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// This appender uses a buffer to store logging events before
/// delivering them. A triggering event causes the whole buffer
/// to be send to the remote sink. If the buffer overruns before
/// a triggering event then logging events could be lost. Set
/// <see cref="Lossy"/> to <c>false</c> to prevent logging events
/// from being lost.
/// </para>
/// <para>If <see cref="Lossy"/> is set to <c>true</c> then an
/// <see cref="Evaluator"/> must be specified.</para>
/// </remarks>
public bool Lossy
{
get { return m_lossy; }
set { m_lossy = value; }
}
/// <summary>
/// Gets or sets the size of the cyclic buffer used to hold the
/// logging events.
/// </summary>
/// <value>
/// The size of the cyclic buffer used to hold the logging events.
/// </value>
/// <remarks>
/// <para>
/// The <see cref="BufferSize"/> option takes a positive integer
/// representing the maximum number of logging events to collect in
/// a cyclic buffer. When the <see cref="BufferSize"/> is reached,
/// oldest events are deleted as new events are added to the
/// buffer. By default the size of the cyclic buffer is 512 events.
/// </para>
/// <para>
/// If the <see cref="BufferSize"/> is set to a value less than
/// or equal to 1 then no buffering will occur. The logging event
/// will be delivered synchronously (depending on the <see cref="Lossy"/>
/// and <see cref="Evaluator"/> properties). Otherwise the event will
/// be buffered.
/// </para>
/// </remarks>
public int BufferSize
{
get { return m_bufferSize; }
set { m_bufferSize = value; }
}
/// <summary>
/// Gets or sets the <see cref="ITriggeringEventEvaluator"/> that causes the
/// buffer to be sent immediately.
/// </summary>
/// <value>
/// The <see cref="ITriggeringEventEvaluator"/> that causes the buffer to be
/// sent immediately.
/// </value>
/// <remarks>
/// <para>
/// The evaluator will be called for each event that is appended to this
/// appender. If the evaluator triggers then the current buffer will
/// immediately be sent (see <see cref="SendBuffer(LoggingEvent[])"/>).
/// </para>
/// <para>If <see cref="Lossy"/> is set to <c>true</c> then an
/// <see cref="Evaluator"/> must be specified.</para>
/// </remarks>
public ITriggeringEventEvaluator Evaluator
{
get { return m_evaluator; }
set { m_evaluator = value; }
}
/// <summary>
/// Gets or sets the value of the <see cref="ITriggeringEventEvaluator"/> to use.
/// </summary>
/// <value>
/// The value of the <see cref="ITriggeringEventEvaluator"/> to use.
/// </value>
/// <remarks>
/// <para>
/// The evaluator will be called for each event that is discarded from this
/// appender. If the evaluator triggers then the current buffer will immediately
/// be sent (see <see cref="SendBuffer(LoggingEvent[])"/>).
/// </para>
/// </remarks>
public ITriggeringEventEvaluator LossyEvaluator
{
get { return m_lossyEvaluator; }
set { m_lossyEvaluator = value; }
}
/// <summary>
/// Gets or sets a value indicating if only part of the logging event data
/// should be fixed.
/// </summary>
/// <value>
/// <c>true</c> if the appender should only fix part of the logging event
/// data, otherwise <c>false</c>. The default is <c>false</c>.
/// </value>
/// <remarks>
/// <para>
/// Setting this property to <c>true</c> will cause only part of the
/// event data to be fixed and serialized. This will improve performance.
/// </para>
/// <para>
/// See <see cref="LoggingEvent.FixVolatileData(FixFlags)"/> for more information.
/// </para>
/// </remarks>
[Obsolete("Use Fix property")]
virtual public bool OnlyFixPartialEventData
{
get { return (Fix == FixFlags.Partial); }
set
{
if (value)
{
Fix = FixFlags.Partial;
}
else
{
Fix = FixFlags.All;
}
}
}
/// <summary>
/// Gets or sets a the fields that will be fixed in the event
/// </summary>
/// <value>
/// The event fields that will be fixed before the event is buffered
/// </value>
/// <remarks>
/// <para>
/// The logging event needs to have certain thread specific values
/// captured before it can be buffered. See <see cref="LoggingEvent.Fix"/>
/// for details.
/// </para>
/// </remarks>
/// <seealso cref="LoggingEvent.Fix"/>
virtual public FixFlags Fix
{
get { return m_fixFlags; }
set { m_fixFlags = value; }
}
#endregion Public Instance Properties
#region Public Methods
/// <summary>
/// Flush the currently buffered events
/// </summary>
/// <remarks>
/// <para>
/// Flushes any events that have been buffered.
/// </para>
/// <para>
/// If the appender is buffering in <see cref="Lossy"/> mode then the contents
/// of the buffer will NOT be flushed to the appender.
/// </para>
/// </remarks>
public virtual void Flush()
{
Flush(false);
}
/// <summary>
/// Flush the currently buffered events
/// </summary>
/// <param name="flushLossyBuffer">set to <c>true</c> to flush the buffer of lossy events</param>
/// <remarks>
/// <para>
/// Flushes events that have been buffered. If <paramref name="flushLossyBuffer" /> is
/// <c>false</c> then events will only be flushed if this buffer is non-lossy mode.
/// </para>
/// <para>
/// If the appender is buffering in <see cref="Lossy"/> mode then the contents
/// of the buffer will only be flushed if <paramref name="flushLossyBuffer" /> is <c>true</c>.
/// In this case the contents of the buffer will be tested against the
/// <see cref="LossyEvaluator"/> and if triggering will be output. All other buffered
/// events will be discarded.
/// </para>
/// <para>
/// If <paramref name="flushLossyBuffer" /> is <c>true</c> then the buffer will always
/// be emptied by calling this method.
/// </para>
/// </remarks>
public virtual void Flush(bool flushLossyBuffer)
{
// This method will be called outside of the AppenderSkeleton DoAppend() method
// therefore it needs to be protected by its own lock. This will block any
// Appends while the buffer is flushed.
lock(this)
{
if (m_cb != null && m_cb.Length > 0)
{
if (m_lossy)
{
// If we are allowed to eagerly flush from the lossy buffer
if (flushLossyBuffer)
{
if (m_lossyEvaluator != null)
{
// Test the contents of the buffer against the lossy evaluator
LoggingEvent[] bufferedEvents = m_cb.PopAll();
ArrayList filteredEvents = new ArrayList(bufferedEvents.Length);
foreach(LoggingEvent loggingEvent in bufferedEvents)
{
if (m_lossyEvaluator.IsTriggeringEvent(loggingEvent))
{
filteredEvents.Add(loggingEvent);
}
}
// Send the events that meet the lossy evaluator criteria
if (filteredEvents.Count > 0)
{
SendBuffer((LoggingEvent[])filteredEvents.ToArray(typeof(LoggingEvent)));
}
}
else
{
// No lossy evaluator, all buffered events are discarded
m_cb.Clear();
}
}
}
else
{
// Not lossy, send whole buffer
SendFromBuffer(null, m_cb);
}
}
}
}
#endregion Public Methods
#region Implementation of IOptionHandler
/// <summary>
/// Initialize the appender based on the options set
/// </summary>
/// <remarks>
/// <para>
/// This is part of the <see cref="IOptionHandler"/> delayed object
/// activation scheme. The <see cref="ActivateOptions"/> method must
/// be called on this object after the configuration properties have
/// been set. Until <see cref="ActivateOptions"/> is called this
/// object is in an undefined state and must not be used.
/// </para>
/// <para>
/// If any of the configuration properties are modified then
/// <see cref="ActivateOptions"/> must be called again.
/// </para>
/// </remarks>
override public void ActivateOptions()
{
base.ActivateOptions();
// If the appender is in Lossy mode then we will
// only send the buffer when the Evaluator triggers
// therefore check we have an evaluator.
if (m_lossy && m_evaluator == null)
{
ErrorHandler.Error("Appender ["+Name+"] is Lossy but has no Evaluator. The buffer will never be sent!");
}
if (m_bufferSize > 1)
{
m_cb = new CyclicBuffer(m_bufferSize);
}
else
{
m_cb = null;
}
}
#endregion Implementation of IOptionHandler
#region Override implementation of AppenderSkeleton
/// <summary>
/// Close this appender instance.
/// </summary>
/// <remarks>
/// <para>
/// Close this appender instance. If this appender is marked
/// as not <see cref="Lossy"/> then the remaining events in
/// the buffer must be sent when the appender is closed.
/// </para>
/// </remarks>
override protected void OnClose()
{
// Flush the buffer on close
Flush(true);
}
/// <summary>
/// This method is called by the <see cref="AppenderSkeleton.DoAppend(LoggingEvent)"/> method.
/// </summary>
/// <param name="loggingEvent">the event to log</param>
/// <remarks>
/// <para>
/// Stores the <paramref name="loggingEvent"/> in the cyclic buffer.
/// </para>
/// <para>
/// The buffer will be sent (i.e. passed to the <see cref="SendBuffer"/>
/// method) if one of the following conditions is met:
/// </para>
/// <list type="bullet">
/// <item>
/// <description>The cyclic buffer is full and this appender is
/// marked as not lossy (see <see cref="Lossy"/>)</description>
/// </item>
/// <item>
/// <description>An <see cref="Evaluator"/> is set and
/// it is triggered for the <paramref name="loggingEvent"/>
/// specified.</description>
/// </item>
/// </list>
/// <para>
/// Before the event is stored in the buffer it is fixed
/// (see <see cref="LoggingEvent.FixVolatileData(FixFlags)"/>) to ensure that
/// any data referenced by the event will be valid when the buffer
/// is processed.
/// </para>
/// </remarks>
override protected void Append(LoggingEvent loggingEvent)
{
// If the buffer size is set to 1 or less then the buffer will be
// sent immediately because there is not enough space in the buffer
// to buffer up more than 1 event. Therefore as a special case
// we don't use the buffer at all.
if (m_cb == null || m_bufferSize <= 1)
{
// Only send the event if we are in non lossy mode or the event is a triggering event
if ((!m_lossy) ||
(m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent)) ||
(m_lossyEvaluator != null && m_lossyEvaluator.IsTriggeringEvent(loggingEvent)))
{
if (m_eventMustBeFixed)
{
// Derive class expects fixed events
loggingEvent.Fix = this.Fix;
}
// Not buffering events, send immediately
SendBuffer(new LoggingEvent[] { loggingEvent } );
}
}
else
{
// Because we are caching the LoggingEvent beyond the
// lifetime of the Append() method we must fix any
// volatile data in the event.
loggingEvent.Fix = this.Fix;
// Add to the buffer, returns the event discarded from the buffer if there is no space remaining after the append
LoggingEvent discardedLoggingEvent = m_cb.Append(loggingEvent);
if (discardedLoggingEvent != null)
{
// Buffer is full and has had to discard an event
if (!m_lossy)
{
// Not lossy, must send all events
SendFromBuffer(discardedLoggingEvent, m_cb);
}
else
{
// Check if the discarded event should not be logged
if (m_lossyEvaluator == null || !m_lossyEvaluator.IsTriggeringEvent(discardedLoggingEvent))
{
// Clear the discarded event as we should not forward it
discardedLoggingEvent = null;
}
// Check if the event should trigger the whole buffer to be sent
if (m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent))
{
SendFromBuffer(discardedLoggingEvent, m_cb);
}
else if (discardedLoggingEvent != null)
{
// Just send the discarded event
SendBuffer(new LoggingEvent[] { discardedLoggingEvent } );
}
}
}
else
{
// Buffer is not yet full
// Check if the event should trigger the whole buffer to be sent
if (m_evaluator != null && m_evaluator.IsTriggeringEvent(loggingEvent))
{
SendFromBuffer(null, m_cb);
}
}
}
}
#endregion Override implementation of AppenderSkeleton
#region Protected Instance Methods
/// <summary>
/// Sends the contents of the buffer.
/// </summary>
/// <param name="firstLoggingEvent">The first logging event.</param>
/// <param name="buffer">The buffer containing the events that need to be send.</param>
/// <remarks>
/// <para>
/// The subclass must override <see cref="SendBuffer(LoggingEvent[])"/>.
/// </para>
/// </remarks>
virtual protected void SendFromBuffer(LoggingEvent firstLoggingEvent, CyclicBuffer buffer)
{
LoggingEvent[] bufferEvents = buffer.PopAll();
if (firstLoggingEvent == null)
{
SendBuffer(bufferEvents);
}
else if (bufferEvents.Length == 0)
{
SendBuffer(new LoggingEvent[] { firstLoggingEvent } );
}
else
{
// Create new array with the firstLoggingEvent at the head
LoggingEvent[] events = new LoggingEvent[bufferEvents.Length + 1];
Array.Copy(bufferEvents, 0, events, 1, bufferEvents.Length);
events[0] = firstLoggingEvent;
SendBuffer(events);
}
}
#endregion Protected Instance Methods
/// <summary>
/// Sends the events.
/// </summary>
/// <param name="events">The events that need to be send.</param>
/// <remarks>
/// <para>
/// The subclass must override this method to process the buffered events.
/// </para>
/// </remarks>
abstract protected void SendBuffer(LoggingEvent[] events);
#region Private Static Fields
/// <summary>
/// The default buffer size.
/// </summary>
/// <remarks>
/// The default size of the cyclic buffer used to store events.
/// This is set to 512 by default.
/// </remarks>
private const int DEFAULT_BUFFER_SIZE = 512;
#endregion Private Static Fields
#region Private Instance Fields
/// <summary>
/// The size of the cyclic buffer used to hold the logging events.
/// </summary>
/// <remarks>
/// Set to <see cref="DEFAULT_BUFFER_SIZE"/> by default.
/// </remarks>
private int m_bufferSize = DEFAULT_BUFFER_SIZE;
/// <summary>
/// The cyclic buffer used to store the logging events.
/// </summary>
private CyclicBuffer m_cb;
/// <summary>
/// The triggering event evaluator that causes the buffer to be sent immediately.
/// </summary>
/// <remarks>
/// The object that is used to determine if an event causes the entire
/// buffer to be sent immediately. This field can be <c>null</c>, which
/// indicates that event triggering is not to be done. The evaluator
/// can be set using the <see cref="Evaluator"/> property. If this appender
/// has the <see cref="m_lossy"/> (<see cref="Lossy"/> property) set to
/// <c>true</c> then an <see cref="Evaluator"/> must be set.
/// </remarks>
private ITriggeringEventEvaluator m_evaluator;
/// <summary>
/// Indicates if the appender should overwrite events in the cyclic buffer
/// when it becomes full, or if the buffer should be flushed when the
/// buffer is full.
/// </summary>
/// <remarks>
/// If this field is set to <c>true</c> then an <see cref="Evaluator"/> must
/// be set.
/// </remarks>
private bool m_lossy = false;
/// <summary>
/// The triggering event evaluator filters discarded events.
/// </summary>
/// <remarks>
/// The object that is used to determine if an event that is discarded should
/// really be discarded or if it should be sent to the appenders.
/// This field can be <c>null</c>, which indicates that all discarded events will
/// be discarded.
/// </remarks>
private ITriggeringEventEvaluator m_lossyEvaluator;
/// <summary>
/// Value indicating which fields in the event should be fixed
/// </summary>
/// <remarks>
/// By default all fields are fixed
/// </remarks>
private FixFlags m_fixFlags = FixFlags.All;
/// <summary>
/// The events delivered to the subclass must be fixed.
/// </summary>
private readonly bool m_eventMustBeFixed;
#endregion Private Instance Fields
}
}
| |
#region ExecutionTests.cs file
//
// Tests for StaMa state machine controller library
//
// Copyright (c) 2005-2015, Roland Schneider. All rights reserved.
//
#endregion
using System;
using StaMa;
#if !MF_FRAMEWORK
using NUnit.Framework;
#else
using MFUnitTest.Framework;
using Microsoft.SPOT;
#endif
namespace StaMaTest
{
[TestFixture]
public class ExecutionTests
{
[Test]
public void SendTriggerEvent_WithOrthogonalRegions_ExecutesActionsInExpectedSequence()
{
// Arrange
const string Startup = "*Startup*";
const string Finish = "*Finish*";
//## Begin StateAndTransitionNames57
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution1_OrthogonalRegions"
// at 07-22-2015 22:05:11 using StaMaShapes Version 2300
const string StateB = "StateB";
const string Transi8 = "Transi8";
const string Event6 = "Event6";
const string Transi6 = "Transi6";
const string Transi3 = "Transi3";
const string Event2 = "Event2";
const string Transi5 = "Transi5";
const string Event5 = "Event5";
const string StateB1A = "StateB1A";
const string StateB1B = "StateB1B";
const string StateB2A = "StateB2A";
const string StateB2B = "StateB2B";
const string Transi9 = "Transi9";
const string Event4 = "Event4";
const string StateB2B1A = "StateB2B1A";
const string StateB2B2A = "StateB2B2A";
const string Transi4 = "Transi4";
const string Event3 = "Event3";
const string StateB2B2B = "StateB2B2B";
const string StateB2B3A = "StateB2B3A";
const string Transi7 = "Transi7";
const string StateB2B3B = "StateB2B3B";
const string StateC = "StateC";
const string StateA = "StateA";
const string Transi1 = "Transi1";
const string Event1 = "Event1";
//## End StateAndTransitionNames57
//## Begin ActionNames
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution1_OrthogonalRegions"
// at 07-22-2015 22:05:11 using StaMaShapes Version 2300
const string EnterB = "EnterB";
const string ExitB = "ExitB";
const string DoB = "DoB";
const string EnterB1A = "EnterB1A";
const string ExitB1A = "ExitB1A";
const string DoB1A = "DoB1A";
const string EnterB1B = "EnterB1B";
const string ExitB1B = "ExitB1B";
const string DoB1B = "DoB1B";
const string EnterB2A = "EnterB2A";
const string ExitB2A = "ExitB2A";
const string DoB2A = "DoB2A";
const string EnterB2B = "EnterB2B";
const string ExitB2B = "ExitB2B";
const string DoB2B = "DoB2B";
const string EnterB2B1A = "EnterB2B1A";
const string ExitB2B1A = "ExitB2B1A";
const string DoB2B1A = "DoB2B1A";
const string EnterB2B2A = "EnterB2B2A";
const string ExitB2B2A = "ExitB2B2A";
const string DoB2B2A = "DoB2B2A";
const string EnterB2B2B = "EnterB2B2B";
const string ExitB2B2B = "ExitB2B2B";
const string DoB2B2B = "DoB2B2B";
const string EnterB2B3A = "EnterB2B3A";
const string ExitB2B3A = "ExitB2B3A";
const string DoB2B3A = "DoB2B3A";
const string EnterB2B3B = "EnterB2B3B";
const string ExitB2B3B = "ExitB2B3B";
const string DoB2B3B = "DoB2B3B";
const string EnterC = "EnterC";
const string ExitC = "ExitC";
const string DoC = "DoC";
const string EnterA = "EnterA";
const string ExitA = "ExitA";
const string DoA = "DoA";
//## End ActionNames
ActionRecorder recorder = new ActionRecorder();
StateMachineTemplate t = new StateMachineTemplate(StateMachineOptions.UseDoActions);
//## Begin StateMachineTemplate4
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution1_OrthogonalRegions"
// at 07-22-2015 22:05:12 using StaMaShapes Version 2300
t.Region(StateA, false);
t.State(StateB, recorder.CreateAction(EnterB), recorder.CreateAction(ExitB), recorder.CreateDoAction(DoB));
t.Transition(Transi8, StateB2A, StateC, Event6, null, null);
t.Transition(Transi6, new string[] {StateB1B, StateB2B}, StateA, Event6, null, null);
t.Transition(Transi3, StateB1A, new string[] {StateB1B, StateB2B}, Event2, null, null);
t.Transition(Transi5, StateB2B2A, new string[] {StateB1B, StateB2B2A}, Event5, null, null);
t.Region(StateB1A, false);
t.State(StateB1A, recorder.CreateAction(EnterB1A), recorder.CreateAction(ExitB1A), recorder.CreateDoAction(DoB1A));
t.EndState();
t.State(StateB1B, recorder.CreateAction(EnterB1B), recorder.CreateAction(ExitB1B), recorder.CreateDoAction(DoB1B));
t.EndState();
t.EndRegion();
t.Region(StateB2A, false);
t.State(StateB2A, recorder.CreateAction(EnterB2A), recorder.CreateAction(ExitB2A), recorder.CreateDoAction(DoB2A));
t.EndState();
t.State(StateB2B, recorder.CreateAction(EnterB2B), recorder.CreateAction(ExitB2B), recorder.CreateDoAction(DoB2B));
t.Transition(Transi9, StateB2B, Event4, null, null);
t.Region(StateB2B1A, false);
t.State(StateB2B1A, recorder.CreateAction(EnterB2B1A), recorder.CreateAction(ExitB2B1A), recorder.CreateDoAction(DoB2B1A));
t.EndState();
t.EndRegion();
t.Region(StateB2B2A, false);
t.State(StateB2B2A, recorder.CreateAction(EnterB2B2A), recorder.CreateAction(ExitB2B2A), recorder.CreateDoAction(DoB2B2A));
t.Transition(Transi4, StateB2B2B, Event3, null, null);
t.EndState();
t.State(StateB2B2B, recorder.CreateAction(EnterB2B2B), recorder.CreateAction(ExitB2B2B), recorder.CreateDoAction(DoB2B2B));
t.EndState();
t.EndRegion();
t.Region(StateB2B3A, true);
t.State(StateB2B3A, recorder.CreateAction(EnterB2B3A), recorder.CreateAction(ExitB2B3A), recorder.CreateDoAction(DoB2B3A));
t.Transition(Transi7, StateB2B3B, Event3, null, null);
t.EndState();
t.State(StateB2B3B, recorder.CreateAction(EnterB2B3B), recorder.CreateAction(ExitB2B3B), recorder.CreateDoAction(DoB2B3B));
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
t.EndState();
t.State(StateC, recorder.CreateAction(EnterC), recorder.CreateAction(ExitC), recorder.CreateDoAction(DoC));
t.EndState();
t.State(StateA, recorder.CreateAction(EnterA), recorder.CreateAction(ExitA), recorder.CreateDoAction(DoA));
t.Transition(Transi1, StateB, Event1, null, null);
t.EndState();
t.EndRegion();
//## End StateMachineTemplate4
StateMachine stateMachine = t.CreateStateMachine(this);
stateMachine.TraceStateChange = delegate(StateMachine stateMachinex, StateConfiguration stateConfigurationFrom, StateConfiguration stateConfigurationTo, Transition transition)
{
System.Console.WriteLine("TestExecConcurrent: Transition from {0} to {1} using {2}",
stateConfigurationFrom.ToString(),
stateConfigurationTo.ToString(),
(transition != null) ? transition.Name : "*");
};
stateMachine.TraceTestTransition = delegate(StateMachine stateMachinex, Transition transition, object triggerEvent, EventArgs eventArgs)
{
System.Console.WriteLine("TestExecConcurrent: Test transition {0} with event {1} in state {2}",
transition.ToString(),
(triggerEvent != null) ? triggerEvent.ToString() : "*",
stateMachine.ActiveStateConfiguration.ToString());
};
stateMachine.TraceDispatchTriggerEvent = delegate(StateMachine stateMachinex, object triggerEvent, EventArgs eventArgs)
{
string eventName = (triggerEvent != null) ? triggerEvent.ToString() : "*";
System.Console.WriteLine("TestExecConcurrent: Dispatch event {0} in state {1}", eventName, stateMachine.ActiveStateConfiguration.ToString());
};
Assert.That(recorder.RecordedActions, Is.EqualTo(new String[] {}), "Precondition not met: Actions were executed during state machine creation.");
foreach (TestData testData in new TestData[]
{
new TestData()
{
EventToSend = Startup,
ExpectedState = t.CreateStateConfiguration(new String[] { StateA }),
ExpectedActions = new String[] { EnterA, DoA, },
},
new TestData()
{
EventToSend = Event1,
ExpectedState = t.CreateStateConfiguration(new String[] { StateB1A, StateB2A }),
ExpectedActions = new String[] { ExitA, EnterB, EnterB1A, EnterB2A, DoB, DoB1A, DoB2A, },
},
new TestData()
{
EventToSend = Event2,
ExpectedState = t.CreateStateConfiguration(new String[] { StateB1B, StateB2B1A, StateB2B2A, StateB2B3A }),
ExpectedActions = new String[] { ExitB2A, ExitB1A, ExitB, EnterB, EnterB1B, EnterB2B, EnterB2B1A, EnterB2B2A, EnterB2B3A, DoB, DoB1B, DoB2B, DoB2B1A, DoB2B2A, DoB2B3A, },
},
new TestData()
{
EventToSend = Event3,
ExpectedState = t.CreateStateConfiguration(new String[] { StateB1B, StateB2B1A, StateB2B2B, StateB2B3B }),
ExpectedActions = new String[] { ExitB2B2A, EnterB2B2B, ExitB2B3A, EnterB2B3B, DoB, DoB1B, DoB2B, DoB2B1A, DoB2B2B, DoB2B3B, },
},
new TestData()
{
EventToSend = Event4,
ExpectedState = t.CreateStateConfiguration(new String[] { StateB1B, StateB2B1A, StateB2B2A, StateB2B3B }),
ExpectedActions = new String[] { ExitB2B3B, ExitB2B2B, ExitB2B1A, ExitB2B, EnterB2B, EnterB2B1A, EnterB2B2A, EnterB2B3B, DoB, DoB1B, DoB2B, DoB2B1A, DoB2B2A, DoB2B3B },
},
new TestData()
{
EventToSend = Event5,
ExpectedState = t.CreateStateConfiguration(new String[] { StateB1B, StateB2B1A, StateB2B2A, StateB2B3B }),
ExpectedActions = new String[] { ExitB2B3B, ExitB2B2A, ExitB2B1A, ExitB2B, ExitB1B, ExitB, EnterB, EnterB1B, EnterB2B, EnterB2B1A, EnterB2B2A, EnterB2B3B, DoB, DoB1B, DoB2B, DoB2B1A, DoB2B2A, DoB2B3B, },
},
new TestData()
{
EventToSend = Event6,
ExpectedState = t.CreateStateConfiguration(new String[] { StateA }),
ExpectedActions = new String[] { ExitB2B3B, ExitB2B2A, ExitB2B1A, ExitB2B, ExitB1B, ExitB, EnterA, DoA, },
},
new TestData()
{
EventToSend = Finish,
ExpectedState = t.CreateStateConfiguration(new String[] { }),
ExpectedActions = new String[] { ExitA },
},
})
{
recorder.Clear();
// Act
switch (testData.EventToSend)
{
case Startup:
stateMachine.Startup();
break;
case Finish:
stateMachine.Finish();
break;
default:
stateMachine.SendTriggerEvent(testData.EventToSend);
break;
}
// Assert
Assert.That(stateMachine.ActiveStateConfiguration.ToString(), Is.EqualTo(testData.ExpectedState.ToString()), testData.EventToSend + ": Active state not as expected.");
Assert.That(recorder.RecordedActions, Is.EqualTo(testData.ExpectedActions), testData.EventToSend + ": Unexpected entry and exit actions during state machine processing.");
}
}
[Test]
public void SendTriggerEvent_WithOrthogonalRegionsEarlyRegionExit_ExecutesActionsInExpectedSequence()
{
// Arrange
const string Startup = "*Startup*";
const string Finish = "*Finish*";
//## Begin StateAndTransitionNames19
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution2_OrthogonalRegionsEarlyExit"
// at 07-22-2015 22:05:14 using StaMaShapes Version 2300
const string StateA = "StateA";
const string StateA1A = "StateA1A";
const string StateA1A1A = "StateA1A1A";
const string Transi1 = "Transi1";
const string StateA1A2A = "StateA1A2A";
const string Transi2 = "Transi2";
const string StateA1A2B = "StateA1A2B";
const string StateA1B = "StateA1B";
const string StateA2A = "StateA2A";
const string Transi3 = "Transi3";
const string StateA2B = "StateA2B";
//## End StateAndTransitionNames19
//## Begin EventNames
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution2_OrthogonalRegionsEarlyExit"
// at 07-22-2015 22:05:14 using StaMaShapes Version 2300
const string Event = "Event";
//## End EventNames
//## Begin StateAndTransitionNames30
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution2_OrthogonalRegionsEarlyExit"
// at 07-22-2015 22:05:15 using StaMaShapes Version 2300
const string EnterA = "EnterA";
const string ExitA = "ExitA";
const string EnterA1A = "EnterA1A";
const string ExitA1A = "ExitA1A";
const string EnterA1A1A = "EnterA1A1A";
const string ExitA1A1A = "ExitA1A1A";
const string EnterA1A2A = "EnterA1A2A";
const string ExitA1A2A = "ExitA1A2A";
const string EnterA1A2B = "EnterA1A2B";
const string ExitA1A2B = "ExitA1A2B";
const string EnterA1B = "EnterA1B";
const string ExitA1B = "ExitA1B";
const string EnterA2A = "EnterA2A";
const string ExitA2A = "ExitA2A";
const string EnterA2B = "EnterA2B";
const string ExitA2B = "ExitA2B";
//## End StateAndTransitionNames30
ActionRecorder recorder = new ActionRecorder();
StateMachineTemplate t = new StateMachineTemplate(StateMachineOptions.UseDoActions);
//## Begin StateMachineTemplate18
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution2_OrthogonalRegionsEarlyExit"
// at 07-22-2015 22:05:15 using StaMaShapes Version 2300
t.Region(StateA, false);
t.State(StateA, recorder.CreateAction(EnterA), recorder.CreateAction(ExitA));
t.Region(StateA1A, false);
t.State(StateA1A, recorder.CreateAction(EnterA1A), recorder.CreateAction(ExitA1A));
t.Region(StateA1A1A, false);
t.State(StateA1A1A, recorder.CreateAction(EnterA1A1A), recorder.CreateAction(ExitA1A1A));
t.Transition(Transi1, StateA1B, Event, null, null);
t.EndState();
t.EndRegion();
t.Region(StateA1A2A, false);
t.State(StateA1A2A, recorder.CreateAction(EnterA1A2A), recorder.CreateAction(ExitA1A2A));
t.Transition(Transi2, StateA1A2B, Event, null, null);
t.EndState();
t.State(StateA1A2B, recorder.CreateAction(EnterA1A2B), recorder.CreateAction(ExitA1A2B));
t.EndState();
t.EndRegion();
t.EndState();
t.State(StateA1B, recorder.CreateAction(EnterA1B), recorder.CreateAction(ExitA1B));
t.EndState();
t.EndRegion();
t.Region(StateA2A, false);
t.State(StateA2A, recorder.CreateAction(EnterA2A), recorder.CreateAction(ExitA2A));
t.Transition(Transi3, StateA2B, Event, null, null);
t.EndState();
t.State(StateA2B, recorder.CreateAction(EnterA2B), recorder.CreateAction(ExitA2B));
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
//## End StateMachineTemplate18
Assert.That(recorder.RecordedActions, Is.EqualTo(new String[] {}), "Precondition not met: Actions were executed during state machine creation.");
StateMachine stateMachine = t.CreateStateMachine(this);
foreach (TestData testData in new TestData[]
{
new TestData()
{
EventToSend = Startup,
ExpectedState = t.CreateStateConfiguration(new String[] { StateA1A1A, StateA1A2A, StateA2A }),
ExpectedActions = new String[] { EnterA, EnterA1A, EnterA1A1A, EnterA1A2A, EnterA2A },
},
new TestData()
{
EventToSend = Event,
ExpectedState = t.CreateStateConfiguration(new String[] { StateA1B, StateA2B }),
ExpectedActions = new String[] { ExitA1A2A, ExitA1A1A, ExitA1A, EnterA1B, ExitA2A, EnterA2B },
},
new TestData()
{
EventToSend = Finish,
ExpectedState = t.CreateStateConfiguration(new String[] { }),
ExpectedActions = new String[] { ExitA2B, ExitA1B, ExitA },
}
})
{
recorder.Clear();
// Act
switch (testData.EventToSend)
{
case Startup:
stateMachine.Startup();
break;
case Finish:
stateMachine.Finish();
break;
default:
stateMachine.SendTriggerEvent(testData.EventToSend);
break;
}
// Assert
Assert.That(stateMachine.ActiveStateConfiguration.ToString(), Is.EqualTo(testData.ExpectedState.ToString()), testData.EventToSend + ": Active state not as expected.");
Assert.That(recorder.RecordedActions, Is.EqualTo(testData.ExpectedActions), testData.EventToSend + ": Unexpected entry and exit actions during state machine processing.");
}
}
[Test]
public void SendTriggerEvent_WithOrthogonalRegionsGuardState_ExecutesActionsInExpectedSequence()
{
// Arrange
const string Startup = "*Startup*";
const string Finish = "*Finish*";
//## Begin StateAndTransitionNames27
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution3_OrthogonalRegionsGuardState"
// at 07-22-2015 22:05:18 using StaMaShapes Version 2300
const string StateA = "StateA";
const string Transi3 = "Transi3";
const string StateA1A = "StateA1A";
const string Transi2 = "Transi2";
const string StateA1B = "StateA1B";
const string StateA2A = "StateA2A";
const string Transi1 = "Transi1";
const string StateA2B = "StateA2B";
const string StateA2C = "StateA2C";
//## End StateAndTransitionNames27
//## Begin StateAndTransitionNames26
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution3_OrthogonalRegionsGuardState"
// at 07-22-2015 22:05:17 using StaMaShapes Version 2300
const string Event3 = "Event3";
const string Event2 = "Event2";
const string Event1 = "Event1";
//## End StateAndTransitionNames26
//## Begin StateAndTransitionNames29
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution3_OrthogonalRegionsGuardState"
// at 07-22-2015 22:05:18 using StaMaShapes Version 2300
const string EnterA = "EnterA";
const string ExitA = "ExitA";
const string EnterA1A = "EnterA1A";
const string ExitA1A = "ExitA1A";
const string EnterA1B = "EnterA1B";
const string ExitA1B = "ExitA1B";
const string EnterA2A = "EnterA2A";
const string ExitA2A = "ExitA2A";
const string EnterA2B = "EnterA2B";
const string ExitA2B = "ExitA2B";
const string EnterA2C = "EnterA2C";
const string ExitA2C = "ExitA2C";
//## End StateAndTransitionNames29
ActionRecorder recorder = new ActionRecorder();
StateMachineTemplate t = new StateMachineTemplate(StateMachineOptions.UseDoActions);
//## Begin StateMachineTemplate28
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution3_OrthogonalRegionsGuardState"
// at 07-22-2015 22:05:18 using StaMaShapes Version 2300
t.Region(StateA, false);
t.State(StateA, recorder.CreateAction(EnterA), recorder.CreateAction(ExitA));
t.Transition(Transi3, new string[] {StateA1B, StateA2B}, StateA2C, Event3, null, null);
t.Region(StateA1A, false);
t.State(StateA1A, recorder.CreateAction(EnterA1A), recorder.CreateAction(ExitA1A));
t.Transition(Transi2, new string[] {StateA1A, StateA2B}, StateA1B, Event2, null, null);
t.EndState();
t.State(StateA1B, recorder.CreateAction(EnterA1B), recorder.CreateAction(ExitA1B));
t.EndState();
t.EndRegion();
t.Region(StateA2A, false);
t.State(StateA2A, recorder.CreateAction(EnterA2A), recorder.CreateAction(ExitA2A));
t.Transition(Transi1, StateA2B, Event1, null, null);
t.EndState();
t.State(StateA2B, recorder.CreateAction(EnterA2B), recorder.CreateAction(ExitA2B));
t.EndState();
t.State(StateA2C, recorder.CreateAction(EnterA2C), recorder.CreateAction(ExitA2C));
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
//## End StateMachineTemplate28
Assert.That(recorder.RecordedActions, Is.EqualTo(new String[] {}), "Precondition not met: Actions were executed during state machine creation.");
StateMachine stateMachine = t.CreateStateMachine(this);
foreach (TestData testData in new TestData[]
{
new TestData()
{
EventToSend = Startup,
ExpectedState = t.CreateStateConfiguration(new String[] { StateA1A, StateA2A }),
ExpectedActions = new String[] { EnterA, EnterA1A, EnterA2A },
},
new TestData()
{
EventToSend = Event2,
ExpectedState = t.CreateStateConfiguration(new string[] { StateA1A, StateA2A }),
ExpectedActions = new String[] { }
},
new TestData()
{
EventToSend = Event1,
ExpectedState = t.CreateStateConfiguration(new string[] { StateA1A, StateA2B }),
ExpectedActions = new String[] { ExitA2A, EnterA2B }
},
new TestData()
{
EventToSend = Event2,
ExpectedState = t.CreateStateConfiguration(new string[] { StateA1B, StateA2B }),
ExpectedActions = new String[] { ExitA1A, EnterA1B }
},
new TestData()
{
EventToSend = Event3,
ExpectedState = t.CreateStateConfiguration(new string[] { StateA1A, StateA2C }),
ExpectedActions = new String[] { ExitA2B, ExitA1B, ExitA, EnterA, EnterA1A, EnterA2C }
},
new TestData()
{
EventToSend = Finish,
ExpectedState = t.CreateStateConfiguration(new string[] { }),
ExpectedActions = new String[] { ExitA2C, ExitA1A, ExitA }
},
})
{
recorder.Clear();
// Act
switch (testData.EventToSend)
{
case Startup:
stateMachine.Startup();
break;
case Finish:
stateMachine.Finish();
break;
default:
stateMachine.SendTriggerEvent(testData.EventToSend);
break;
}
// Assert
Assert.That(stateMachine.ActiveStateConfiguration.ToString(), Is.EqualTo(testData.ExpectedState.ToString()), testData.EventToSend + ": Active state not as expected.");
Assert.That(recorder.RecordedActions, Is.EqualTo(testData.ExpectedActions), testData.EventToSend + ": Unexpected entry and exit actions during state machine processing.");
}
}
[Test]
public void SendTriggerEvent_WithDeepNesting_ExecutesActionsInExpectedSequence()
{
bool flag = false;
// Arrange
const string Startup = "*Startup*";
const string Finish = "*Finish*";
//## Begin StateAndTransitionNames5
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution4_DeepNesting"
// at 07-22-2015 22:05:21 using StaMaShapes Version 2300
const string State1 = "State1";
const string Transi1 = "Transi1";
const string Ev5 = "Ev5";
const string State2 = "State2";
const string Transi2 = "Transi2";
const string Ev1 = "Ev1";
const string State3 = "State3";
const string Transi3 = "Transi3";
const string Ev2 = "Ev2";
const string State4 = "State4";
const string State5 = "State5";
const string State7 = "State7";
const string State6 = "State6";
const string Transi4 = "Transi4";
const string Transi5 = "Transi5";
const string State8 = "State8";
const string State9 = "State9";
const string State10 = "State10";
const string Transi6 = "Transi6";
const string Ev4 = "Ev4";
const string State11 = "State11";
const string Transi7 = "Transi7";
const string Ev3 = "Ev3";
const string Transi8 = "Transi8";
const string State12 = "State12";
const string Transi9 = "Transi9";
const string State13 = "State13";
//## End StateAndTransitionNames5
//## Begin StateAndTransitionNames4
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution4_DeepNesting"
// at 07-22-2015 22:05:21 using StaMaShapes Version 2300
const string TransAct1To13 = "TransAct1To13";
const string Entry2 = "Entry2";
const string Exit2 = "Exit2";
const string TransAct2To6 = "TransAct2To6";
const string Entry3 = "Entry3";
const string Exit3 = "Exit3";
const string TransAct3To10 = "TransAct3To10";
const string Entry7 = "Entry7";
const string Exit7 = "Exit7";
const string Entry6 = "Entry6";
const string Exit6 = "Exit6";
const string TransAct10To3 = "TransAct10To3";
const string Entry11 = "Entry11";
const string Exit11 = "Exit11";
const string TransAct11To12 = "TransAct11To12";
const string Entry12 = "Entry12";
const string Exit12 = "Exit12";
//## End StateAndTransitionNames4
ActionRecorder recorder = new ActionRecorder();
StateMachineTemplate t = new StateMachineTemplate(StateMachineOptions.UseDoActions);
//## Begin StateMachineTemplate6
// Generated from <file:S:\StaMa_State_Machine_Controller_Library\StaMaShapesMaster.vst> page "UT_Execution4_DeepNesting"
// at 07-22-2015 22:05:21 using StaMaShapes Version 2300
t.Region(State1, false);
t.State(State1, null, null);
t.Transition(Transi1, State13, Ev5, null, recorder.CreateAction(TransAct1To13));
t.Region(State2, false);
t.State(State2, recorder.CreateAction(Entry2), recorder.CreateAction(Exit2));
t.Transition(Transi2, State6, Ev1, null, recorder.CreateAction(TransAct2To6));
t.Region(State3, false);
t.State(State3, recorder.CreateAction(Entry3), recorder.CreateAction(Exit3));
t.Transition(Transi3, State10, Ev2, null, recorder.CreateAction(TransAct3To10));
t.Region(State4, false);
t.State(State4, null, null);
t.Region(State5, false);
t.State(State5, null, null);
t.Region(State7, true);
t.State(State7, recorder.CreateAction(Entry7), recorder.CreateAction(Exit7));
t.EndState();
t.State(State6, recorder.CreateAction(Entry6), recorder.CreateAction(Exit6));
t.Transition(Transi4, State6, null, (stm, ev, args) => false, null);
t.Transition(Transi5, State6, Ev2, (stm, ev, args) => false, null);
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
t.EndState();
t.State(State8, null, null);
t.Region(State9, false);
t.State(State9, null, null);
t.Region(State10, false);
t.State(State10, null, null);
t.Transition(Transi6, State3, Ev4, null, recorder.CreateAction(TransAct10To3));
t.Region(State11, true);
t.State(State11, recorder.CreateAction(Entry11), recorder.CreateAction(Exit11));
t.Transition(Transi7, State12, Ev3, null, recorder.CreateAction(TransAct11To12));
t.Transition(Transi8, State12, null, (stm, ev, args) => flag, null);
t.EndState();
t.State(State12, recorder.CreateAction(Entry12), recorder.CreateAction(Exit12));
t.Transition(Transi9, State11, null, (stm, ev, args) => !flag, (stm, ev, args) => flag = true);
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
t.EndState();
t.EndRegion();
t.EndState();
t.State(State13, null, null);
t.EndState();
t.EndRegion();
//## End StateMachineTemplate6
Assert.That(recorder.RecordedActions, Is.EqualTo(new String[] { }), "Precondition not met: Actions were executed during state machine creation.");
StateMachine stateMachine = t.CreateStateMachine(this);
stateMachine.TraceStateChange = delegate(StateMachine stateMachinex, StateConfiguration stateConfigurationFrom, StateConfiguration stateConfigurationTo, Transition transition)
{
System.Console.WriteLine("TestExecDeepNest: Transition from {0} to {1} using {2}",
stateConfigurationFrom.ToString(),
stateConfigurationTo.ToString(),
(transition != null) ? transition.Name : "*");
};
stateMachine.TraceTestTransition = delegate(StateMachine stateMachinex, Transition transition, object triggerEvent, EventArgs eventArgs)
{
System.Console.WriteLine("TestExecDeepNest: Test transition {0} with event {1} in state {2}",
transition.ToString(),
(triggerEvent != null) ? triggerEvent.ToString() : "*",
stateMachine.ActiveStateConfiguration.ToString());
};
stateMachine.TraceDispatchTriggerEvent = delegate(StateMachine stateMachinex, object triggerEvent, EventArgs eventArgs)
{
string eventName = (triggerEvent != null) ? triggerEvent.ToString() : "*";
System.Console.WriteLine("TestExecDeepNest: Dispatch event {0} in state {1}", eventName, stateMachine.ActiveStateConfiguration.ToString());
};
foreach (TestData testData in new TestData[]
{
new TestData()
{
EventToSend = Startup,
ExpectedState = t.CreateStateConfiguration(new String[] { State7 }),
ExpectedActions = new String[] { Entry2, Entry3, Entry7 },
},
new TestData()
{
EventToSend = Ev1,
ExpectedState = t.CreateStateConfiguration(new string[] { State6 }),
ExpectedActions = new String[] { Exit7, Exit3, Exit2, TransAct2To6, Entry2, Entry3, Entry6 }
},
new TestData()
{
EventToSend = Ev2,
ExpectedState = t.CreateStateConfiguration(new string[] { State11 }),
ExpectedActions = new String[] { Exit6, Exit3, Exit2, TransAct3To10, Entry11 }
},
new TestData()
{
EventToSend = Ev3,
ExpectedState = t.CreateStateConfiguration(new string[] { State12 }),
ExpectedActions = new String[] { Exit11, TransAct11To12, Entry12, Exit12, Entry11, Exit11, Entry12 }
},
new TestData()
{
EventToSend = Ev4,
ExpectedState = t.CreateStateConfiguration(new string[] { State6 }),
ExpectedActions = new String[] { Exit12, TransAct10To3, Entry2, Entry3, Entry6 }
},
new TestData()
{
EventToSend = Ev5,
ExpectedState = t.CreateStateConfiguration(new string[] { State13 }),
ExpectedActions = new String[] { Exit6, Exit3, Exit2, TransAct1To13 }
},
new TestData()
{
EventToSend = Finish,
ExpectedState = t.CreateStateConfiguration(new string[] { }),
ExpectedActions = new String[] { }
},
})
{
recorder.Clear();
// Act
switch (testData.EventToSend)
{
case Startup:
stateMachine.Startup();
break;
case Finish:
stateMachine.Finish();
break;
default:
stateMachine.SendTriggerEvent(testData.EventToSend);
break;
}
// Assert
Assert.That(stateMachine.ActiveStateConfiguration.ToString(), Is.EqualTo(testData.ExpectedState.ToString()), testData.EventToSend + ": Active state not as expected.");
Assert.That(recorder.RecordedActions, Is.EqualTo(testData.ExpectedActions), testData.EventToSend + ": Unexpected entry and exit actions during state machine processing.");
}
}
private class TestData
{
public String EventToSend { get; set; }
public StateConfiguration ExpectedState { get; set; }
public String[] ExpectedActions { get; set; }
}
}
}
| |
/*
Copyright (c) 2004-2006 Tomas Matousek, Vaclav Novak, and Martin Maly.
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.Collections;
using System.Collections.Generic;
using System.Reflection.Emit;
using PHP.Core;
using PHP.Core.AST;
using PHP.Core.Parsers;
using PHP.Core.Emit;
using System.Diagnostics;
namespace PHP.Core.Compiler.AST
{
partial class NodeCompilers
{
#region IfStmt
[NodeCompiler(typeof(IfStmt), Singleton = true)]
sealed class IfStmtCompiler : StatementCompiler<IfStmt>
{
internal override Statement Analyze(IfStmt node, Analyzer analyzer)
{
if (analyzer.IsThisCodeUnreachable())
{
analyzer.ReportUnreachableCode(node.Span);
return EmptyStmt.Unreachable;
}
ExInfoFromParent info = ExInfoFromParent.DefaultExInfo;
var/*!*/conditions = node.Conditions;
bool is_first = true;
int remaining = conditions.Count;
int last_non_null = -1;
for (int i = 0; i < conditions.Count; i++)
{
// "else":
if (conditions[i].Condition == null)
{
Debug.Assert(i > 0);
if (!is_first) analyzer.EnterConditionalCode();
conditions[i].Statement = conditions[i].Statement.Analyze(analyzer);
if (!is_first) analyzer.LeaveConditionalCode();
last_non_null = i;
break;
}
// all but the condition before the first non-evaluable including are conditional:
if (!is_first) analyzer.EnterConditionalCode();
Evaluation cond_eval = conditions[i].Condition.Analyze(analyzer, info);
if (!is_first) analyzer.LeaveConditionalCode();
if (cond_eval.HasValue)
{
if (Convert.ObjectToBoolean(cond_eval.Value))
{
// condition is evaluated to be true //
// analyze the first statement unconditionally, the the others conditionally:
if (!is_first) analyzer.EnterConditionalCode();
conditions[i].Statement = conditions[i].Statement.Analyze(analyzer);
if (!is_first) analyzer.LeaveConditionalCode();
// the remaining conditions are unreachable:
for (int j = i + 1; j < conditions.Count; j++)
{
conditions[j].Statement.ReportUnreachable(analyzer);
conditions[j] = null;
remaining--;
}
conditions[i].Condition = null;
last_non_null = i;
break;
}
else
{
// condition is evaluated to be false //
// remove the condition, report unreachable code:
conditions[i].Statement.ReportUnreachable(analyzer);
conditions[i] = null;
remaining--;
}
}
else
{
// condition is not evaluable:
conditions[i].Condition = cond_eval.Expression;
// analyze statement conditinally:
analyzer.EnterConditionalCode();
conditions[i].Statement = conditions[i].Statement.Analyze(analyzer);
analyzer.LeaveConditionalCode();
is_first = false;
last_non_null = i;
}
}
if (remaining == 0)
return EmptyStmt.Skipped;
Debug.Assert(last_non_null != -1 && conditions[last_non_null] != null);
// only "else" remained:
if (remaining == 1 && conditions[last_non_null].Condition == null)
return conditions[last_non_null].Statement;
// compact the list (remove nulls):
if (remaining < conditions.Count)
{
List<ConditionalStmt> compacted = new List<ConditionalStmt>(remaining);
foreach (ConditionalStmt condition in conditions)
{
if (condition != null)
compacted.Add(condition);
}
node.Conditions = compacted;
}
return node;
}
internal override void Emit(IfStmt node, CodeGenerator codeGenerator)
{
Statistics.AST.AddNode("IfStmt");
var/*!*/conditions = node.Conditions;
Debug.Assert(conditions.Count > 0);
// marks a sequence point containing whole condition:
codeGenerator.MarkSequencePoint(conditions[0].Condition); // NOTE: (J) when emitting a statement, sequence point has to be marked. Normally it is done in Statement.Emit()
ILEmitter il = codeGenerator.IL;
Label exit_label = il.DefineLabel();
Label false_label = il.DefineLabel();
// IF
codeGenerator.EmitConversion(conditions[0].Condition, PhpTypeCode.Boolean);
il.Emit(OpCodes.Brfalse, false_label);
conditions[0].Statement.Emit(codeGenerator);
// (J) Mark the end of condition body so debugger will jump off the block properly
codeGenerator.MarkSequencePoint(conditions[0].Statement.Span.End);
il.Emit(OpCodes.Br, exit_label);
// ELSEIF:
for (int i = 1; i < conditions.Count && conditions[i].Condition != null; i++)
{
il.MarkLabel(false_label, true);
false_label = il.DefineLabel();
// IF (!<(bool) condition>)
codeGenerator.MarkSequencePoint(conditions[i].Condition); // marks a sequence point of the condition "statement"
codeGenerator.EmitConversion(conditions[i].Condition, PhpTypeCode.Boolean);
il.Emit(OpCodes.Brfalse, false_label);
conditions[i].Statement.Emit(codeGenerator);
il.Emit(OpCodes.Br, exit_label);
}
il.MarkLabel(false_label, true);
// ELSE
if (conditions[conditions.Count - 1].Condition == null)
conditions[conditions.Count - 1].Statement.Emit(codeGenerator);
il.MarkLabel(exit_label, true);
}
}
#endregion
#region ConditionalStmt
[NodeCompiler(typeof(ConditionalStmt), Singleton = true)]
sealed class ConditionalStmtCompiler : INodeCompiler
{
}
#endregion
}
}
| |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Threading.Tasks;
using Xunit;
using VerifyCS = Test.Utilities.CSharpSecurityCodeFixVerifier<
Microsoft.NetFramework.CSharp.Analyzers.CSharpDoNotUseInsecureDtdProcessingInApiDesignAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
using VerifyVB = Test.Utilities.VisualBasicSecurityCodeFixVerifier<
Microsoft.NetFramework.VisualBasic.Analyzers.BasicDoNotUseInsecureDtdProcessingInApiDesignAnalyzer,
Microsoft.CodeAnalysis.Testing.EmptyCodeFixProvider>;
namespace Microsoft.NetFramework.Analyzers.UnitTests
{
public partial class DoNotUseInsecureDtdProcessingInApiDesignAnalyzerTests
{
[Fact]
public async Task TextReaderDerivedTypeWithEmptyConstructorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass () {}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeNullResolverAndProhibitInOnlyCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlTextReaderDerivedTypeUrlResolverAndProhibitInOnlyCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = new XmlUrlResolver();
this.DtdProcessing = DtdProcessing.Prohibit;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = New XmlUrlResolver()
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSecureResolverAndParseInOnlyCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass(XmlSecureResolver resolver)
{
this.XmlResolver = resolver;
this.DtdProcessing = DtdProcessing.Parse;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New(resolver As XmlSecureResolver)
Me.XmlResolver = resolver
Me.DtdProcessing = DtdProcessing.Parse
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeNullResolverInOnlyCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeIgnoreInOnlyCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass(XmlSecureResolver resolver)
{
this.DtdProcessing = DtdProcessing.Ignore;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New(resolver As XmlSecureResolver)
Me.DtdProcessing = DtdProcessing.Ignore
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetInsecureResolverInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Ignore;
}
public TestClass(XmlResolver resolver)
{
this.XmlResolver = resolver;
this.DtdProcessing = DtdProcessing.Ignore;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Ignore
End Sub
Public Sub New(resolver As XmlResolver)
Me.XmlResolver = resolver
Me.DtdProcessing = DtdProcessing.Ignore
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSecureSettingsForVariableInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass(XmlTextReader reader)
{
reader.XmlResolver = null;
reader.DtdProcessing = DtdProcessing.Ignore;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New(reader As XmlTextReader)
reader.XmlResolver = Nothing
reader.DtdProcessing = DtdProcessing.Ignore
End Sub
End Class
End Namespace
"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSecureSettingsWithOutThisInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass(XmlTextReader reader)
{
reader.XmlResolver = null;
XmlResolver = null;
DtdProcessing = DtdProcessing.Prohibit;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New(reader As XmlTextReader)
reader.XmlResolver = Nothing
XmlResolver = Nothing
DtdProcessing = DtdProcessing.Prohibit
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetSecureSettingsToAXmlTextReaderFieldInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
private XmlTextReader reader = new XmlTextReader(""path"");
public TestClass()
{
this.reader.XmlResolver = null;
this.reader.DtdProcessing = DtdProcessing.Ignore;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private reader As New XmlTextReader("""")
Public Sub New()
Me.reader.XmlResolver = Nothing
Me.reader.DtdProcessing = DtdProcessing.Ignore
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetSecureSettingsAtLeastOnceInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass(bool flag)
{
if (flag)
{
XmlResolver = null;
DtdProcessing = DtdProcessing.Ignore;
}
else
{
XmlResolver = new XmlUrlResolver();
DtdProcessing = DtdProcessing.Parse;
}
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New(flag As Boolean)
If flag Then
XmlResolver = Nothing
DtdProcessing = DtdProcessing.Ignore
Else
XmlResolver = New XmlUrlResolver()
DtdProcessing = DtdProcessing.Parse
End If
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetSecureSettingsAtLeastOnceInCtorShouldNotGenerateDiagnosticFalseNeg()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass(bool flag)
{
if (flag)
{
XmlResolver = null;
DtdProcessing = DtdProcessing.Parse;
}
else
{
XmlResolver = new XmlUrlResolver();
DtdProcessing = DtdProcessing.Ignore;
}
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New(flag As Boolean)
If flag Then
XmlResolver = Nothing
DtdProcessing = DtdProcessing.Parse
Else
XmlResolver = New XmlUrlResolver()
DtdProcessing = DtdProcessing.Ignore
End If
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetIgnoreToHidingFieldInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
DtdProcessing DtdProcessing;
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Ignore;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private DtdProcessing As DtdProcessing
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Ignore
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetNullToHidingFieldInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
XmlResolver XmlResolver;
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Ignore;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private XmlResolver As XmlResolver
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Ignore
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetNullToBaseXmlResolverInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
XmlResolver XmlResolver;
public TestClass()
{
base.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private XmlResolver As XmlResolver
Public Sub New()
MyBase.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetProhibitToBaseInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
DtdProcessing DtdProcessing;
public TestClass()
{
this.XmlResolver = null;
base.DtdProcessing = DtdProcessing.Prohibit;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private DtdProcessing As DtdProcessing
Public Sub New()
Me.XmlResolver = Nothing
MyBase.DtdProcessing = DtdProcessing.Prohibit
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetSecureSettingsToBaseWithHidingFieldsInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
DtdProcessing DtdProcessing;
XmlResolver XmlResolver;
public TestClass()
{
base.XmlResolver = null;
base.DtdProcessing = DtdProcessing.Prohibit;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private DtdProcessing As DtdProcessing
Private XmlResolver As XmlResolver
Public Sub New()
MyBase.XmlResolver = Nothing
MyBase.DtdProcessing = DtdProcessing.Prohibit
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetSecureSettingsToBaseInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
public TestClass()
{
base.XmlResolver = null;
base.DtdProcessing = DtdProcessing.Prohibit;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Public Sub New()
MyBase.XmlResolver = Nothing
MyBase.DtdProcessing = DtdProcessing.Prohibit
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetUrlResolverToBaseXmlResolverInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
DtdProcessing DtdProcessing;
XmlResolver XmlResolver;
public TestClass()
{
base.XmlResolver = new XmlUrlResolver();
base.DtdProcessing = DtdProcessing.Prohibit;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private DtdProcessing As DtdProcessing
Private XmlResolver As XmlResolver
Public Sub New()
MyBase.XmlResolver = New XmlUrlResolver()
MyBase.DtdProcessing = DtdProcessing.Prohibit
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetNullToHidingPropertyInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
XmlResolver XmlResolver { set; get; }
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Ignore;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private Property XmlResolver() As XmlResolver
Get
Return m_XmlResolver
End Get
Set
m_XmlResolver = Value
End Set
End Property
Private m_XmlResolver As XmlResolver
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Ignore
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetProhibitToHidingPropertyInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
DtdProcessing DtdProcessing { set; get; }
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Ignore;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private Property DtdProcessing() As DtdProcessing
Get
Return m_DtdProcessing
End Get
Set
m_DtdProcessing = Value
End Set
End Property
Private m_DtdProcessing As DtdProcessing
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Ignore
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetSecureSettingsToHidingPropertiesInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
DtdProcessing DtdProcessing { set; get; }
XmlResolver XmlResolver { set; get; }
public TestClass()
{
this.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Ignore;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private Property DtdProcessing() As DtdProcessing
Get
Return m_DtdProcessing
End Get
Set
m_DtdProcessing = Value
End Set
End Property
Private m_DtdProcessing As DtdProcessing
Private Property XmlResolver() As XmlResolver
Get
Return m_XmlResolver
End Get
Set
m_XmlResolver = Value
End Set
End Property
Private m_XmlResolver As XmlResolver
Public Sub New()
Me.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Ignore
End Sub
End Class
End Namespace"
);
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetNullToBaseWithHidingPropertyInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
XmlResolver XmlResolver { set; get; }
public TestClass()
{
base.XmlResolver = null;
this.DtdProcessing = DtdProcessing.Prohibit;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private Property XmlResolver() As XmlResolver
Get
Return m_XmlResolver
End Get
Set
m_XmlResolver = Value
End Set
End Property
Private m_XmlResolver As XmlResolver
Public Sub New()
MyBase.XmlResolver = Nothing
Me.DtdProcessing = DtdProcessing.Prohibit
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetIgnoreToBaseWithHidingPropertyInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
DtdProcessing DtdProcessing { set; get; }
public TestClass()
{
this.XmlResolver = null;
base.DtdProcessing = DtdProcessing.Ignore;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private Property DtdProcessing() As DtdProcessing
Get
Return m_DtdProcessing
End Get
Set
m_DtdProcessing = Value
End Set
End Property
Private m_DtdProcessing As DtdProcessing
Public Sub New()
Me.XmlResolver = Nothing
MyBase.DtdProcessing = DtdProcessing.Ignore
End Sub
End Class
End Namespace");
}
[Fact]
public async Task XmlTextReaderDerivedTypeSetParseToBaseWithHidingPropertyInCtorShouldNotGenerateDiagnostic()
{
await VerifyCS.VerifyAnalyzerAsync(@"
using System;
using System.Xml;
namespace TestNamespace
{
class TestClass : XmlTextReader
{
XmlResolver XmlResolver { set; get; }
DtdProcessing DtdProcessing { set; get; }
public TestClass()
{
base.XmlResolver = null;
base.DtdProcessing = DtdProcessing.Parse;
}
}
}"
);
await VerifyVB.VerifyAnalyzerAsync(@"
Imports System.Xml
Namespace TestNamespace
Class TestClass
Inherits XmlTextReader
Private Property XmlResolver() As XmlResolver
Get
Return m_XmlResolver
End Get
Set
m_XmlResolver = Value
End Set
End Property
Private m_XmlResolver As XmlResolver
Private Property DtdProcessing() As DtdProcessing
Get
Return m_DtdProcessing
End Get
Set
m_DtdProcessing = Value
End Set
End Property
Private m_DtdProcessing As DtdProcessing
Public Sub New()
MyBase.XmlResolver = Nothing
MyBase.DtdProcessing = DtdProcessing.Parse
End Sub
End Class
End Namespace"
);
}
}
}
| |
using System;
/// <summary>
/// Char.IsSurrogate(Char)
/// Indicates whether the character at the specified position in a specified string is categorized
/// as a surrogate.
/// </summary>
public class CharIsSurrogate
{
private const int c_MIN_STR_LEN = 2;
private const int c_MAX_STR_LEN = 256;
private const char c_HIGH_SURROGATE_START = '\ud800';
private const char c_HIGH_SURROGATE_END = '\udbff';
private const char c_LOW_SURROGATE_START = '\udc00';
private const char c_LOW_SURROGATE_END = '\udfff';
public static int Main()
{
CharIsSurrogate testObj = new CharIsSurrogate();
TestLibrary.TestFramework.BeginTestCase("for method: Char.IsSurrogate(Char)");
if (testObj.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
TestLibrary.TestFramework.LogInformation("[Negaitive]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
return retVal;
}
#region Positive tests
public bool PosTest1()
{
char ch;
//Generate a low surrogate character for validate
int count = (int)c_LOW_SURROGATE_END - (int)c_LOW_SURROGATE_START + 1;
int offset = TestLibrary.Generator.GetInt32(-55) % count;
ch = (char)((int)c_LOW_SURROGATE_START + offset);
return this.DoTest("PosTest1: Low surrogate character",
"P001", "001", "002", ch, true);
}
public bool PosTest2()
{
char ch;
//Generate a hign surrogate character for validate
int count = (int)c_HIGH_SURROGATE_END - (int)c_HIGH_SURROGATE_START + 1;
int offset = TestLibrary.Generator.GetInt32(-55) % count;
ch = (char)((int)c_HIGH_SURROGATE_START + offset);
return this.DoTest("PosTest2: Hign surrogate character.",
"P002", "003", "004", ch, true);
}
public bool PosTest3()
{
//Generate a non surrogate character for validate
char ch = TestLibrary.Generator.GetCharLetter(-55);
return this.DoTest("PosTest3: Non-surrogate character.",
"P003", "005", "006", ch, false);
}
#endregion
#region Helper method for positive tests
private bool DoTest(string testDesc,
string testId,
string errorNum1,
string errorNum2,
char ch,
bool expectedResult)
{
bool retVal = true;
string errorDesc;
TestLibrary.TestFramework.BeginScenario(testDesc);
try
{
string str = new string(ch, 1);
bool actualResult = char.IsSurrogate(str, 0);
if (expectedResult != actualResult)
{
if (expectedResult)
{
errorDesc = string.Format("Character \\u{0:x} should belong to surrogate.", (int)ch);
}
else
{
errorDesc = string.Format("Character \\u{0:x} does not belong to surrogate.", (int)ch);
}
TestLibrary.TestFramework.LogError(errorNum1 + " TestId-" + testId, errorDesc);
retVal = false;
}
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nCharacter is \\u{0:x}", ch);
TestLibrary.TestFramework.LogError(errorNum2 + " TestId-" + testId, errorDesc);
retVal = false;
}
return retVal;
}
#endregion
#region Negative tests
//ArgumentNullException
public bool NegTest1()
{
bool retVal = true;
const string c_TEST_ID = "N001";
const string c_TEST_DESC = "NegTest1: String is a null reference (Nothing in Visual Basic).";
string errorDesc;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
index = TestLibrary.Generator.GetInt32(-55);
char.IsSurrogate(null, index);
errorDesc = "ArgumentNullException is not thrown as expected, index is " + index;
TestLibrary.TestFramework.LogError("007" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentNullException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e + "\n Index is " + index;
TestLibrary.TestFramework.LogError("008" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
//ArgumentOutOfRangeException
public bool NegTest2()
{
bool retVal = true;
const string c_TEST_ID = "N002";
const string c_TEST_DESC = "NegTest2: Index is too great.";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = str.Length + TestLibrary.Generator.GetInt16(-55);
index = str.Length;
char.IsSurrogate(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("009" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index);
TestLibrary.TestFramework.LogError("010" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
const string c_TEST_ID = "N003";
const string c_TEST_DESC = "NegTest3: Index is a negative value";
string errorDesc;
string str = string.Empty;
int index = 0;
TestLibrary.TestFramework.BeginScenario(c_TEST_DESC);
try
{
str = TestLibrary.Generator.GetString(-55, false, c_MIN_STR_LEN, c_MAX_STR_LEN);
index = -1 * (TestLibrary.Generator.GetInt16(-55));
char.IsSurrogate(str, index);
errorDesc = "ArgumentOutOfRangeException is not thrown as expected";
TestLibrary.TestFramework.LogError("011" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
catch (ArgumentOutOfRangeException)
{
}
catch (Exception e)
{
errorDesc = "Unexpected exception: " + e;
errorDesc += string.Format("\nThe string is {0}, and the index is {1}", str, index);
TestLibrary.TestFramework.LogError("012" + " TestId-" + c_TEST_ID, errorDesc);
retVal = false;
}
return retVal;
}
#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.Numerics;
using System.Text;
using Xunit;
namespace System.SpanTests
{
public static partial class ReadOnlySpanTests
{
[Fact]
public static void ZeroLengthIndexOf_Byte()
{
ReadOnlySpan<byte> sp = new ReadOnlySpan<byte>(Array.Empty<byte>());
int idx = sp.IndexOf(0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOf_Byte()
{
for (int length = 0; length <= byte.MaxValue; length++)
{
byte[] a = new byte[length];
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
for (int i = 0; i < length; i++)
{
byte target0 = default(byte);
int idx = span.IndexOf(target0);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatch_Byte()
{
for (int length = 0; length <= byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
a[i] = (byte)(i + 1);
}
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
byte target = a[targetIndex];
int idx = span.IndexOf(target);
Assert.Equal(targetIndex, idx);
}
}
}
[Fact]
public static void TestNoMatch_Byte()
{
var rnd = new Random(42);
for (int length = 0; length <= byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte target = (byte)rnd.Next(0, 256);
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == target ? (byte)(target + 1) : val;
}
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
int idx = span.IndexOf(target);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestAllignmentNoMatch_Byte()
{
byte[] array = new byte[4 * Vector<byte>.Count];
for (var i = 0; i < Vector<byte>.Count; i++)
{
var span = new ReadOnlySpan<byte>(array, i, 3 * Vector<byte>.Count);
int idx = span.IndexOf((byte)'1');
Assert.Equal(-1, idx);
span = new ReadOnlySpan<byte>(array, i, 3 * Vector<byte>.Count - 3);
idx = span.IndexOf((byte)'1');
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestAllignmentMatch_Byte()
{
byte[] array = new byte[4 * Vector<byte>.Count];
for (int i = 0; i < array.Length; i++)
{
array[i] = 5;
}
for (var i = 0; i < Vector<byte>.Count; i++)
{
var span = new ReadOnlySpan<byte>(array, i, 3 * Vector<byte>.Count);
int idx = span.IndexOf(5);
Assert.Equal(0, idx);
span = new ReadOnlySpan<byte>(array, i, 3 * Vector<byte>.Count - 3);
idx = span.IndexOf(5);
Assert.Equal(0, idx);
}
}
[Fact]
public static void TestMultipleMatch_Byte()
{
for (int length = 2; length <= byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == 200 ? (byte)201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
int idx = span.IndexOf(200);
Assert.Equal(length - 2, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRange_Byte()
{
for (int length = 0; length <= byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 99;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 1, length);
int index = span.IndexOf(99);
Assert.Equal(-1, index);
}
}
[Theory]
[InlineData("a", "a", 'a', 0)]
[InlineData("ab", "a", 'a', 0)]
[InlineData("aab", "a", 'a', 0)]
[InlineData("acab", "a", 'a', 0)]
[InlineData("acab", "c", 'c', 1)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "lo", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "ol", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "ll", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "rml", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyz", "mlr", 'l', 11)]
[InlineData("abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)]
[InlineData("aaaaaaaaaaalmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'l', 11)]
[InlineData("aaaaaaaaaaacmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'm', 12)]
[InlineData("aaaaaaaaaaarmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz", "lmr", 'r', 11)]
[InlineData("/localhost:5000/PATH/%2FPATH2/ HTTP/1.1", " %?", '%', 21)]
[InlineData("/localhost:5000/PATH/%2FPATH2/?key=value HTTP/1.1", " %?", '%', 21)]
[InlineData("/localhost:5000/PATH/PATH2/?key=value HTTP/1.1", " %?", '?', 27)]
[InlineData("/localhost:5000/PATH/PATH2/ HTTP/1.1", " %?", ' ', 27)]
public static void IndexOfAnyStrings_Byte(string raw, string search, char expectResult, int expectIndex)
{
var buffers = Encoding.UTF8.GetBytes(raw);
var span = new ReadOnlySpan<byte>(buffers);
var searchFor = search.ToCharArray();
var searchForBytes = Encoding.UTF8.GetBytes(searchFor);
var index = -1;
if (searchFor.Length == 1)
{
index = span.IndexOf((byte)searchFor[0]);
}
else if (searchFor.Length == 2)
{
index = span.IndexOfAny((byte)searchFor[0], (byte)searchFor[1]);
}
else if (searchFor.Length == 3)
{
index = span.IndexOfAny((byte)searchFor[0], (byte)searchFor[1], (byte)searchFor[2]);
}
else
{
index = span.IndexOfAny(new ReadOnlySpan<byte>(searchForBytes));
}
var found = span[index];
Assert.Equal((byte)expectResult, found);
Assert.Equal(expectIndex, index);
}
[Fact]
public static void ZeroLengthIndexOfTwo_Byte()
{
ReadOnlySpan<byte> sp = new ReadOnlySpan<byte>(Array.Empty<byte>());
int idx = sp.IndexOfAny(0, 0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOfTwo_Byte()
{
Random rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
byte[] targets = { default(byte), 99 };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 2) == 0 ? 0 : 1;
byte target0 = targets[index];
byte target1 = targets[(index + 1) % 2];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchTwo_Byte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
a[i] = (byte)(i + 1);
}
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = 0;
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = a[targetIndex + 1];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 1; targetIndex++)
{
byte target0 = 0;
byte target1 = a[targetIndex + 1];
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(targetIndex + 1, idx);
}
}
}
[Fact]
public static void TestNoMatchTwo_Byte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte target0 = (byte)rnd.Next(1, 256);
byte target1 = (byte)rnd.Next(1, 256);
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
int idx = span.IndexOfAny(target0, target1);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchTwo_Byte()
{
for (int length = 3; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == 200 ? (byte)201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
int idx = span.IndexOfAny(200, 200);
Assert.Equal(length - 3, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeTwo_Byte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 98;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 1, length - 1);
int index = span.IndexOfAny(99, 98);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 99;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 1, length - 1);
int index = span.IndexOfAny(99, 99);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOfThree_Byte()
{
ReadOnlySpan<byte> sp = new ReadOnlySpan<byte>(Array.Empty<byte>());
int idx = sp.IndexOfAny(0, 0, 0);
Assert.Equal(-1, idx);
}
[Fact]
public static void DefaultFilledIndexOfThree_Byte()
{
Random rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
byte[] targets = { default(byte), 99, 98 };
for (int i = 0; i < length; i++)
{
int index = rnd.Next(0, 3);
byte target0 = targets[index];
byte target1 = targets[(index + 1) % 2];
byte target2 = targets[(index + 1) % 3];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchThree_Byte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
a[i] = (byte)(i + 1);
}
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = 0;
byte target2 = 0;
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
byte target0 = a[targetIndex];
byte target1 = a[targetIndex + 1];
byte target2 = a[targetIndex + 2];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 2; targetIndex++)
{
byte target0 = 0;
byte target1 = 0;
byte target2 = a[targetIndex + 2];
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(targetIndex + 2, idx);
}
}
}
[Fact]
public static void TestNoMatchThree_Byte()
{
var rnd = new Random(42);
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte target0 = (byte)rnd.Next(1, 256);
byte target1 = (byte)rnd.Next(1, 256);
byte target2 = (byte)rnd.Next(1, 256);
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
int idx = span.IndexOfAny(target0, target1, target2);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchThree_Byte()
{
for (int length = 4; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == 200 ? (byte)201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
a[length - 4] = 200;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
int idx = span.IndexOfAny(200, 200, 200);
Assert.Equal(length - 4, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeThree_Byte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 98;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 1, length - 1);
int index = span.IndexOfAny(99, 98, 99);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 99;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 1, length - 1);
int index = span.IndexOfAny(99, 99, 99);
Assert.Equal(-1, index);
}
}
[Fact]
public static void ZeroLengthIndexOfMany_Byte()
{
ReadOnlySpan<byte> sp = new ReadOnlySpan<byte>(Array.Empty<byte>());
var values = new ReadOnlySpan<byte>(new byte[] { 0, 0, 0, 0 });
int idx = sp.IndexOfAny(values);
Assert.Equal(-1, idx);
values = new ReadOnlySpan<byte>(new byte[] { });
idx = sp.IndexOfAny(values);
Assert.Equal(0, idx);
}
[Fact]
public static void DefaultFilledIndexOfMany_Byte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
var values = new ReadOnlySpan<byte>(new byte[] { default(byte), 99, 98, 0 });
for (int i = 0; i < length; i++)
{
int idx = span.IndexOfAny(values);
Assert.Equal(0, idx);
}
}
}
[Fact]
public static void TestMatchMany_Byte()
{
for (int length = 0; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
a[i] = (byte)(i + 1);
}
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
for (int targetIndex = 0; targetIndex < length; targetIndex++)
{
var values = new ReadOnlySpan<byte>(new byte[] { a[targetIndex], 0, 0, 0 });
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
var values = new ReadOnlySpan<byte>(new byte[] { a[targetIndex], a[targetIndex + 1], a[targetIndex + 2], a[targetIndex + 3] });
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex, idx);
}
for (int targetIndex = 0; targetIndex < length - 3; targetIndex++)
{
var values = new ReadOnlySpan<byte>(new byte[] { 0, 0, 0, a[targetIndex + 3] });
int idx = span.IndexOfAny(values);
Assert.Equal(targetIndex + 3, idx);
}
}
}
[Fact]
public static void TestMatchValuesLargerMany_Byte()
{
var rnd = new Random(42);
for (int length = 2; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
int expectedIndex = length / 2;
for (int i = 0; i < length; i++)
{
if (i == expectedIndex)
{
continue;
}
a[i] = 255;
}
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
byte[] targets = new byte[length * 2];
for (int i = 0; i < targets.Length; i++)
{
if (i == length + 1)
{
continue;
}
targets[i] = (byte)rnd.Next(1, 255);
}
var values = new ReadOnlySpan<byte>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(expectedIndex, idx);
}
}
[Fact]
public static void TestNoMatchMany_Byte()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte[] targets = new byte[length];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = (byte)rnd.Next(1, 256);
}
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
var values = new ReadOnlySpan<byte>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestNoMatchValuesLargerMany_Byte()
{
var rnd = new Random(42);
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
byte[] targets = new byte[length * 2];
for (int i = 0; i < targets.Length; i++)
{
targets[i] = (byte)rnd.Next(1, 256);
}
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
var values = new ReadOnlySpan<byte>(targets);
int idx = span.IndexOfAny(values);
Assert.Equal(-1, idx);
}
}
[Fact]
public static void TestMultipleMatchMany_Byte()
{
for (int length = 5; length < byte.MaxValue; length++)
{
byte[] a = new byte[length];
for (int i = 0; i < length; i++)
{
byte val = (byte)(i + 1);
a[i] = val == 200 ? (byte)201 : val;
}
a[length - 1] = 200;
a[length - 2] = 200;
a[length - 3] = 200;
a[length - 4] = 200;
a[length - 5] = 200;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a);
var values = new ReadOnlySpan<byte>(new byte[] { 200, 200, 200, 200, 200, 200, 200, 200, 200 });
int idx = span.IndexOfAny(values);
Assert.Equal(length - 5, idx);
}
}
[Fact]
public static void MakeSureNoChecksGoOutOfRangeMany_Byte()
{
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 98;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 1, length - 1);
var values = new ReadOnlySpan<byte>(new byte[] { 99, 98, 99, 98, 99, 98 });
int index = span.IndexOfAny(values);
Assert.Equal(-1, index);
}
for (int length = 1; length < byte.MaxValue; length++)
{
byte[] a = new byte[length + 2];
a[0] = 99;
a[length + 1] = 99;
ReadOnlySpan<byte> span = new ReadOnlySpan<byte>(a, 1, length - 1);
var values = new ReadOnlySpan<byte>(new byte[] { 99, 99, 99, 99, 99, 99 });
int index = span.IndexOfAny(values);
Assert.Equal(-1, index);
}
}
}
}
| |
//
// RoundedFrame.cs
//
// Authors:
// Aaron Bockover <[email protected]>
// Gabriel Burt <[email protected]>
//
// Copyright (C) 2008 Novell, Inc.
//
// Permission is hereby granted, free of charge, to any person obtaining
// a copy of this software and associated documentation files (the
// "Software"), to deal in the Software without restriction, including
// without limitation the rights to use, copy, modify, merge, publish,
// distribute, sublicense, and/or sell copies of the Software, and to
// permit persons to whom the Software is furnished to do so, subject to
// the following conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
// MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
// LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
// OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
// WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
using System;
using Gtk;
using Cairo;
using Hyena.Gui;
using Hyena.Gui.Theming;
namespace Hyena.Widgets
{
public class RoundedFrame : Bin, IScrollableImplementor
{
private Theme theme;
protected Theme Theme {
get {
if (theme == null) {
InitTheme ();
}
return theme;
}
}
private void InitTheme () {
theme = Hyena.Gui.Theming.ThemeEngine.CreateTheme (this);
frame_width = (int)theme.Context.Radius + 1;
}
private Widget child;
private Gdk.Rectangle child_allocation;
private bool fill_color_set;
private Cairo.Color fill_color;
private bool draw_border = true;
private Pattern fill_pattern;
private int frame_width;
// Ugh, this is to avoid the GLib.MissingIntPtrCtorException seen by some; BGO #552169
protected RoundedFrame (IntPtr ptr) : base (ptr)
{
}
public RoundedFrame ()
{
}
public void SetFillColor (Cairo.Color color)
{
fill_color = color;
fill_color_set = true;
QueueDraw ();
}
public void UnsetFillColor ()
{
fill_color_set = false;
QueueDraw ();
}
public Pattern FillPattern {
get { return fill_pattern; }
set {
if (fill_pattern == value) {
return;
}
if (fill_pattern != null) {
fill_pattern.Dispose ();
}
fill_pattern = value;
QueueDraw ();
}
}
public bool DrawBorder {
get { return draw_border; }
set { draw_border = value; QueueDraw (); }
}
public Gtk.ScrollablePolicy HscrollPolicy {
get; set;
}
public Gtk.ScrollablePolicy VscrollPolicy {
get; set;
}
public Gtk.Adjustment Vadjustment {
get; set;
}
public Gtk.Adjustment Hadjustment {
get; set;
}
#region Gtk.Widget Overrides
protected override void OnStyleUpdated ()
{
base.OnStyleUpdated ();
InitTheme ();
}
protected override void OnGetPreferredHeight (out int minimum_height, out int natural_height)
{
var requisition = SizeRequested ();
minimum_height = natural_height = requisition.Height;
}
protected override void OnGetPreferredWidth (out int minimum_width, out int natural_width)
{
var requisition = SizeRequested ();
minimum_width = natural_width = requisition.Width;
}
protected Requisition SizeRequested ()
{
var requisition = new Requisition ();
if (child != null && child.Visible) {
// Add the child's width/height
Requisition child_requisition, nat_requisition;
child.GetPreferredSize (out child_requisition, out nat_requisition);
requisition.Width = Math.Max (0, child_requisition.Width);
requisition.Height = child_requisition.Height;
} else {
requisition.Width = 0;
requisition.Height = 0;
}
// Add the frame border
requisition.Width += ((int)BorderWidth + frame_width) * 2;
requisition.Height += ((int)BorderWidth + frame_width) * 2;
return requisition;
}
protected override void OnSizeAllocated (Gdk.Rectangle allocation)
{
base.OnSizeAllocated (allocation);
child_allocation = new Gdk.Rectangle ();
if (child == null || !child.Visible) {
return;
}
child_allocation.X = (int)BorderWidth + frame_width;
child_allocation.Y = (int)BorderWidth + frame_width;
child_allocation.Width = (int)Math.Max (1, Allocation.Width - child_allocation.X * 2);
child_allocation.Height = (int)Math.Max (1, Allocation.Height - child_allocation.Y -
(int)BorderWidth - frame_width);
child_allocation.X += Allocation.X;
child_allocation.Y += Allocation.Y;
child.SizeAllocate (child_allocation);
}
protected override bool OnDrawn (Cairo.Context cr)
{
CairoHelper.TransformToWindow (cr, this, Window);
DrawFrame (cr);
if (child != null) {
PropagateDraw (child, cr);
}
return false;
}
private void DrawFrame (Cairo.Context cr)
{
int x = child_allocation.X - frame_width;
int y = child_allocation.Y - frame_width;
int width = child_allocation.Width + 2 * frame_width;
int height = child_allocation.Height + 2 * frame_width;
Gdk.Rectangle rect = new Gdk.Rectangle (x, y, width, height);
Theme.Context.ShowStroke = draw_border;
if (fill_color_set) {
Theme.DrawFrameBackground (cr, rect, fill_color);
} else if (fill_pattern != null) {
Theme.DrawFrameBackground (cr, rect, fill_pattern);
} else {
Theme.DrawFrameBackground (cr, rect, true);
Theme.DrawFrameBorder (cr, rect);
}
}
#endregion
#region Gtk.Container Overrides
protected override void OnAdded (Widget widget)
{
child = widget;
base.OnAdded (widget);
}
protected override void OnRemoved (Widget widget)
{
if (child == widget) {
child = null;
}
base.OnRemoved (widget);
}
#endregion
}
}
| |
/*
* QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals.
* Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Text;
using Newtonsoft.Json;
using NUnit.Framework;
using QuantConnect.Logging;
using QuantConnect.Securities;
namespace QuantConnect.Tests.Common.Securities
{
[TestFixture]
public class SymbolPropertiesDatabaseTests
{
[Test]
public void LoadsLotSize()
{
var db = SymbolPropertiesDatabase.FromDataFolder();
var symbol = Symbol.Create("EURGBP", SecurityType.Forex, Market.FXCM);
var symbolProperties = db.GetSymbolProperties(symbol.ID.Market, symbol, symbol.SecurityType, "GBP");
Assert.AreEqual(symbolProperties.LotSize, 1000);
}
[Test]
public void LoadsQuoteCurrency()
{
var db = SymbolPropertiesDatabase.FromDataFolder();
var symbol = Symbol.Create("EURGBP", SecurityType.Forex, Market.FXCM);
var symbolProperties = db.GetSymbolProperties(symbol.ID.Market, symbol, symbol.SecurityType, "GBP");
Assert.AreEqual(symbolProperties.QuoteCurrency, "GBP");
}
[Test]
public void LoadsDefaultLotSize()
{
var defaultSymbolProperties = SymbolProperties.GetDefault(Currencies.USD);
Assert.AreEqual(defaultSymbolProperties.LotSize, 1);
}
[TestCase(Market.FXCM, SecurityType.Forex)]
[TestCase(Market.Oanda, SecurityType.Forex)]
[TestCase(Market.GDAX, SecurityType.Crypto)]
[TestCase(Market.Bitfinex, SecurityType.Crypto)]
public void BaseCurrencyIsNotEqualToQuoteCurrency(string market, SecurityType securityType)
{
var db = SymbolPropertiesDatabase.FromDataFolder();
var spList = db.GetSymbolPropertiesList(market, securityType).ToList();
Assert.IsNotEmpty(spList);
foreach (var kvp in spList)
{
var quoteCurrency = kvp.Value.QuoteCurrency;
var baseCurrency = kvp.Key.Symbol.Substring(0, kvp.Key.Symbol.Length - quoteCurrency.Length);
Assert.AreNotEqual(baseCurrency, quoteCurrency);
}
}
[Test]
public void CustomEntriesStoredAndFetched()
{
var database = SymbolPropertiesDatabase.FromDataFolder();
var ticker = "BTC";
var properties = SymbolProperties.GetDefault("USD");
// Set the entry
Assert.IsTrue(database.SetEntry(Market.USA, ticker, SecurityType.Base, properties));
// Fetch the entry to ensure we can access it with the ticker
var fetchedProperties = database.GetSymbolProperties(Market.USA, ticker, SecurityType.Base, "USD");
Assert.AreSame(properties, fetchedProperties);
}
[TestCase(Market.FXCM, SecurityType.Cfd)]
[TestCase(Market.Oanda, SecurityType.Cfd)]
[TestCase(Market.CFE, SecurityType.Future)]
[TestCase(Market.CBOT, SecurityType.Future)]
[TestCase(Market.CME, SecurityType.Future)]
[TestCase(Market.COMEX, SecurityType.Future)]
[TestCase(Market.ICE, SecurityType.Future)]
[TestCase(Market.NYMEX, SecurityType.Future)]
[TestCase(Market.SGX, SecurityType.Future)]
[TestCase(Market.HKFE, SecurityType.Future)]
public void GetSymbolPropertiesListIsNotEmpty(string market, SecurityType securityType)
{
var db = SymbolPropertiesDatabase.FromDataFolder();
var spList = db.GetSymbolPropertiesList(market, securityType).ToList();
Assert.IsNotEmpty(spList);
}
[TestCase(Market.USA, SecurityType.Equity)]
[TestCase(Market.USA, SecurityType.Option)]
public void GetSymbolPropertiesListHasOneRow(string market, SecurityType securityType)
{
var db = SymbolPropertiesDatabase.FromDataFolder();
var spList = db.GetSymbolPropertiesList(market, securityType).ToList();
Assert.AreEqual(1, spList.Count);
Assert.IsTrue(spList[0].Key.Symbol.Contains("*"));
}
#region GDAX brokerage
[Test, Explicit]
public void FetchSymbolPropertiesFromGdax()
{
const string urlCurrencies = "https://api.pro.coinbase.com/currencies";
const string urlProducts = "https://api.pro.coinbase.com/products";
var sb = new StringBuilder();
using (var wc = new WebClient())
{
var jsonCurrencies = wc.DownloadString(urlCurrencies);
var rowsCurrencies = JsonConvert.DeserializeObject<List<GdaxCurrency>>(jsonCurrencies);
var currencyDescriptions = rowsCurrencies.ToDictionary(x => x.Id, x => x.Name);
var jsonProducts = wc.DownloadString(urlProducts);
var rowsProducts = JsonConvert.DeserializeObject<List<GdaxProduct>>(jsonProducts);
foreach (var row in rowsProducts.OrderBy(x => x.Id))
{
string baseDescription, quoteDescription;
if (!currencyDescriptions.TryGetValue(row.BaseCurrency, out baseDescription))
{
baseDescription = row.BaseCurrency;
}
if (!currencyDescriptions.TryGetValue(row.QuoteCurrency, out quoteDescription))
{
quoteDescription = row.QuoteCurrency;
}
sb.AppendLine("gdax," +
$"{row.BaseCurrency}{row.QuoteCurrency}," +
"crypto," +
$"{baseDescription}-{quoteDescription}," +
$"{row.QuoteCurrency}," +
"1," +
$"{row.QuoteIncrement.NormalizeToStr()}," +
$"{row.BaseIncrement.NormalizeToStr()}," +
$"{row.Id}");
}
}
Log.Trace(sb.ToString());
}
private class GdaxCurrency
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("name")]
public string Name { get; set; }
[JsonProperty("min_size")]
public decimal MinSize { get; set; }
}
private class GdaxProduct
{
[JsonProperty("id")]
public string Id { get; set; }
[JsonProperty("base_currency")]
public string BaseCurrency { get; set; }
[JsonProperty("quote_currency")]
public string QuoteCurrency { get; set; }
[JsonProperty("base_min_size")]
public decimal BaseMinSize { get; set; }
[JsonProperty("base_max_size")]
public decimal BaseMaxSize { get; set; }
[JsonProperty("quote_increment")]
public decimal QuoteIncrement { get; set; }
[JsonProperty("base_increment")]
public decimal BaseIncrement { get; set; }
[JsonProperty("display_name")]
public string DisplayName { get; set; }
[JsonProperty("min_market_funds")]
public decimal MinMarketFunds { get; set; }
[JsonProperty("max_market_funds")]
public decimal MaxMarketFunds { get; set; }
[JsonProperty("margin_enabled")]
public bool MarginEnabled { get; set; }
[JsonProperty("post_only")]
public bool PostOnly { get; set; }
[JsonProperty("limit_only")]
public bool LimitOnly { get; set; }
[JsonProperty("cancel_only")]
public bool CancelOnly { get; set; }
[JsonProperty("trading_disabled")]
public bool TradingDisabled { get; set; }
[JsonProperty("status")]
public string Status { get; set; }
[JsonProperty("status_message")]
public string StatusMessage { get; set; }
}
#endregion
#region Bitfinex brokerage
[Test, Explicit]
public void FetchSymbolPropertiesFromBitfinex()
{
const string urlExchangePairs = "https://api-pub.bitfinex.com/v2/conf/pub:list:pair:exchange";
const string urlMarginPairs = "https://api-pub.bitfinex.com/v2/conf/pub:list:pair:margin";
const string urlCurrencyMap = "https://api-pub.bitfinex.com/v2/conf/pub:map:currency:sym";
const string urlCurrencyLabels = "https://api-pub.bitfinex.com/v2/conf/pub:map:currency:label";
const string urlSymbolDetails = "https://api.bitfinex.com/v1/symbols_details";
var sb = new StringBuilder();
using (var wc = new WebClient())
{
var jsonExchangePairs = wc.DownloadString(urlExchangePairs);
var exchangePairs = JsonConvert.DeserializeObject<List<List<string>>>(jsonExchangePairs)[0];
var jsonMarginPairs = wc.DownloadString(urlMarginPairs);
var marginPairs = JsonConvert.DeserializeObject<List<List<string>>>(jsonMarginPairs)[0];
var jsonCurrencyMap = wc.DownloadString(urlCurrencyMap);
var rowsCurrencyMap = JsonConvert.DeserializeObject<List<List<List<string>>>>(jsonCurrencyMap)[0];
var currencyMap = rowsCurrencyMap
.ToDictionary(row => row[0], row => row[1].ToUpperInvariant());
var jsonCurrencyLabels = wc.DownloadString(urlCurrencyLabels);
var rowsCurrencyLabels = JsonConvert.DeserializeObject<List<List<List<string>>>>(jsonCurrencyLabels)[0];
var currencyLabels = rowsCurrencyLabels
.ToDictionary(row => row[0], row => row[1]);
var jsonSymbolDetails = wc.DownloadString(urlSymbolDetails);
var symbolDetails = JsonConvert.DeserializeObject<List<BitfinexSymbolDetails>>(jsonSymbolDetails);
var minimumPriceIncrements = symbolDetails
.ToDictionary(x => x.Pair.ToUpperInvariant(), x => (decimal)Math.Pow(10, -x.PricePrecision));
foreach (var pair in exchangePairs.Union(marginPairs).OrderBy(x => x))
{
string baseCurrency, quoteCurrency;
if (pair.Contains(":"))
{
var parts = pair.Split(':');
baseCurrency = parts[0];
quoteCurrency = parts[1];
}
else if (pair.Length == 6)
{
baseCurrency = pair.Substring(0, 3);
quoteCurrency = pair.Substring(3);
}
else
{
// should never happen
Log.Trace($"Skipping pair with unknown format: {pair}");
continue;
}
string baseDescription, quoteDescription;
if (!currencyLabels.TryGetValue(baseCurrency, out baseDescription))
{
Log.Trace($"Base currency description not found: {baseCurrency}");
baseDescription = baseCurrency;
}
if (!currencyLabels.TryGetValue(quoteCurrency, out quoteDescription))
{
Log.Trace($"Quote currency description not found: {quoteCurrency}");
quoteDescription = quoteCurrency;
}
var description = baseDescription + "-" + quoteDescription;
string newBaseCurrency, newQuoteCurrency;
if (currencyMap.TryGetValue(baseCurrency, out newBaseCurrency))
{
baseCurrency = newBaseCurrency;
}
if (currencyMap.TryGetValue(quoteCurrency, out newQuoteCurrency))
{
quoteCurrency = newQuoteCurrency;
}
// skip test symbols
if (quoteCurrency.StartsWith("TEST"))
{
continue;
}
var leanTicker = $"{baseCurrency}{quoteCurrency}";
decimal minimumPriceIncrement;
if (!minimumPriceIncrements.TryGetValue(pair, out minimumPriceIncrement))
{
minimumPriceIncrement = 0.00001m;
}
const decimal lotSize = 0.00000001m;
sb.AppendLine("bitfinex," +
$"{leanTicker}," +
"crypto," +
$"{description}," +
$"{quoteCurrency}," +
"1," +
$"{minimumPriceIncrement.NormalizeToStr()}," +
$"{lotSize.NormalizeToStr()}," +
$"t{pair}");
}
}
Log.Trace(sb.ToString());
}
private class BitfinexSymbolDetails
{
[JsonProperty("pair")]
public string Pair { get; set; }
[JsonProperty("price_precision")]
public int PricePrecision { get; set; }
[JsonProperty("initial_margin")]
public decimal InitialMargin { get; set; }
[JsonProperty("minimum_margin")]
public decimal MinimumMargin { get; set; }
[JsonProperty("maximum_order_size")]
public decimal MaximumOrderSize { get; set; }
[JsonProperty("minimum_order_size")]
public decimal MinimumOrderSize { get; set; }
[JsonProperty("expiration")]
public string Expiration { get; set; }
}
#endregion
[TestCase("ES", Market.CME, 50, 0.25)]
[TestCase("ZB", Market.CBOT, 1000, 0.015625)]
[TestCase("ZW", Market.CBOT, 5000, 0.00125)]
[TestCase("SI", Market.COMEX, 5000, 0.001)]
public void ReadsFuturesOptionsEntries(string ticker, string market, int expectedMultiplier, double expectedMinimumPriceFluctuation)
{
var future = Symbol.CreateFuture(ticker, market, SecurityIdentifier.DefaultDate);
var option = Symbol.CreateOption(
future,
market,
default(OptionStyle),
default(OptionRight),
default(decimal),
SecurityIdentifier.DefaultDate);
var db = SymbolPropertiesDatabase.FromDataFolder();
var results = db.GetSymbolProperties(market, option, SecurityType.FutureOption, "USD");
Assert.AreEqual((decimal)expectedMultiplier, results.ContractMultiplier);
Assert.AreEqual((decimal)expectedMinimumPriceFluctuation, results.MinimumPriceVariation);
}
[TestCase("index")]
[TestCase("indexoption")]
[TestCase("bond")]
[TestCase("swap")]
public void HandlesUnknownSecurityType(string securityType)
{
var line = string.Join(",",
"usa",
"ABCXYZ",
securityType,
"Example Asset",
"USD",
"100",
"0.01",
"1");
SecurityDatabaseKey key;
Assert.DoesNotThrow(() => TestingSymbolPropertiesDatabase.TestFromCsvLine(line, out key));
}
private class TestingSymbolPropertiesDatabase : SymbolPropertiesDatabase
{
public TestingSymbolPropertiesDatabase(string file)
: base(file)
{
}
public static SymbolProperties TestFromCsvLine(string line, out SecurityDatabaseKey key)
{
return FromCsvLine(line, out key);
}
}
}
}
| |
/*
* 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.Collections.Specialized;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
using System.Reflection;
using log4net;
using Mono.Addins;
using Nini.Config;
using OpenSim.Framework;
using OpenSim.Region.Framework.Interfaces;
using OpenSim.Region.Framework.Scenes;
using OpenSim.Services.Interfaces;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
namespace OpenSim.Services.Connectors.SimianGrid
{
/// <summary>
/// Connects region registration and neighbor lookups to the SimianGrid
/// backend
/// </summary>
[Extension(Path = "/OpenSim/RegionModules", NodeName = "RegionModule")]
public class SimianGridServiceConnector : IGridService, ISharedRegionModule
{
private static readonly ILog m_log =
LogManager.GetLogger(
MethodBase.GetCurrentMethod().DeclaringType);
private string m_serverUrl = String.Empty;
private Dictionary<UUID, Scene> m_scenes = new Dictionary<UUID, Scene>();
#region ISharedRegionModule
public Type ReplaceableInterface { get { return null; } }
public void RegionLoaded(Scene scene) { }
public void PostInitialise() { }
public void Close() { }
public SimianGridServiceConnector() { }
public string Name { get { return "SimianGridServiceConnector"; } }
public void AddRegion(Scene scene)
{
// Every shared region module has to maintain an indepedent list of
// currently running regions
lock (m_scenes)
m_scenes[scene.RegionInfo.RegionID] = scene;
if (!String.IsNullOrEmpty(m_serverUrl))
scene.RegisterModuleInterface<IGridService>(this);
}
public void RemoveRegion(Scene scene)
{
lock (m_scenes)
m_scenes.Remove(scene.RegionInfo.RegionID);
if (!String.IsNullOrEmpty(m_serverUrl))
scene.UnregisterModuleInterface<IGridService>(this);
}
#endregion ISharedRegionModule
public SimianGridServiceConnector(IConfigSource source)
{
Initialise(source);
}
public void Initialise(IConfigSource source)
{
if (Simian.IsSimianEnabled(source, "GridServices", this.Name))
{
IConfig gridConfig = source.Configs["GridService"];
if (gridConfig == null)
{
m_log.Error("[SIMIAN GRID CONNECTOR]: GridService missing from OpenSim.ini");
throw new Exception("Grid connector init error");
}
string serviceUrl = gridConfig.GetString("GridServerURI");
if (String.IsNullOrEmpty(serviceUrl))
{
m_log.Error("[SIMIAN GRID CONNECTOR]: No Server URI named in section GridService");
throw new Exception("Grid connector init error");
}
m_serverUrl = serviceUrl;
}
}
#region IGridService
public string RegisterRegion(UUID scopeID, GridRegion regionInfo)
{
// Generate and upload our map tile in PNG format to the SimianGrid AddMapTile service
Scene scene;
if (m_scenes.TryGetValue(regionInfo.RegionID, out scene))
UploadMapTile(scene);
else
m_log.Warn("Registering region " + regionInfo.RegionName + " (" + regionInfo.RegionID + ") that we are not tracking");
Vector3d minPosition = new Vector3d(regionInfo.RegionLocX, regionInfo.RegionLocY, 0.0);
Vector3d maxPosition = minPosition + new Vector3d(Constants.RegionSize, Constants.RegionSize, 4096.0);
string httpAddress = "http://" + regionInfo.ExternalHostName + ":" + regionInfo.HttpPort + "/";
OSDMap extraData = new OSDMap
{
{ "ServerURI", OSD.FromString(regionInfo.ServerURI) },
{ "InternalAddress", OSD.FromString(regionInfo.InternalEndPoint.Address.ToString()) },
{ "InternalPort", OSD.FromInteger(regionInfo.InternalEndPoint.Port) },
{ "ExternalAddress", OSD.FromString(regionInfo.ExternalEndPoint.Address.ToString()) },
{ "ExternalPort", OSD.FromInteger(regionInfo.ExternalEndPoint.Port) },
{ "MapTexture", OSD.FromUUID(regionInfo.TerrainImage) },
{ "Access", OSD.FromInteger(regionInfo.Access) },
{ "RegionSecret", OSD.FromString(regionInfo.RegionSecret) },
{ "EstateOwner", OSD.FromUUID(regionInfo.EstateOwner) },
{ "Token", OSD.FromString(regionInfo.Token) }
};
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddScene" },
{ "SceneID", regionInfo.RegionID.ToString() },
{ "Name", regionInfo.RegionName },
{ "MinPosition", minPosition.ToString() },
{ "MaxPosition", maxPosition.ToString() },
{ "Address", httpAddress },
{ "Enabled", "1" },
{ "ExtraData", OSDParser.SerializeJsonString(extraData) }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
return String.Empty;
else
return "Region registration for " + regionInfo.RegionName + " failed: " + response["Message"].AsString();
}
public bool DeregisterRegion(UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "AddScene" },
{ "SceneID", regionID.ToString() },
{ "Enabled", "0" }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
bool success = response["Success"].AsBoolean();
if (!success)
m_log.Warn("[SIMIAN GRID CONNECTOR]: Region deregistration for " + regionID + " failed: " + response["Message"].AsString());
return success;
}
public List<GridRegion> GetNeighbours(UUID scopeID, UUID regionID)
{
const int NEIGHBOR_RADIUS = 128;
GridRegion region = GetRegionByUUID(scopeID, regionID);
if (region != null)
{
List<GridRegion> regions = GetRegionRange(scopeID,
region.RegionLocX - NEIGHBOR_RADIUS, region.RegionLocX + (int)Constants.RegionSize + NEIGHBOR_RADIUS,
region.RegionLocY - NEIGHBOR_RADIUS, region.RegionLocY + (int)Constants.RegionSize + NEIGHBOR_RADIUS);
for (int i = 0; i < regions.Count; i++)
{
if (regions[i].RegionID == regionID)
{
regions.RemoveAt(i);
break;
}
}
m_log.Debug("[SIMIAN GRID CONNECTOR]: Found " + regions.Count + " neighbors for region " + regionID);
return regions;
}
return new List<GridRegion>(0);
}
public GridRegion GetRegionByUUID(UUID scopeID, UUID regionID)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "SceneID", regionID.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
return ResponseToGridRegion(response);
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region " + regionID);
return null;
}
}
public GridRegion GetRegionByPosition(UUID scopeID, int x, int y)
{
// Go one meter in from the requested x/y coords to avoid requesting a position
// that falls on the border of two sims
Vector3d position = new Vector3d(x + 1, y + 1, 0.0);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "Position", position.ToString() },
{ "Enabled", "1" }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
return ResponseToGridRegion(response);
}
else
{
//m_log.InfoFormat("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region at {0},{1}",
// x / Constants.RegionSize, y / Constants.RegionSize);
return null;
}
}
public GridRegion GetRegionByName(UUID scopeID, string regionName)
{
List<GridRegion> regions = GetRegionsByName(scopeID, regionName, 1);
m_log.Debug("[SIMIAN GRID CONNECTOR]: Got " + regions.Count + " matches for region name " + regionName);
if (regions.Count > 0)
return regions[0];
return null;
}
public List<GridRegion> GetRegionsByName(UUID scopeID, string name, int maxNumber)
{
List<GridRegion> foundRegions = new List<GridRegion>();
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "NameQuery", name },
{ "Enabled", "1" }
};
if (maxNumber > 0)
requestArgs["MaxNumber"] = maxNumber.ToString();
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public List<GridRegion> GetRegionRange(UUID scopeID, int xmin, int xmax, int ymin, int ymax)
{
List<GridRegion> foundRegions = new List<GridRegion>();
Vector3d minPosition = new Vector3d(xmin, ymin, 0.0);
Vector3d maxPosition = new Vector3d(xmax, ymax, 4096.0);
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScenes" },
{ "MinPosition", minPosition.ToString() },
{ "MaxPosition", maxPosition.ToString() },
{ "Enabled", "1" }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
OSDArray array = response["Scenes"] as OSDArray;
if (array != null)
{
for (int i = 0; i < array.Count; i++)
{
GridRegion region = ResponseToGridRegion(array[i] as OSDMap);
if (region != null)
foundRegions.Add(region);
}
}
}
return foundRegions;
}
public List<GridRegion> GetDefaultRegions(UUID scopeID)
{
// TODO: Allow specifying the default grid location
const int DEFAULT_X = 1000 * 256;
const int DEFAULT_Y = 1000 * 256;
GridRegion defRegion = GetNearestRegion(new Vector3d(DEFAULT_X, DEFAULT_Y, 0.0), true);
if (defRegion != null)
return new List<GridRegion>(1) { defRegion };
else
return new List<GridRegion>(0);
}
public List<GridRegion> GetFallbackRegions(UUID scopeID, int x, int y)
{
GridRegion defRegion = GetNearestRegion(new Vector3d(x, y, 0.0), true);
if (defRegion != null)
return new List<GridRegion>(1) { defRegion };
else
return new List<GridRegion>(0);
}
public List<GridRegion> GetHyperlinks(UUID scopeID)
{
// Hypergrid/linked regions are not supported
return new List<GridRegion>();
}
public int GetRegionFlags(UUID scopeID, UUID regionID)
{
const int REGION_ONLINE = 4;
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "SceneID", regionID.ToString() }
};
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
return response["Enabled"].AsBoolean() ? REGION_ONLINE : 0;
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region " + regionID + " during region flags check");
return -1;
}
}
#endregion IGridService
private void UploadMapTile(IScene scene)
{
string errorMessage = null;
// Create a PNG map tile and upload it to the AddMapTile API
byte[] pngData = Utils.EmptyBytes;
IMapImageGenerator tileGenerator = scene.RequestModuleInterface<IMapImageGenerator>();
if (tileGenerator == null)
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Cannot upload PNG map tile without an IMapImageGenerator");
return;
}
using (Image mapTile = tileGenerator.CreateMapTile("defaultstripe.png"))
{
using (MemoryStream stream = new MemoryStream())
{
mapTile.Save(stream, ImageFormat.Png);
pngData = stream.ToArray();
}
}
List<MultipartForm.Element> postParameters = new List<MultipartForm.Element>()
{
new MultipartForm.Parameter("X", scene.RegionInfo.RegionLocX.ToString()),
new MultipartForm.Parameter("Y", scene.RegionInfo.RegionLocY.ToString()),
new MultipartForm.File("Tile", "tile.png", "image/png", pngData)
};
// Make the remote storage request
try
{
HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create(m_serverUrl);
HttpWebResponse response = MultipartForm.Post(request, postParameters);
using (Stream responseStream = response.GetResponseStream())
{
string responseStr = null;
try
{
responseStr = responseStream.GetStreamString();
OSD responseOSD = OSDParser.Deserialize(responseStr);
if (responseOSD.Type == OSDType.Map)
{
OSDMap responseMap = (OSDMap)responseOSD;
if (responseMap["Success"].AsBoolean())
m_log.Info("[SIMIAN GRID CONNECTOR]: Uploaded " + pngData.Length + " byte PNG map tile to AddMapTile");
else
errorMessage = "Upload failed: " + responseMap["Message"].AsString();
}
else
{
errorMessage = "Response format was invalid:\n" + responseStr;
}
}
catch (Exception ex)
{
if (!String.IsNullOrEmpty(responseStr))
errorMessage = "Failed to parse the response:\n" + responseStr;
else
errorMessage = "Failed to retrieve the response: " + ex.Message;
}
}
}
catch (WebException ex)
{
errorMessage = ex.Message;
}
if (!String.IsNullOrEmpty(errorMessage))
{
m_log.WarnFormat("[SIMIAN GRID CONNECTOR]: Failed to store {0} byte PNG map tile for {1}: {2}",
pngData.Length, scene.RegionInfo.RegionName, errorMessage.Replace('\n', ' '));
}
}
private GridRegion GetNearestRegion(Vector3d position, bool onlyEnabled)
{
NameValueCollection requestArgs = new NameValueCollection
{
{ "RequestMethod", "GetScene" },
{ "Position", position.ToString() },
{ "FindClosest", "1" }
};
if (onlyEnabled)
requestArgs["Enabled"] = "1";
OSDMap response = WebUtil.PostToService(m_serverUrl, requestArgs);
if (response["Success"].AsBoolean())
{
return ResponseToGridRegion(response);
}
else
{
m_log.Warn("[SIMIAN GRID CONNECTOR]: Grid service did not find a match for region at " + position);
return null;
}
}
private GridRegion ResponseToGridRegion(OSDMap response)
{
if (response == null)
return null;
OSDMap extraData = response["ExtraData"] as OSDMap;
if (extraData == null)
return null;
GridRegion region = new GridRegion();
region.RegionID = response["SceneID"].AsUUID();
region.RegionName = response["Name"].AsString();
Vector3d minPosition = response["MinPosition"].AsVector3d();
region.RegionLocX = (int)minPosition.X;
region.RegionLocY = (int)minPosition.Y;
Uri httpAddress = response["Address"].AsUri();
region.ExternalHostName = httpAddress.Host;
region.HttpPort = (uint)httpAddress.Port;
region.ServerURI = extraData["ServerURI"].AsString();
IPAddress internalAddress;
IPAddress.TryParse(extraData["InternalAddress"].AsString(), out internalAddress);
if (internalAddress == null)
internalAddress = IPAddress.Any;
region.InternalEndPoint = new IPEndPoint(internalAddress, extraData["InternalPort"].AsInteger());
region.TerrainImage = extraData["MapTexture"].AsUUID();
region.Access = (byte)extraData["Access"].AsInteger();
region.RegionSecret = extraData["RegionSecret"].AsString();
region.EstateOwner = extraData["EstateOwner"].AsUUID();
region.Token = extraData["Token"].AsString();
return region;
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Reflection;
using System.Runtime.Serialization;
using System.Web.Http;
using System.Web.Http.Description;
using System.Xml.Serialization;
using Newtonsoft.Json;
namespace VowTracker.Areas.HelpPage.ModelDescriptions
{
/// <summary>
/// Generates model descriptions for given types.
/// </summary>
public class ModelDescriptionGenerator
{
// Modify this to support more data annotation attributes.
private readonly IDictionary<Type, Func<object, string>> AnnotationTextGenerator = new Dictionary<Type, Func<object, string>>
{
{ typeof(RequiredAttribute), a => "Required" },
{ typeof(RangeAttribute), a =>
{
RangeAttribute range = (RangeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Range: inclusive between {0} and {1}", range.Minimum, range.Maximum);
}
},
{ typeof(MaxLengthAttribute), a =>
{
MaxLengthAttribute maxLength = (MaxLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Max length: {0}", maxLength.Length);
}
},
{ typeof(MinLengthAttribute), a =>
{
MinLengthAttribute minLength = (MinLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Min length: {0}", minLength.Length);
}
},
{ typeof(StringLengthAttribute), a =>
{
StringLengthAttribute strLength = (StringLengthAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "String length: inclusive between {0} and {1}", strLength.MinimumLength, strLength.MaximumLength);
}
},
{ typeof(DataTypeAttribute), a =>
{
DataTypeAttribute dataType = (DataTypeAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Data type: {0}", dataType.CustomDataType ?? dataType.DataType.ToString());
}
},
{ typeof(RegularExpressionAttribute), a =>
{
RegularExpressionAttribute regularExpression = (RegularExpressionAttribute)a;
return String.Format(CultureInfo.CurrentCulture, "Matching regular expression pattern: {0}", regularExpression.Pattern);
}
},
};
// Modify this to add more default documentations.
private readonly IDictionary<Type, string> DefaultTypeDocumentation = new Dictionary<Type, string>
{
{ typeof(Int16), "integer" },
{ typeof(Int32), "integer" },
{ typeof(Int64), "integer" },
{ typeof(UInt16), "unsigned integer" },
{ typeof(UInt32), "unsigned integer" },
{ typeof(UInt64), "unsigned integer" },
{ typeof(Byte), "byte" },
{ typeof(Char), "character" },
{ typeof(SByte), "signed byte" },
{ typeof(Uri), "URI" },
{ typeof(Single), "decimal number" },
{ typeof(Double), "decimal number" },
{ typeof(Decimal), "decimal number" },
{ typeof(String), "string" },
{ typeof(Guid), "globally unique identifier" },
{ typeof(TimeSpan), "time interval" },
{ typeof(DateTime), "date" },
{ typeof(DateTimeOffset), "date" },
{ typeof(Boolean), "boolean" },
};
private Lazy<IModelDocumentationProvider> _documentationProvider;
public ModelDescriptionGenerator(HttpConfiguration config)
{
if (config == null)
{
throw new ArgumentNullException("config");
}
_documentationProvider = new Lazy<IModelDocumentationProvider>(() => config.Services.GetDocumentationProvider() as IModelDocumentationProvider);
GeneratedModels = new Dictionary<string, ModelDescription>(StringComparer.OrdinalIgnoreCase);
}
public Dictionary<string, ModelDescription> GeneratedModels { get; private set; }
private IModelDocumentationProvider DocumentationProvider
{
get
{
return _documentationProvider.Value;
}
}
public ModelDescription GetOrCreateModelDescription(Type modelType)
{
if (modelType == null)
{
throw new ArgumentNullException("modelType");
}
Type underlyingType = Nullable.GetUnderlyingType(modelType);
if (underlyingType != null)
{
modelType = underlyingType;
}
ModelDescription modelDescription;
string modelName = ModelNameHelper.GetModelName(modelType);
if (GeneratedModels.TryGetValue(modelName, out modelDescription))
{
if (modelType != modelDescription.ModelType)
{
throw new InvalidOperationException(
String.Format(
CultureInfo.CurrentCulture,
"A model description could not be created. Duplicate model name '{0}' was found for types '{1}' and '{2}'. " +
"Use the [ModelName] attribute to change the model name for at least one of the types so that it has a unique name.",
modelName,
modelDescription.ModelType.FullName,
modelType.FullName));
}
return modelDescription;
}
if (DefaultTypeDocumentation.ContainsKey(modelType))
{
return GenerateSimpleTypeModelDescription(modelType);
}
if (modelType.IsEnum)
{
return GenerateEnumTypeModelDescription(modelType);
}
if (modelType.IsGenericType)
{
Type[] genericArguments = modelType.GetGenericArguments();
if (genericArguments.Length == 1)
{
Type enumerableType = typeof(IEnumerable<>).MakeGenericType(genericArguments);
if (enumerableType.IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, genericArguments[0]);
}
}
if (genericArguments.Length == 2)
{
Type dictionaryType = typeof(IDictionary<,>).MakeGenericType(genericArguments);
if (dictionaryType.IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
Type keyValuePairType = typeof(KeyValuePair<,>).MakeGenericType(genericArguments);
if (keyValuePairType.IsAssignableFrom(modelType))
{
return GenerateKeyValuePairModelDescription(modelType, genericArguments[0], genericArguments[1]);
}
}
}
if (modelType.IsArray)
{
Type elementType = modelType.GetElementType();
return GenerateCollectionModelDescription(modelType, elementType);
}
if (modelType == typeof(NameValueCollection))
{
return GenerateDictionaryModelDescription(modelType, typeof(string), typeof(string));
}
if (typeof(IDictionary).IsAssignableFrom(modelType))
{
return GenerateDictionaryModelDescription(modelType, typeof(object), typeof(object));
}
if (typeof(IEnumerable).IsAssignableFrom(modelType))
{
return GenerateCollectionModelDescription(modelType, typeof(object));
}
return GenerateComplexTypeModelDescription(modelType);
}
// Change this to provide different name for the member.
private static string GetMemberName(MemberInfo member, bool hasDataContractAttribute)
{
JsonPropertyAttribute jsonProperty = member.GetCustomAttribute<JsonPropertyAttribute>();
if (jsonProperty != null && !String.IsNullOrEmpty(jsonProperty.PropertyName))
{
return jsonProperty.PropertyName;
}
if (hasDataContractAttribute)
{
DataMemberAttribute dataMember = member.GetCustomAttribute<DataMemberAttribute>();
if (dataMember != null && !String.IsNullOrEmpty(dataMember.Name))
{
return dataMember.Name;
}
}
return member.Name;
}
private static bool ShouldDisplayMember(MemberInfo member, bool hasDataContractAttribute)
{
JsonIgnoreAttribute jsonIgnore = member.GetCustomAttribute<JsonIgnoreAttribute>();
XmlIgnoreAttribute xmlIgnore = member.GetCustomAttribute<XmlIgnoreAttribute>();
IgnoreDataMemberAttribute ignoreDataMember = member.GetCustomAttribute<IgnoreDataMemberAttribute>();
NonSerializedAttribute nonSerialized = member.GetCustomAttribute<NonSerializedAttribute>();
ApiExplorerSettingsAttribute apiExplorerSetting = member.GetCustomAttribute<ApiExplorerSettingsAttribute>();
bool hasMemberAttribute = member.DeclaringType.IsEnum ?
member.GetCustomAttribute<EnumMemberAttribute>() != null :
member.GetCustomAttribute<DataMemberAttribute>() != null;
// Display member only if all the followings are true:
// no JsonIgnoreAttribute
// no XmlIgnoreAttribute
// no IgnoreDataMemberAttribute
// no NonSerializedAttribute
// no ApiExplorerSettingsAttribute with IgnoreApi set to true
// no DataContractAttribute without DataMemberAttribute or EnumMemberAttribute
return jsonIgnore == null &&
xmlIgnore == null &&
ignoreDataMember == null &&
nonSerialized == null &&
(apiExplorerSetting == null || !apiExplorerSetting.IgnoreApi) &&
(!hasDataContractAttribute || hasMemberAttribute);
}
private string CreateDefaultDocumentation(Type type)
{
string documentation;
if (DefaultTypeDocumentation.TryGetValue(type, out documentation))
{
return documentation;
}
if (DocumentationProvider != null)
{
documentation = DocumentationProvider.GetDocumentation(type);
}
return documentation;
}
private void GenerateAnnotations(MemberInfo property, ParameterDescription propertyModel)
{
List<ParameterAnnotation> annotations = new List<ParameterAnnotation>();
IEnumerable<Attribute> attributes = property.GetCustomAttributes();
foreach (Attribute attribute in attributes)
{
Func<object, string> textGenerator;
if (AnnotationTextGenerator.TryGetValue(attribute.GetType(), out textGenerator))
{
annotations.Add(
new ParameterAnnotation
{
AnnotationAttribute = attribute,
Documentation = textGenerator(attribute)
});
}
}
// Rearrange the annotations
annotations.Sort((x, y) =>
{
// Special-case RequiredAttribute so that it shows up on top
if (x.AnnotationAttribute is RequiredAttribute)
{
return -1;
}
if (y.AnnotationAttribute is RequiredAttribute)
{
return 1;
}
// Sort the rest based on alphabetic order of the documentation
return String.Compare(x.Documentation, y.Documentation, StringComparison.OrdinalIgnoreCase);
});
foreach (ParameterAnnotation annotation in annotations)
{
propertyModel.Annotations.Add(annotation);
}
}
private CollectionModelDescription GenerateCollectionModelDescription(Type modelType, Type elementType)
{
ModelDescription collectionModelDescription = GetOrCreateModelDescription(elementType);
if (collectionModelDescription != null)
{
return new CollectionModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
ElementDescription = collectionModelDescription
};
}
return null;
}
private ModelDescription GenerateComplexTypeModelDescription(Type modelType)
{
ComplexTypeModelDescription complexModelDescription = new ComplexTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(complexModelDescription.Name, complexModelDescription);
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
PropertyInfo[] properties = modelType.GetProperties(BindingFlags.Public | BindingFlags.Instance);
foreach (PropertyInfo property in properties)
{
if (ShouldDisplayMember(property, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(property, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(property);
}
GenerateAnnotations(property, propertyModel);
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(property.PropertyType);
}
}
FieldInfo[] fields = modelType.GetFields(BindingFlags.Public | BindingFlags.Instance);
foreach (FieldInfo field in fields)
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
ParameterDescription propertyModel = new ParameterDescription
{
Name = GetMemberName(field, hasDataContractAttribute)
};
if (DocumentationProvider != null)
{
propertyModel.Documentation = DocumentationProvider.GetDocumentation(field);
}
complexModelDescription.Properties.Add(propertyModel);
propertyModel.TypeDescription = GetOrCreateModelDescription(field.FieldType);
}
}
return complexModelDescription;
}
private DictionaryModelDescription GenerateDictionaryModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new DictionaryModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private EnumTypeModelDescription GenerateEnumTypeModelDescription(Type modelType)
{
EnumTypeModelDescription enumDescription = new EnumTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
bool hasDataContractAttribute = modelType.GetCustomAttribute<DataContractAttribute>() != null;
foreach (FieldInfo field in modelType.GetFields(BindingFlags.Public | BindingFlags.Static))
{
if (ShouldDisplayMember(field, hasDataContractAttribute))
{
EnumValueDescription enumValue = new EnumValueDescription
{
Name = field.Name,
Value = field.GetRawConstantValue().ToString()
};
if (DocumentationProvider != null)
{
enumValue.Documentation = DocumentationProvider.GetDocumentation(field);
}
enumDescription.Values.Add(enumValue);
}
}
GeneratedModels.Add(enumDescription.Name, enumDescription);
return enumDescription;
}
private KeyValuePairModelDescription GenerateKeyValuePairModelDescription(Type modelType, Type keyType, Type valueType)
{
ModelDescription keyModelDescription = GetOrCreateModelDescription(keyType);
ModelDescription valueModelDescription = GetOrCreateModelDescription(valueType);
return new KeyValuePairModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
KeyModelDescription = keyModelDescription,
ValueModelDescription = valueModelDescription
};
}
private ModelDescription GenerateSimpleTypeModelDescription(Type modelType)
{
SimpleTypeModelDescription simpleModelDescription = new SimpleTypeModelDescription
{
Name = ModelNameHelper.GetModelName(modelType),
ModelType = modelType,
Documentation = CreateDefaultDocumentation(modelType)
};
GeneratedModels.Add(simpleModelDescription.Name, simpleModelDescription);
return simpleModelDescription;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Model = Discord.API.Channel;
namespace Discord.Rest
{
/// <summary>
/// Represents a REST-based direct-message channel.
/// </summary>
[DebuggerDisplay(@"{DebuggerDisplay,nq}")]
public class RestDMChannel : RestChannel, IDMChannel, IRestPrivateChannel, IRestMessageChannel
{
/// <summary>
/// Gets the current logged-in user.
/// </summary>
public RestUser CurrentUser { get; }
/// <summary>
/// Gets the recipient of the channel.
/// </summary>
public RestUser Recipient { get; }
/// <summary>
/// Gets a collection that is the current logged-in user and the recipient.
/// </summary>
public IReadOnlyCollection<RestUser> Users => ImmutableArray.Create(CurrentUser, Recipient);
internal RestDMChannel(BaseDiscordClient discord, ulong id, ulong recipientId)
: base(discord, id)
{
Recipient = new RestUser(Discord, recipientId);
CurrentUser = new RestUser(Discord, discord.CurrentUser.Id);
}
internal new static RestDMChannel Create(BaseDiscordClient discord, Model model)
{
var entity = new RestDMChannel(discord, model.Id, model.Recipients.Value[0].Id);
entity.Update(model);
return entity;
}
internal override void Update(Model model)
{
Recipient.Update(model.Recipients.Value[0]);
}
/// <inheritdoc />
public override async Task UpdateAsync(RequestOptions options = null)
{
var model = await Discord.ApiClient.GetChannelAsync(Id, options).ConfigureAwait(false);
Update(model);
}
/// <inheritdoc />
public Task CloseAsync(RequestOptions options = null)
=> ChannelHelper.DeleteAsync(this, Discord, options);
/// <summary>
/// Gets a user in this channel from the provided <paramref name="id"/>.
/// </summary>
/// <param name="id">The snowflake identifier of the user.</param>
/// <returns>
/// A <see cref="RestUser"/> object that is a recipient of this channel; otherwise <c>null</c>.
/// </returns>
public RestUser GetUser(ulong id)
{
if (id == Recipient.Id)
return Recipient;
else if (id == Discord.CurrentUser.Id)
return CurrentUser;
else
return null;
}
/// <inheritdoc />
public Task<RestMessage> GetMessageAsync(ulong id, RequestOptions options = null)
=> ChannelHelper.GetMessageAsync(this, Discord, id, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, null, Direction.Before, limit, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(ulong fromMessageId, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, fromMessageId, dir, limit, options);
/// <inheritdoc />
public IAsyncEnumerable<IReadOnlyCollection<RestMessage>> GetMessagesAsync(IMessage fromMessage, Direction dir, int limit = DiscordConfig.MaxMessagesPerBatch, RequestOptions options = null)
=> ChannelHelper.GetMessagesAsync(this, Discord, fromMessage.Id, dir, limit, options);
/// <inheritdoc />
public Task<IReadOnlyCollection<RestMessage>> GetPinnedMessagesAsync(RequestOptions options = null)
=> ChannelHelper.GetPinnedMessagesAsync(this, Discord, options);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendMessageAsync(string text = null, bool isTTS = false, Embed embed = null, RequestOptions options = null, AllowedMentions allowedMentions = null, MessageReference messageReference = null)
=> ChannelHelper.SendMessageAsync(this, Discord, text, isTTS, embed, allowedMentions, messageReference, options);
/// <inheritdoc />
/// <exception cref="ArgumentException">
/// <paramref name="filePath" /> is a zero-length string, contains only white space, or contains one or more
/// invalid characters as defined by <see cref="System.IO.Path.GetInvalidPathChars"/>.
/// </exception>
/// <exception cref="ArgumentNullException">
/// <paramref name="filePath" /> is <c>null</c>.
/// </exception>
/// <exception cref="PathTooLongException">
/// The specified path, file name, or both exceed the system-defined maximum length. For example, on
/// Windows-based platforms, paths must be less than 248 characters, and file names must be less than 260
/// characters.
/// </exception>
/// <exception cref="DirectoryNotFoundException">
/// The specified path is invalid, (for example, it is on an unmapped drive).
/// </exception>
/// <exception cref="UnauthorizedAccessException">
/// <paramref name="filePath" /> specified a directory.-or- The caller does not have the required permission.
/// </exception>
/// <exception cref="FileNotFoundException">
/// The file specified in <paramref name="filePath" /> was not found.
/// </exception>
/// <exception cref="NotSupportedException"><paramref name="filePath" /> is in an invalid format.</exception>
/// <exception cref="IOException">An I/O error occurred while opening the file.</exception>
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(string filePath, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null)
=> ChannelHelper.SendFileAsync(this, Discord, filePath, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler);
/// <inheritdoc />
/// <exception cref="ArgumentOutOfRangeException">Message content is too long, length must be less or equal to <see cref="DiscordConfig.MaxMessageSize"/>.</exception>
public Task<RestUserMessage> SendFileAsync(Stream stream, string filename, string text, bool isTTS = false, Embed embed = null, RequestOptions options = null, bool isSpoiler = false, AllowedMentions allowedMentions = null, MessageReference messageReference = null)
=> ChannelHelper.SendFileAsync(this, Discord, stream, filename, text, isTTS, embed, allowedMentions, messageReference, options, isSpoiler);
/// <inheritdoc />
public Task DeleteMessageAsync(ulong messageId, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, messageId, Discord, options);
/// <inheritdoc />
public Task DeleteMessageAsync(IMessage message, RequestOptions options = null)
=> ChannelHelper.DeleteMessageAsync(this, message.Id, Discord, options);
/// <inheritdoc />
public Task TriggerTypingAsync(RequestOptions options = null)
=> ChannelHelper.TriggerTypingAsync(this, Discord, options);
/// <inheritdoc />
public IDisposable EnterTypingState(RequestOptions options = null)
=> ChannelHelper.EnterTypingState(this, Discord, options);
/// <summary>
/// Gets a string that represents the Username#Discriminator of the recipient.
/// </summary>
/// <returns>
/// A string that resolves to the Recipient of this channel.
/// </returns>
public override string ToString() => $"@{Recipient}";
private string DebuggerDisplay => $"@{Recipient} ({Id}, DM)";
//IDMChannel
/// <inheritdoc />
IUser IDMChannel.Recipient => Recipient;
//IRestPrivateChannel
/// <inheritdoc />
IReadOnlyCollection<RestUser> IRestPrivateChannel.Recipients => ImmutableArray.Create(Recipient);
//IPrivateChannel
/// <inheritdoc />
IReadOnlyCollection<IUser> IPrivateChannel.Recipients => ImmutableArray.Create<IUser>(Recipient);
//IMessageChannel
/// <inheritdoc />
async Task<IMessage> IMessageChannel.GetMessageAsync(ulong id, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return await GetMessageAsync(id, options).ConfigureAwait(false);
else
return null;
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return GetMessagesAsync(limit, options);
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(ulong fromMessageId, Direction dir, int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return GetMessagesAsync(fromMessageId, dir, limit, options);
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IMessage>> IMessageChannel.GetMessagesAsync(IMessage fromMessage, Direction dir, int limit, CacheMode mode, RequestOptions options)
{
if (mode == CacheMode.AllowDownload)
return GetMessagesAsync(fromMessage, dir, limit, options);
else
return AsyncEnumerable.Empty<IReadOnlyCollection<IMessage>>();
}
/// <inheritdoc />
async Task<IReadOnlyCollection<IMessage>> IMessageChannel.GetPinnedMessagesAsync(RequestOptions options)
=> await GetPinnedMessagesAsync(options).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(string filePath, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference)
=> await SendFileAsync(filePath, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendFileAsync(Stream stream, string filename, string text, bool isTTS, Embed embed, RequestOptions options, bool isSpoiler, AllowedMentions allowedMentions, MessageReference messageReference)
=> await SendFileAsync(stream, filename, text, isTTS, embed, options, isSpoiler, allowedMentions, messageReference).ConfigureAwait(false);
/// <inheritdoc />
async Task<IUserMessage> IMessageChannel.SendMessageAsync(string text, bool isTTS, Embed embed, RequestOptions options, AllowedMentions allowedMentions, MessageReference messageReference)
=> await SendMessageAsync(text, isTTS, embed, options, allowedMentions, messageReference).ConfigureAwait(false);
//IChannel
/// <inheritdoc />
string IChannel.Name => $"@{Recipient}";
/// <inheritdoc />
Task<IUser> IChannel.GetUserAsync(ulong id, CacheMode mode, RequestOptions options)
=> Task.FromResult<IUser>(GetUser(id));
/// <inheritdoc />
IAsyncEnumerable<IReadOnlyCollection<IUser>> IChannel.GetUsersAsync(CacheMode mode, RequestOptions options)
=> ImmutableArray.Create<IReadOnlyCollection<IUser>>(Users).ToAsyncEnumerable();
}
}
| |
// Copyright 2018 Esri.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at: http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific
// language governing permissions and limitations under the License.
using ArcGISRuntime.Samples.Managers;
using Esri.ArcGISRuntime.Geometry;
using Esri.ArcGISRuntime.Mapping;
using Esri.ArcGISRuntime.Symbology;
using Esri.ArcGISRuntime.UI;
using Esri.ArcGISRuntime.UI.GeoAnalysis;
using System;
using System.Drawing;
using Windows.UI.Popups;
using Windows.UI.Xaml;
namespace ArcGISRuntime.UWP.Samples.LineOfSightGeoElement
{
[ArcGISRuntime.Samples.Shared.Attributes.Sample(
name: "Line of sight (geoelement)",
category: "Analysis",
description: "Show a line of sight between two moving objects.",
instructions: "A line of sight will display between a point on the Empire State Building (observer) and a taxi (target).",
tags: new[] { "3D", "line of sight", "visibility", "visibility analysis" })]
[ArcGISRuntime.Samples.Shared.Attributes.OfflineData("3af5cfec0fd24dac8d88aea679027cb9")]
public partial class LineOfSightGeoElement
{
// URL of the elevation service - provides elevation component of the scene.
private readonly Uri _elevationUri = new Uri("https://elevation3d.arcgis.com/arcgis/rest/services/WorldElevation3D/Terrain3D/ImageServer");
// URL of the building service - provides building models.
private readonly Uri _buildingsUri = new Uri("https://tiles.arcgis.com/tiles/z2tnIkrLQ2BRzr6P/arcgis/rest/services/New_York_LoD2_3D_Buildings/SceneServer/layers/0");
// Starting point of the observation point.
private readonly MapPoint _observerPoint = new MapPoint(-73.984988, 40.748131, 20, SpatialReferences.Wgs84);
// Graphic to represent the observation point.
private Graphic _observerGraphic;
// Graphic to represent the observed target.
private Graphic _taxiGraphic;
// Line of Sight Analysis.
private GeoElementLineOfSight _geoLine;
// For taxi animation - four points in a loop.
private readonly MapPoint[] _points = {
new MapPoint(-73.984513, 40.748469, SpatialReferences.Wgs84),
new MapPoint(-73.985068, 40.747786, SpatialReferences.Wgs84),
new MapPoint(-73.983452, 40.747091, SpatialReferences.Wgs84),
new MapPoint(-73.982961, 40.747762, SpatialReferences.Wgs84)
};
// For taxi animation - tracks animation state.
private int _pointIndex = 0;
private int _frameIndex = 0;
private const int FrameMax = 150;
public LineOfSightGeoElement()
{
InitializeComponent();
// Setup the control references and execute initialization.
Initialize();
}
private async void Initialize()
{
// Create scene.
Scene myScene = new Scene(Basemap.CreateImageryWithLabels())
{
InitialViewpoint = new Viewpoint(_observerPoint, 1600)
};
// Create the elevation source.
ElevationSource myElevationSource = new ArcGISTiledElevationSource(_elevationUri);
// Add the elevation source to the scene.
myScene.BaseSurface.ElevationSources.Add(myElevationSource);
// Create the building scene layer.
ArcGISSceneLayer mySceneLayer = new ArcGISSceneLayer(_buildingsUri);
// Add the building layer to the scene.
myScene.OperationalLayers.Add(mySceneLayer);
// Add the observer to the scene.
// Create a graphics overlay with relative surface placement; relative surface placement allows the Z position of the observation point to be adjusted.
GraphicsOverlay overlay = new GraphicsOverlay() { SceneProperties = new LayerSceneProperties(SurfacePlacement.Relative) };
// Create the symbol that will symbolize the observation point.
SimpleMarkerSceneSymbol symbol = new SimpleMarkerSceneSymbol(SimpleMarkerSceneSymbolStyle.Sphere, Color.Red, 10, 10, 10, SceneSymbolAnchorPosition.Bottom);
// Create the observation point graphic from the point and symbol.
_observerGraphic = new Graphic(_observerPoint, symbol);
// Add the observer to the overlay.
overlay.Graphics.Add(_observerGraphic);
// Add the overlay to the scene.
MySceneView.GraphicsOverlays.Add(overlay);
try
{
// Add the taxi to the scene.
// Create the model symbol for the taxi.
ModelSceneSymbol taxiSymbol = await ModelSceneSymbol.CreateAsync(new Uri(DataManager.GetDataFolder("3af5cfec0fd24dac8d88aea679027cb9", "dolmus.3ds")));
// Set the anchor position for the mode; ensures that the model appears above the ground.
taxiSymbol.AnchorPosition = SceneSymbolAnchorPosition.Bottom;
// Create the graphic from the taxi starting point and the symbol.
_taxiGraphic = new Graphic(_points[0], taxiSymbol);
// Add the taxi graphic to the overlay.
overlay.Graphics.Add(_taxiGraphic);
// Create GeoElement Line of sight analysis (taxi to building).
// Create the analysis.
_geoLine = new GeoElementLineOfSight(_observerGraphic, _taxiGraphic)
{
// Apply an offset to the target. This helps avoid some false negatives.
TargetOffsetZ = 2
};
// Create the analysis overlay.
AnalysisOverlay myAnalysisOverlay = new AnalysisOverlay();
// Add the analysis to the overlay.
myAnalysisOverlay.Analyses.Add(_geoLine);
// Add the analysis overlay to the scene.
MySceneView.AnalysisOverlays.Add(myAnalysisOverlay);
// Create a timer; this will enable animating the taxi.
DispatcherTimer animationTimer = new DispatcherTimer()
{
Interval = new TimeSpan(0, 0, 0, 0, 60)
};
// Move the taxi every time the timer expires.
animationTimer.Tick += AnimationTimer_Tick;
// Start the timer.
animationTimer.Start();
// Subscribe to TargetVisible events; allows for updating the UI and selecting the taxi when it is visible.
_geoLine.TargetVisibilityChanged += Geoline_TargetVisibilityChanged;
// Add the scene to the view.
MySceneView.Scene = myScene;
}
catch (Exception e)
{
await new MessageDialog(e.ToString(), "Error").ShowAsync();
}
}
private void AnimationTimer_Tick(object sender, object e)
{
// Note: the contents of this function are solely related to animating the taxi.
// Increment the frame counter.
_frameIndex++;
// Reset the frame counter once one segment of the path has been traveled.
if (_frameIndex == FrameMax)
{
_frameIndex = 0;
// Start navigating toward the next point.
_pointIndex++;
// Restart if finished circuit.
if (_pointIndex == _points.Length)
{
_pointIndex = 0;
}
}
// Get the point the taxi is traveling from.
MapPoint starting = _points[_pointIndex];
// Get the point the taxi is traveling to.
MapPoint ending = _points[(_pointIndex + 1) % _points.Length];
// Calculate the progress based on the current frame.
double progress = _frameIndex / (double)FrameMax;
// Calculate the position of the taxi when it is {progress}% of the way through.
MapPoint intermediatePoint = InterpolatedPoint(starting, ending, progress);
// Update the taxi geometry.
_taxiGraphic.Geometry = intermediatePoint;
// Update the taxi rotation.
GeodeticDistanceResult distance = GeometryEngine.DistanceGeodetic(starting, ending, LinearUnits.Meters, AngularUnits.Degrees, GeodeticCurveType.Geodesic);
((ModelSceneSymbol)_taxiGraphic.Symbol).Heading = distance.Azimuth1;
}
private static MapPoint InterpolatedPoint(MapPoint firstPoint, MapPoint secondPoint, double progress)
{
// This function returns a MapPoint that is the result of traveling {progress}% of the way from {firstPoint} to {secondPoint}.
// Get the difference between the two points.
MapPoint difference = new MapPoint(secondPoint.X - firstPoint.X, secondPoint.Y - firstPoint.Y, secondPoint.Z - firstPoint.Z, SpatialReferences.Wgs84);
// Scale the difference by the progress towards the destination.
MapPoint scaled = new MapPoint(difference.X * progress, difference.Y * progress, difference.Z * progress);
// Add the scaled progress to the starting point.
return new MapPoint(firstPoint.X + scaled.X, firstPoint.Y + scaled.Y, firstPoint.Z + scaled.Z);
}
private async void Geoline_TargetVisibilityChanged(object sender, EventArgs e)
{
// This is needed because Runtime delivers notifications from a different thread that doesn't have access to UI controls.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, UpdateUiAndSelection);
}
private void UpdateUiAndSelection()
{
switch (_geoLine.TargetVisibility)
{
case LineOfSightTargetVisibility.Obstructed:
StatusLabel.Text = "Status: Obstructed";
_taxiGraphic.IsSelected = false;
break;
case LineOfSightTargetVisibility.Visible:
StatusLabel.Text = "Status: Visible";
_taxiGraphic.IsSelected = true;
break;
default:
case LineOfSightTargetVisibility.Unknown:
StatusLabel.Text = "Status: Unknown";
_taxiGraphic.IsSelected = false;
break;
}
}
private void HeightSlider_ValueChanged(object sender, Windows.UI.Xaml.Controls.Primitives.RangeBaseValueChangedEventArgs e)
{
// Update the height of the observer based on the slider value.
// Constrain the min and max to 20 and 150 units.
const double minHeight = 20;
const double maxHeight = 150;
// Scale the slider value; its default range is 0-100.
double value = e.NewValue / 100;
// Get the current point.
MapPoint oldPoint = (MapPoint)_observerGraphic.Geometry;
// Create a new point with the same (x,y) but updated z.
MapPoint newPoint = new MapPoint(oldPoint.X, oldPoint.Y, (maxHeight - minHeight) * value + minHeight);
// Apply the updated geometry to the observer point.
_observerGraphic.Geometry = newPoint;
}
}
}
| |
// 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.IdentityModel.Selectors;
using System.IdentityModel.Tokens;
using System.Net.Http;
using System.Net.Security;
using System.Runtime;
using System.Security.Cryptography.X509Certificates;
using System.ServiceModel.Description;
using System.ServiceModel.Security;
using System.ServiceModel.Security.Tokens;
using System.Threading.Tasks;
namespace System.ServiceModel.Channels
{
internal class HttpsChannelFactory<TChannel> : HttpChannelFactory<TChannel>
{
private bool _requireClientCertificate;
private X509CertificateValidator _sslCertificateValidator;
private Func<HttpRequestMessage, X509Certificate2, X509Chain, SslPolicyErrors, bool> _remoteCertificateValidationCallback;
internal HttpsChannelFactory(HttpsTransportBindingElement httpsBindingElement, BindingContext context)
: base(httpsBindingElement, context)
{
_requireClientCertificate = httpsBindingElement.RequireClientCertificate;
ClientCredentials credentials = context.BindingParameters.Find<ClientCredentials>();
if (credentials != null && credentials.ServiceCertificate.SslCertificateAuthentication != null)
{
_sslCertificateValidator = credentials.ServiceCertificate.SslCertificateAuthentication.GetCertificateValidator();
_remoteCertificateValidationCallback = RemoteCertificateValidationCallback;
}
}
public override string Scheme
{
get
{
return UriEx.UriSchemeHttps;
}
}
public bool RequireClientCertificate
{
get
{
return _requireClientCertificate;
}
}
public override bool IsChannelBindingSupportEnabled
{
get
{
return false;
}
}
public override T GetProperty<T>()
{
return base.GetProperty<T>();
}
protected override void ValidateCreateChannelParameters(EndpointAddress remoteAddress, Uri via)
{
if (string.Compare(via.Scheme, "wss", StringComparison.OrdinalIgnoreCase) != 0)
{
ValidateScheme(via);
}
if (MessageVersion.Addressing == AddressingVersion.None && remoteAddress.Uri != via)
{
throw DiagnosticUtility.ExceptionUtility.ThrowHelperError(CreateToMustEqualViaException(remoteAddress.Uri, via));
}
}
protected override TChannel OnCreateChannelCore(EndpointAddress address, Uri via)
{
ValidateCreateChannelParameters(address, via);
ValidateWebSocketTransportUsage();
if (typeof(TChannel) == typeof(IRequestChannel))
{
return (TChannel)(object)new HttpsClientRequestChannel((HttpsChannelFactory<IRequestChannel>)(object)this, address, via, ManualAddressing);
}
else
{
return (TChannel)(object)new ClientWebSocketTransportDuplexSessionChannel((HttpChannelFactory<IDuplexSessionChannel>)(object)this, _clientWebSocketFactory, address, via);
}
}
protected override bool IsSecurityTokenManagerRequired()
{
return _requireClientCertificate || base.IsSecurityTokenManagerRequired();
}
private void OnOpenCore()
{
if (_requireClientCertificate && SecurityTokenManager == null)
{
throw Fx.AssertAndThrow("HttpsChannelFactory: SecurityTokenManager is null on open.");
}
}
protected override void OnEndOpen(IAsyncResult result)
{
base.OnEndOpen(result);
OnOpenCore();
}
protected override void OnOpen(TimeSpan timeout)
{
base.OnOpen(timeout);
OnOpenCore();
}
protected internal override async Task OnOpenAsync(TimeSpan timeout)
{
await base.OnOpenAsync(timeout);
OnOpenCore();
}
internal SecurityTokenProvider CreateAndOpenCertificateTokenProvider(EndpointAddress target, Uri via, ChannelParameterCollection channelParameters, TimeSpan timeout)
{
if (!RequireClientCertificate)
{
return null;
}
SecurityTokenProvider certificateProvider = TransportSecurityHelpers.GetCertificateTokenProvider(
SecurityTokenManager, target, via, Scheme, channelParameters);
SecurityUtils.OpenTokenProviderIfRequired(certificateProvider, timeout);
return certificateProvider;
}
internal SecurityTokenContainer GetCertificateSecurityToken(SecurityTokenProvider certificateProvider,
EndpointAddress to, Uri via, ChannelParameterCollection channelParameters, ref TimeoutHelper timeoutHelper)
{
SecurityToken token = null;
SecurityTokenContainer tokenContainer = null;
SecurityTokenProvider requestCertificateProvider;
if (ManualAddressing && RequireClientCertificate)
{
requestCertificateProvider = CreateAndOpenCertificateTokenProvider(to, via, channelParameters, timeoutHelper.RemainingTime());
}
else
{
requestCertificateProvider = certificateProvider;
}
if (requestCertificateProvider != null)
{
token = requestCertificateProvider.GetTokenAsync(timeoutHelper.GetCancellationToken()).GetAwaiter().GetResult();
}
if (ManualAddressing && RequireClientCertificate)
{
SecurityUtils.AbortTokenProviderIfRequired(requestCertificateProvider);
}
if (token != null)
{
tokenContainer = new SecurityTokenContainer(token);
}
return tokenContainer;
}
private void AddServerCertMappingOrSetRemoteCertificateValidationCallback(ServiceModelHttpMessageHandler messageHandler, EndpointAddress to)
{
Fx.Assert(messageHandler != null, "httpMessageHandler should not be null.");
if (_sslCertificateValidator != null)
{
if (!messageHandler.SupportsCertificateValidationCallback)
{
throw ExceptionHelper.PlatformNotSupported("Server certificate validation not supported yet");
}
messageHandler.ServerCertificateValidationCallback = _remoteCertificateValidationCallback;
}
else
{
if (to.Identity is X509CertificateEndpointIdentity)
{
HttpTransportSecurityHelpers.SetServerCertificateValidationCallback(messageHandler);
}
}
}
private bool RemoteCertificateValidationCallback(HttpRequestMessage sender, X509Certificate2 certificate, X509Chain chain, SslPolicyErrors sslPolicyErrors)
{
Fx.Assert(_sslCertificateValidator != null, "sslCertificateAuthentidation should not be null.");
try
{
_sslCertificateValidator.Validate(certificate);
return true;
}
catch (SecurityTokenValidationException ex)
{
FxTrace.Exception.AsInformation(ex);
return false;
}
catch (Exception ex)
{
if (Fx.IsFatal(ex))
{
throw;
}
FxTrace.Exception.AsWarning(ex);
return false;
}
}
internal override ServiceModelHttpMessageHandler GetHttpMessageHandler(EndpointAddress to, SecurityTokenContainer clientCertificateToken)
{
ServiceModelHttpMessageHandler handler = base.GetHttpMessageHandler(to, clientCertificateToken);
if (RequireClientCertificate)
{
SetCertificate(handler, clientCertificateToken);
}
AddServerCertMappingOrSetRemoteCertificateValidationCallback(handler, to);
return handler;
}
private static void SetCertificate(ServiceModelHttpMessageHandler handler, SecurityTokenContainer clientCertificateToken)
{
if (clientCertificateToken != null)
{
if (!handler.SupportsClientCertificates)
{
throw ExceptionHelper.PlatformNotSupported("Client certificates not supported yet");
}
X509SecurityToken x509Token = (X509SecurityToken)clientCertificateToken.Token;
handler.ClientCertificates.Add(x509Token.Certificate);
}
}
protected class HttpsClientRequestChannel : HttpClientRequestChannel
{
private SecurityTokenProvider _certificateProvider;
private HttpsChannelFactory<IRequestChannel> _factory;
public HttpsClientRequestChannel(HttpsChannelFactory<IRequestChannel> factory, EndpointAddress to, Uri via, bool manualAddressing)
: base(factory, to, via, manualAddressing)
{
_factory = factory;
}
public new HttpsChannelFactory<IRequestChannel> Factory
{
get { return _factory; }
}
private void CreateAndOpenTokenProvider(TimeSpan timeout)
{
if (!ManualAddressing && Factory.RequireClientCertificate)
{
_certificateProvider = Factory.CreateAndOpenCertificateTokenProvider(RemoteAddress, Via, ChannelParameters, timeout);
}
}
private void CloseTokenProvider(TimeSpan timeout)
{
if (_certificateProvider != null)
{
SecurityUtils.CloseTokenProviderIfRequired(_certificateProvider, timeout);
}
}
private void AbortTokenProvider()
{
if (_certificateProvider != null)
{
SecurityUtils.AbortTokenProviderIfRequired(_certificateProvider);
}
}
protected override IAsyncResult OnBeginOpen(TimeSpan timeout, AsyncCallback callback, object state)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CreateAndOpenTokenProvider(timeoutHelper.RemainingTime());
return base.OnBeginOpen(timeoutHelper.RemainingTime(), callback, state);
}
protected override void OnOpen(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CreateAndOpenTokenProvider(timeoutHelper.RemainingTime());
base.OnOpen(timeoutHelper.RemainingTime());
}
internal protected override Task OnOpenAsync(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CreateAndOpenTokenProvider(timeoutHelper.RemainingTime());
return base.OnOpenAsync(timeoutHelper.RemainingTime());
}
protected override void OnAbort()
{
AbortTokenProvider();
base.OnAbort();
}
protected override IAsyncResult OnBeginClose(TimeSpan timeout, AsyncCallback callback, object state)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CloseTokenProvider(timeoutHelper.RemainingTime());
return base.OnBeginClose(timeoutHelper.RemainingTime(), callback, state);
}
protected override void OnClose(TimeSpan timeout)
{
TimeoutHelper timeoutHelper = new TimeoutHelper(timeout);
CloseTokenProvider(timeoutHelper.RemainingTime());
base.OnClose(timeoutHelper.RemainingTime());
}
internal override void OnHttpRequestCompleted(HttpRequestMessage request)
{
}
internal override async Task<HttpClient> GetHttpClientAsync(EndpointAddress to, Uri via, TimeoutHelper timeoutHelper)
{
SecurityTokenContainer clientCertificateToken = Factory.GetCertificateSecurityToken(_certificateProvider, to, via, this.ChannelParameters, ref timeoutHelper);
HttpClient httpClient = await base.GetHttpClientAsync(to, via, clientCertificateToken, timeoutHelper);
return httpClient;
}
}
}
}
| |
using Lucene.Net.Diagnostics;
using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace Lucene.Net.Search
{
/*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using AtomicReaderContext = Lucene.Net.Index.AtomicReaderContext;
using IBits = Lucene.Net.Util.IBits;
using IndexReader = Lucene.Net.Index.IndexReader;
using Term = Lucene.Net.Index.Term;
using ToStringUtils = Lucene.Net.Util.ToStringUtils;
/// <summary>
/// A query that applies a filter to the results of another query.
///
/// <para/>Note: the bits are retrieved from the filter each time this
/// query is used in a search - use a <see cref="CachingWrapperFilter"/> to avoid
/// regenerating the bits every time.
/// <para/>
/// @since 1.4 </summary>
/// <seealso cref="CachingWrapperFilter"/>
public class FilteredQuery : Query
{
private readonly Query query;
private readonly Filter filter;
private readonly FilterStrategy strategy;
/// <summary>
/// Constructs a new query which applies a filter to the results of the original query.
/// <see cref="Filter.GetDocIdSet(AtomicReaderContext, IBits)"/> will be called every time this query is used in a search. </summary>
/// <param name="query"> Query to be filtered, cannot be <c>null</c>. </param>
/// <param name="filter"> Filter to apply to query results, cannot be <c>null</c>. </param>
public FilteredQuery(Query query, Filter filter)
: this(query, filter, RANDOM_ACCESS_FILTER_STRATEGY)
{
}
/// <summary>
/// Expert: Constructs a new query which applies a filter to the results of the original query.
/// <see cref="Filter.GetDocIdSet(AtomicReaderContext, IBits)"/> will be called every time this query is used in a search. </summary>
/// <param name="query"> Query to be filtered, cannot be <c>null</c>. </param>
/// <param name="filter"> Filter to apply to query results, cannot be <c>null</c>. </param>
/// <param name="strategy"> A filter strategy used to create a filtered scorer.
/// </param>
/// <seealso cref="FilterStrategy"/>
public FilteredQuery(Query query, Filter filter, FilterStrategy strategy)
{
if (query == null || filter == null)
{
throw new ArgumentException("Query and filter cannot be null.");
}
if (strategy == null)
{
throw new ArgumentException("FilterStrategy can not be null");
}
this.strategy = strategy;
this.query = query;
this.filter = filter;
}
/// <summary>
/// Returns a <see cref="Weight"/> that applies the filter to the enclosed query's <see cref="Weight"/>.
/// this is accomplished by overriding the <see cref="Scorer"/> returned by the <see cref="Weight"/>.
/// </summary>
public override Weight CreateWeight(IndexSearcher searcher)
{
Weight weight = query.CreateWeight(searcher);
return new WeightAnonymousInnerClassHelper(this, weight);
}
private class WeightAnonymousInnerClassHelper : Weight
{
private readonly FilteredQuery outerInstance;
private Lucene.Net.Search.Weight weight;
public WeightAnonymousInnerClassHelper(FilteredQuery outerInstance, Lucene.Net.Search.Weight weight)
{
this.outerInstance = outerInstance;
this.weight = weight;
}
public override bool ScoresDocsOutOfOrder => true;
public override float GetValueForNormalization()
{
return weight.GetValueForNormalization() * outerInstance.Boost * outerInstance.Boost; // boost sub-weight
}
public override void Normalize(float norm, float topLevelBoost)
{
weight.Normalize(norm, topLevelBoost * outerInstance.Boost); // incorporate boost
}
public override Explanation Explain(AtomicReaderContext ir, int i)
{
Explanation inner = weight.Explain(ir, i);
Filter f = outerInstance.filter;
DocIdSet docIdSet = f.GetDocIdSet(ir, ir.AtomicReader.LiveDocs);
DocIdSetIterator docIdSetIterator = docIdSet == null ? DocIdSetIterator.GetEmpty() : docIdSet.GetIterator();
if (docIdSetIterator == null)
{
docIdSetIterator = DocIdSetIterator.GetEmpty();
}
if (docIdSetIterator.Advance(i) == i)
{
return inner;
}
else
{
Explanation result = new Explanation(0.0f, "failure to match filter: " + f.ToString());
result.AddDetail(inner);
return result;
}
}
// return this query
public override Query Query => outerInstance;
// return a filtering scorer
public override Scorer GetScorer(AtomicReaderContext context, IBits acceptDocs)
{
if (Debugging.AssertsEnabled) Debugging.Assert(outerInstance.filter != null);
DocIdSet filterDocIdSet = outerInstance.filter.GetDocIdSet(context, acceptDocs);
if (filterDocIdSet == null)
{
// this means the filter does not accept any documents.
return null;
}
return outerInstance.strategy.FilteredScorer(context, weight, filterDocIdSet);
}
// return a filtering top scorer
public override BulkScorer GetBulkScorer(AtomicReaderContext context, bool scoreDocsInOrder, IBits acceptDocs)
{
if (Debugging.AssertsEnabled) Debugging.Assert(outerInstance.filter != null);
DocIdSet filterDocIdSet = outerInstance.filter.GetDocIdSet(context, acceptDocs);
if (filterDocIdSet == null)
{
// this means the filter does not accept any documents.
return null;
}
return outerInstance.strategy.FilteredBulkScorer(context, weight, scoreDocsInOrder, filterDocIdSet);
}
}
/// <summary>
/// A scorer that consults the filter if a document was matched by the
/// delegate scorer. This is useful if the filter computation is more expensive
/// than document scoring or if the filter has a linear running time to compute
/// the next matching doc like exact geo distances.
/// </summary>
private sealed class QueryFirstScorer : Scorer
{
private readonly Scorer scorer;
private int scorerDoc = -1;
private readonly IBits filterBits;
internal QueryFirstScorer(Weight weight, IBits filterBits, Scorer other)
: base(weight)
{
this.scorer = other;
this.filterBits = filterBits;
}
public override int NextDoc()
{
int doc;
for (; ; )
{
doc = scorer.NextDoc();
if (doc == Scorer.NO_MORE_DOCS || filterBits.Get(doc))
{
return scorerDoc = doc;
}
}
}
public override int Advance(int target)
{
int doc = scorer.Advance(target);
if (doc != Scorer.NO_MORE_DOCS && !filterBits.Get(doc))
{
return scorerDoc = NextDoc();
}
else
{
return scorerDoc = doc;
}
}
public override int DocID => scorerDoc;
public override float GetScore()
{
return scorer.GetScore();
}
public override int Freq => scorer.Freq;
public override ICollection<ChildScorer> GetChildren()
{
return new[] { new ChildScorer(scorer, "FILTERED") };
}
public override long GetCost()
{
return scorer.GetCost();
}
}
private class QueryFirstBulkScorer : BulkScorer
{
private readonly Scorer scorer;
private readonly IBits filterBits;
public QueryFirstBulkScorer(Scorer scorer, IBits filterBits)
{
this.scorer = scorer;
this.filterBits = filterBits;
}
public override bool Score(ICollector collector, int maxDoc)
{
// the normalization trick already applies the boost of this query,
// so we can use the wrapped scorer directly:
collector.SetScorer(scorer);
if (scorer.DocID == -1)
{
scorer.NextDoc();
}
while (true)
{
int scorerDoc = scorer.DocID;
if (scorerDoc < maxDoc)
{
if (filterBits.Get(scorerDoc))
{
collector.Collect(scorerDoc);
}
scorer.NextDoc();
}
else
{
break;
}
}
return scorer.DocID != Scorer.NO_MORE_DOCS;
}
}
/// <summary>
/// A <see cref="Scorer"/> that uses a "leap-frog" approach (also called "zig-zag join"). The scorer and the filter
/// take turns trying to advance to each other's next matching document, often
/// jumping past the target document. When both land on the same document, it's
/// collected.
/// </summary>
private class LeapFrogScorer : Scorer
{
private readonly DocIdSetIterator secondary;
private readonly DocIdSetIterator primary;
private readonly Scorer scorer;
protected int m_primaryDoc = -1;
protected int m_secondaryDoc = -1;
protected internal LeapFrogScorer(Weight weight, DocIdSetIterator primary, DocIdSetIterator secondary, Scorer scorer)
: base(weight)
{
this.primary = primary;
this.secondary = secondary;
this.scorer = scorer;
}
private int AdvanceToNextCommonDoc()
{
for (; ; )
{
if (m_secondaryDoc < m_primaryDoc)
{
m_secondaryDoc = secondary.Advance(m_primaryDoc);
}
else if (m_secondaryDoc == m_primaryDoc)
{
return m_primaryDoc;
}
else
{
m_primaryDoc = primary.Advance(m_secondaryDoc);
}
}
}
public override sealed int NextDoc()
{
m_primaryDoc = PrimaryNext();
return AdvanceToNextCommonDoc();
}
protected virtual int PrimaryNext()
{
return primary.NextDoc();
}
public override sealed int Advance(int target)
{
if (target > m_primaryDoc)
{
m_primaryDoc = primary.Advance(target);
}
return AdvanceToNextCommonDoc();
}
public override sealed int DocID => m_secondaryDoc;
public override sealed float GetScore()
{
return scorer.GetScore();
}
public override sealed int Freq => scorer.Freq;
public override sealed ICollection<ChildScorer> GetChildren()
{
return new[] { new ChildScorer(scorer, "FILTERED") };
}
public override long GetCost()
{
return Math.Min(primary.GetCost(), secondary.GetCost());
}
}
// TODO once we have way to figure out if we use RA or LeapFrog we can remove this scorer
private sealed class PrimaryAdvancedLeapFrogScorer : LeapFrogScorer
{
private readonly int firstFilteredDoc;
internal PrimaryAdvancedLeapFrogScorer(Weight weight, int firstFilteredDoc, DocIdSetIterator filterIter, Scorer other)
: base(weight, filterIter, other, other)
{
this.firstFilteredDoc = firstFilteredDoc;
this.m_primaryDoc = firstFilteredDoc; // initialize to prevent and advance call to move it further
}
protected override int PrimaryNext()
{
if (m_secondaryDoc != -1)
{
return base.PrimaryNext();
}
else
{
return firstFilteredDoc;
}
}
}
/// <summary>
/// Rewrites the query. If the wrapped is an instance of
/// <see cref="MatchAllDocsQuery"/> it returns a <see cref="ConstantScoreQuery"/>. Otherwise
/// it returns a new <see cref="FilteredQuery"/> wrapping the rewritten query.
/// </summary>
public override Query Rewrite(IndexReader reader)
{
Query queryRewritten = query.Rewrite(reader);
if (queryRewritten != query)
{
// rewrite to a new FilteredQuery wrapping the rewritten query
Query rewritten = new FilteredQuery(queryRewritten, filter, strategy);
rewritten.Boost = this.Boost;
return rewritten;
}
else
{
// nothing to rewrite, we are done!
return this;
}
}
/// <summary>
/// Returns this <see cref="FilteredQuery"/>'s (unfiltered) <see cref="Query"/> </summary>
public Query Query => query;
/// <summary>
/// Returns this <see cref="FilteredQuery"/>'s filter </summary>
public Filter Filter => filter;
/// <summary>
/// Returns this <see cref="FilteredQuery"/>'s <seealso cref="FilterStrategy"/> </summary>
public virtual FilterStrategy Strategy => this.strategy;
/// <summary>
/// Expert: adds all terms occurring in this query to the terms set. Only
/// works if this query is in its rewritten (<see cref="Rewrite(IndexReader)"/>) form.
/// </summary>
/// <exception cref="InvalidOperationException"> If this query is not yet rewritten </exception>
public override void ExtractTerms(ISet<Term> terms)
{
Query.ExtractTerms(terms);
}
/// <summary>
/// Prints a user-readable version of this query. </summary>
public override string ToString(string s)
{
StringBuilder buffer = new StringBuilder();
buffer.Append("filtered(");
buffer.Append(query.ToString(s));
buffer.Append(")->");
buffer.Append(filter);
buffer.Append(ToStringUtils.Boost(Boost));
return buffer.ToString();
}
/// <summary>
/// Returns true if <paramref name="o"/> is equal to this. </summary>
public override bool Equals(object o)
{
if (o == this)
{
return true;
}
if (!base.Equals(o))
{
return false;
}
if (Debugging.AssertsEnabled) Debugging.Assert(o is FilteredQuery);
FilteredQuery fq = (FilteredQuery)o;
return fq.query.Equals(this.query) && fq.filter.Equals(this.filter) && fq.strategy.Equals(this.strategy);
}
/// <summary>
/// Returns a hash code value for this object. </summary>
public override int GetHashCode()
{
int hash = base.GetHashCode();
hash = hash * 31 + strategy.GetHashCode();
hash = hash * 31 + query.GetHashCode();
hash = hash * 31 + filter.GetHashCode();
return hash;
}
/// <summary>
/// A <see cref="FilterStrategy"/> that conditionally uses a random access filter if
/// the given <see cref="DocIdSet"/> supports random access (returns a non-null value
/// from <see cref="DocIdSet.Bits"/>) and
/// <see cref="RandomAccessFilterStrategy.UseRandomAccess(IBits, int)"/> returns
/// <c>true</c>. Otherwise this strategy falls back to a "zig-zag join" (
/// <see cref="FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY"/>) strategy.
///
/// <para>
/// Note: this strategy is the default strategy in <see cref="FilteredQuery"/>
/// </para>
/// </summary>
public static readonly FilterStrategy RANDOM_ACCESS_FILTER_STRATEGY = new RandomAccessFilterStrategy();
/// <summary>
/// A filter strategy that uses a "leap-frog" approach (also called "zig-zag join").
/// The scorer and the filter
/// take turns trying to advance to each other's next matching document, often
/// jumping past the target document. When both land on the same document, it's
/// collected.
/// <para>
/// Note: this strategy uses the filter to lead the iteration.
/// </para>
/// </summary>
public static readonly FilterStrategy LEAP_FROG_FILTER_FIRST_STRATEGY = new LeapFrogFilterStrategy(false);
/// <summary>
/// A filter strategy that uses a "leap-frog" approach (also called "zig-zag join").
/// The scorer and the filter
/// take turns trying to advance to each other's next matching document, often
/// jumping past the target document. When both land on the same document, it's
/// collected.
/// <para>
/// Note: this strategy uses the query to lead the iteration.
/// </para>
/// </summary>
public static readonly FilterStrategy LEAP_FROG_QUERY_FIRST_STRATEGY = new LeapFrogFilterStrategy(true);
/// <summary>
/// A filter strategy that advances the <see cref="Search.Query"/> or rather its <see cref="Scorer"/> first and consults the
/// filter <see cref="DocIdSet"/> for each matched document.
/// <para>
/// Note: this strategy requires a <see cref="DocIdSet.Bits"/> to return a non-null value. Otherwise
/// this strategy falls back to <see cref="FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY"/>
/// </para>
/// <para>
/// Use this strategy if the filter computation is more expensive than document
/// scoring or if the filter has a linear running time to compute the next
/// matching doc like exact geo distances.
/// </para>
/// </summary>
public static readonly FilterStrategy QUERY_FIRST_FILTER_STRATEGY = new QueryFirstFilterStrategy();
/// <summary>
/// Abstract class that defines how the filter (<see cref="DocIdSet"/>) applied during document collection. </summary>
public abstract class FilterStrategy
{
/// <summary>
/// Returns a filtered <see cref="Scorer"/> based on this strategy.
/// </summary>
/// <param name="context">
/// the <see cref="AtomicReaderContext"/> for which to return the <see cref="Scorer"/>. </param>
/// <param name="weight"> the <see cref="FilteredQuery"/> <see cref="Weight"/> to create the filtered scorer. </param>
/// <param name="docIdSet"> the filter <see cref="DocIdSet"/> to apply </param>
/// <returns> a filtered scorer
/// </returns>
/// <exception cref="IOException"> if an <see cref="IOException"/> occurs </exception>
public abstract Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet);
/// <summary>
/// Returns a filtered <see cref="BulkScorer"/> based on this
/// strategy. this is an optional method: the default
/// implementation just calls <see cref="FilteredScorer(AtomicReaderContext, Weight, DocIdSet)"/> and
/// wraps that into a <see cref="BulkScorer"/>.
/// </summary>
/// <param name="context">
/// the <seealso cref="AtomicReaderContext"/> for which to return the <seealso cref="Scorer"/>. </param>
/// <param name="weight"> the <seealso cref="FilteredQuery"/> <seealso cref="Weight"/> to create the filtered scorer. </param>
/// <param name="scoreDocsInOrder"> <c>true</c> to score docs in order </param>
/// <param name="docIdSet"> the filter <seealso cref="DocIdSet"/> to apply </param>
/// <returns> a filtered top scorer </returns>
public virtual BulkScorer FilteredBulkScorer(AtomicReaderContext context, Weight weight, bool scoreDocsInOrder, DocIdSet docIdSet)
{
Scorer scorer = FilteredScorer(context, weight, docIdSet);
if (scorer == null)
{
return null;
}
// this impl always scores docs in order, so we can
// ignore scoreDocsInOrder:
return new Weight.DefaultBulkScorer(scorer);
}
}
/// <summary>
/// A <see cref="FilterStrategy"/> that conditionally uses a random access filter if
/// the given <see cref="DocIdSet"/> supports random access (returns a non-null value
/// from <see cref="DocIdSet.Bits"/>) and
/// <see cref="RandomAccessFilterStrategy.UseRandomAccess(IBits, int)"/> returns
/// <code>true</code>. Otherwise this strategy falls back to a "zig-zag join" (
/// <see cref="FilteredQuery.LEAP_FROG_FILTER_FIRST_STRATEGY"/>) strategy .
/// </summary>
public class RandomAccessFilterStrategy : FilterStrategy
{
public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet)
{
DocIdSetIterator filterIter = docIdSet.GetIterator();
if (filterIter == null)
{
// this means the filter does not accept any documents.
return null;
}
int firstFilterDoc = filterIter.NextDoc();
if (firstFilterDoc == DocIdSetIterator.NO_MORE_DOCS)
{
return null;
}
IBits filterAcceptDocs = docIdSet.Bits;
// force if RA is requested
bool useRandomAccess = filterAcceptDocs != null && UseRandomAccess(filterAcceptDocs, firstFilterDoc);
if (useRandomAccess)
{
// if we are using random access, we return the inner scorer, just with other acceptDocs
return weight.GetScorer(context, filterAcceptDocs);
}
else
{
if (Debugging.AssertsEnabled) Debugging.Assert(firstFilterDoc > -1);
// we are gonna advance() this scorer, so we set inorder=true/toplevel=false
// we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice
Scorer scorer = weight.GetScorer(context, null);
// TODO once we have way to figure out if we use RA or LeapFrog we can remove this scorer
return (scorer == null) ? null : new PrimaryAdvancedLeapFrogScorer(weight, firstFilterDoc, filterIter, scorer);
}
}
/// <summary>
/// Expert: decides if a filter should be executed as "random-access" or not.
/// Random-access means the filter "filters" in a similar way as deleted docs are filtered
/// in Lucene. This is faster when the filter accepts many documents.
/// However, when the filter is very sparse, it can be faster to execute the query+filter
/// as a conjunction in some cases.
/// <para/>
/// The default implementation returns <c>true</c> if the first document accepted by the
/// filter is < 100.
/// <para/>
/// @lucene.internal
/// </summary>
protected virtual bool UseRandomAccess(IBits bits, int firstFilterDoc)
{
//TODO once we have a cost API on filters and scorers we should rethink this heuristic
return firstFilterDoc < 100;
}
}
private sealed class LeapFrogFilterStrategy : FilterStrategy
{
private readonly bool scorerFirst;
internal LeapFrogFilterStrategy(bool scorerFirst)
{
this.scorerFirst = scorerFirst;
}
public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet)
{
DocIdSetIterator filterIter = docIdSet.GetIterator();
if (filterIter == null)
{
// this means the filter does not accept any documents.
return null;
}
// we pass null as acceptDocs, as our filter has already respected acceptDocs, no need to do twice
Scorer scorer = weight.GetScorer(context, null);
if (scorer == null)
{
return null;
}
if (scorerFirst)
{
return new LeapFrogScorer(weight, scorer, filterIter, scorer);
}
else
{
return new LeapFrogScorer(weight, filterIter, scorer, scorer);
}
}
}
/// <summary>
/// A filter strategy that advances the <see cref="Scorer"/> first and consults the
/// <see cref="DocIdSet"/> for each matched document.
/// <para>
/// Note: this strategy requires a <see cref="DocIdSet.Bits"/> to return a non-null value. Otherwise
/// this strategy falls back to <see cref="FilteredQuery.LEAP_FROG_QUERY_FIRST_STRATEGY"/>
/// </para>
/// <para>
/// Use this strategy if the filter computation is more expensive than document
/// scoring or if the filter has a linear running time to compute the next
/// matching doc like exact geo distances.
/// </para>
/// </summary>
private sealed class QueryFirstFilterStrategy : FilterStrategy
{
public override Scorer FilteredScorer(AtomicReaderContext context, Weight weight, DocIdSet docIdSet)
{
IBits filterAcceptDocs = docIdSet.Bits;
if (filterAcceptDocs == null)
{
// Filter does not provide random-access Bits; we
// must fallback to leapfrog:
return LEAP_FROG_QUERY_FIRST_STRATEGY.FilteredScorer(context, weight, docIdSet);
}
Scorer scorer = weight.GetScorer(context, null);
return scorer == null ? null : new QueryFirstScorer(weight, filterAcceptDocs, scorer);
}
public override BulkScorer FilteredBulkScorer(AtomicReaderContext context, Weight weight, bool scoreDocsInOrder, DocIdSet docIdSet) // ignored (we always top-score in order)
{
IBits filterAcceptDocs = docIdSet.Bits;
if (filterAcceptDocs == null)
{
// Filter does not provide random-access Bits; we
// must fallback to leapfrog:
return LEAP_FROG_QUERY_FIRST_STRATEGY.FilteredBulkScorer(context, weight, scoreDocsInOrder, docIdSet);
}
Scorer scorer = weight.GetScorer(context, null);
return scorer == null ? null : new QueryFirstBulkScorer(scorer, filterAcceptDocs);
}
}
}
}
| |
// 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;
using System.Collections.Generic;
using System.Linq;
namespace Moq
{
internal sealed class SetupCollection : ISetupList
{
private List<Setup> setups;
private volatile bool hasEventSetup;
public SetupCollection()
{
this.setups = new List<Setup>();
this.hasEventSetup = false;
}
public int Count
{
get
{
lock (this.setups)
{
return this.setups.Count;
}
}
}
public bool HasEventSetup
{
get
{
return this.hasEventSetup;
}
}
public ISetup this[int index]
{
get
{
lock (this.setups)
{
return this.setups[index];
}
}
}
public void Add(Setup setup)
{
lock (this.setups)
{
if (setup.Method.IsEventAddAccessor() || setup.Method.IsEventRemoveAccessor())
{
this.hasEventSetup = true;
}
this.setups.Add(setup);
this.MarkOverriddenSetups();
}
}
private void MarkOverriddenSetups()
{
var visitedSetups = new HashSet<InvocationShape>();
// Iterating in reverse order because newer setups are more relevant than (i.e. override) older ones
for (int i = this.setups.Count - 1; i >= 0; --i)
{
var setup = this.setups[i];
if (setup.IsOverridden || setup.IsConditional) continue;
if (!visitedSetups.Add(setup.Expectation))
{
// A setup with the same expression has already been iterated over,
// meaning that this older setup is an overridden one.
setup.MarkAsOverridden();
}
}
}
public bool Any(Func<Setup, bool> predicate)
{
lock (this.setups)
{
return this.setups.Any(predicate);
}
}
public void RemoveAllPropertyAccessorSetups()
{
// Fast path (no `lock`) when there are no setups:
if (this.setups.Count == 0)
{
return;
}
lock (this.setups)
{
this.setups.RemoveAll(x => x.Method.IsPropertyAccessor());
// NOTE: In the general case, removing a setup means that some overridden setups might no longer
// be shadowed, and their `IsOverridden` flag should go back from `true` to `false`.
//
// In this particular case however, we don't need to worry about this because we are categorically
// removing all property accessors, and they could only have overridden other property accessors.
}
}
public void Clear()
{
lock (this.setups)
{
this.setups.Clear();
this.hasEventSetup = false;
}
}
public Setup FindMatchFor(Invocation invocation)
{
// Fast path (no `lock`) when there are no setups:
if (this.setups.Count == 0)
{
return null;
}
lock (this.setups)
{
// Iterating in reverse order because newer setups are more relevant than (i.e. override) older ones
for (int i = this.setups.Count - 1; i >= 0; --i)
{
var setup = this.setups[i];
if (setup.IsOverridden) continue;
if (setup.Matches(invocation))
{
return setup;
}
}
}
return null;
}
public IEnumerable<Setup> GetInnerMockSetups()
{
return this.ToArray(setup => !setup.IsOverridden && !setup.IsConditional && setup.InnerMock != null);
}
public void Reset()
{
lock (this.setups)
{
foreach (var setup in this.setups)
{
setup.Reset();
}
}
}
public IReadOnlyList<Setup> ToArray()
{
lock (this.setups)
{
return this.setups.ToArray();
}
}
public IReadOnlyList<Setup> ToArray(Func<Setup, bool> predicate)
{
var matchingSetups = new Stack<Setup>();
lock (this.setups)
{
// Iterating in reverse order because newer setups are more relevant than (i.e. override) older ones
for (int i = this.setups.Count - 1; i >= 0; --i)
{
var setup = this.setups[i];
if (predicate(setup))
{
matchingSetups.Push(setup);
}
}
}
return matchingSetups.ToArray();
}
public IEnumerator<ISetup> GetEnumerator()
{
return this.ToArray().GetEnumerator();
// ^^^^^^^^^^
// TODO: This is somewhat inefficient. We could avoid this array allocation by converting
// this class to something like `InvocationCollection`, however this won't be trivial due to
// the presence of a removal operation in `RemoveAllPropertyAccessorSetups`.
}
IEnumerator IEnumerable.GetEnumerator() => this.GetEnumerator();
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
#if USE_MDT_EVENTSOURCE
using Microsoft.Diagnostics.Tracing;
#else
using System.Diagnostics.Tracing;
#endif
using Xunit;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Text.RegularExpressions;
using System.Threading;
namespace BasicEventSourceTests
{
/// <summary>
/// Tests the user experience for common user errors.
/// </summary>
public class TestsUserErrors
{
/// <summary>
/// Try to pass a user defined class (even with EventData)
/// to a manifest based eventSource
/// </summary>
[Fact]
public void Test_BadTypes_Manifest_UserClass()
{
var badEventSource = new BadEventSource_Bad_Type_UserClass();
Test_BadTypes_Manifest(badEventSource);
}
private void Test_BadTypes_Manifest(EventSource source)
{
try
{
using (var listener = new EventListenerListener())
{
var events = new List<Event>();
Debug.WriteLine("Adding delegate to onevent");
listener.OnEvent = delegate (Event data) { events.Add(data); };
listener.EventSourceCommand(source.Name, EventCommand.Enable);
listener.Dispose();
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("EventSourceMessage", _event.EventName);
// Check the exception text if not ProjectN.
if (!PlatformDetection.IsNetNative)
{
string message = _event.PayloadString(0, "message");
// expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_Bad_Type_ByteArray: Unsupported type Byte[] in event source. "
Assert.True(Regex.IsMatch(message, "Unsupported type"));
}
}
}
finally
{
source.Dispose();
}
}
/// <summary>
/// Test the
/// </summary>
[Fact]
[SkipOnTargetFramework(TargetFrameworkMonikers.UapAot, "Depends on inspecting IL at runtime.")]
public void Test_BadEventSource_MismatchedIds()
{
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
// We expect only one session to be on when running the test but if a ETW session was left
// hanging, it will confuse the EventListener tests.
EtwListener.EnsureStopped();
#endif // USE_ETW
TestUtilities.CheckNoEventSourcesRunning("Start");
var onStartups = new bool[] { false, true };
var listenerGenerators = new Func<Listener>[]
{
() => new EventListenerListener(),
#if USE_ETW // TODO: Enable when TraceEvent is available on CoreCLR. GitHub issue #4864.
() => new EtwListener()
#endif // USE_ETW
};
var settings = new EventSourceSettings[] { EventSourceSettings.Default, EventSourceSettings.EtwSelfDescribingEventFormat };
// For every interesting combination, run the test and see that we get a nice failure message.
foreach (bool onStartup in onStartups)
{
foreach (Func<Listener> listenerGenerator in listenerGenerators)
{
foreach (EventSourceSettings setting in settings)
{
Test_Bad_EventSource_Startup(onStartup, listenerGenerator(), setting);
}
}
}
TestUtilities.CheckNoEventSourcesRunning("Stop");
}
/// <summary>
/// A helper that can run the test under a variety of conditions
/// * Whether the eventSource is enabled at startup
/// * Whether the listener is ETW or an EventListern
/// * Whether the ETW output is self describing or not.
/// </summary>
private void Test_Bad_EventSource_Startup(bool onStartup, Listener listener, EventSourceSettings settings)
{
var eventSourceName = typeof(BadEventSource_MismatchedIds).Name;
Debug.WriteLine("***** Test_BadEventSource_Startup(OnStartUp: " + onStartup + " Listener: " + listener + " Settings: " + settings + ")");
// Activate the source before the source exists (if told to).
if (onStartup)
listener.EventSourceCommand(eventSourceName, EventCommand.Enable);
var events = new List<Event>();
listener.OnEvent = delegate (Event data) { events.Add(data); };
using (var source = new BadEventSource_MismatchedIds(settings))
{
Assert.Equal(eventSourceName, source.Name);
// activate the source after the source exists (if told to).
if (!onStartup)
listener.EventSourceCommand(eventSourceName, EventCommand.Enable);
source.Event1(1); // Try to send something.
}
listener.Dispose();
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("EventSourceMessage", _event.EventName);
string message = _event.PayloadString(0, "message");
Debug.WriteLine(String.Format("Message=\"{0}\"", message));
// expected message: "ERROR: Exception in Command Processing for EventSource BadEventSource_MismatchedIds: Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent. "
if (!PlatformDetection.IsFullFramework) // Full framework has typo
Assert.True(Regex.IsMatch(message, "Event Event2 was assigned event ID 2 but 1 was passed to WriteEvent"));
}
[Fact]
public void Test_Bad_WriteRelatedID_ParameterName()
{
#if true
Debug.WriteLine("Test disabled because the fix it tests is not in CoreCLR yet.");
#else
BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter bes = null;
EventListenerListener listener = null;
try
{
Guid oldGuid;
Guid newGuid = Guid.NewGuid();
Guid newGuid2 = Guid.NewGuid();
EventSource.SetCurrentThreadActivityId(newGuid, out oldGuid);
bes = new BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter();
using (var listener = new EventListenerListener())
{
var events = new List<Event>();
listener.OnEvent = delegate (Event data) { events.Add(data); };
listener.EventSourceCommand(bes.Name, EventCommand.Enable);
bes.RelatedActivity(newGuid2, "Hello", 42, "AA", "BB");
// Confirm that we get exactly one event from this whole process, that has the error message we expect.
Assert.Equal(events.Count, 1);
Event _event = events[0];
Assert.Equal("EventSourceMessage", _event.EventName);
string message = _event.PayloadString(0, "message");
// expected message: "EventSource expects the first parameter of the Event method to be of type Guid and to be named "relatedActivityId" when calling WriteEventWithRelatedActivityId."
Assert.True(Regex.IsMatch(message, "EventSource expects the first parameter of the Event method to be of type Guid and to be named \"relatedActivityId\" when calling WriteEventWithRelatedActivityId."));
}
}
finally
{
if (bes != null)
{
bes.Dispose();
}
if (listener != null)
{
listener.Dispose();
}
}
#endif
}
}
/// <summary>
/// This EventSource has a common user error, and we want to make sure EventSource
/// gives a reasonable experience in that case.
/// </summary>
internal class BadEventSource_MismatchedIds : EventSource
{
public BadEventSource_MismatchedIds(EventSourceSettings settings) : base(settings) { }
public void Event1(int arg) { WriteEvent(1, arg); }
// Error Used the same event ID for this event.
public void Event2(int arg) { WriteEvent(1, arg); }
}
/// <summary>
/// A manifest based provider with a bad type byte[]
/// </summary>
internal class BadEventSource_Bad_Type_ByteArray : EventSource
{
public void Event1(byte[] myArray) { WriteEvent(1, myArray); }
}
public sealed class BadEventSource_IncorrectWriteRelatedActivityIDFirstParameter : EventSource
{
public void E2()
{
this.Write("sampleevent", new { a = "a string" });
}
[Event(7, Keywords = Keywords.Debug, Message = "Hello Message 7", Channel = EventChannel.Admin, Opcode = EventOpcode.Send)]
public void RelatedActivity(Guid guid, string message, int value, string componentName, string instanceId)
{
WriteEventWithRelatedActivityId(7, guid, message, value, componentName, instanceId);
}
public class Keywords
{
public const EventKeywords Debug = (EventKeywords)0x0002;
}
}
[EventData]
public class UserClass
{
public int i;
};
/// <summary>
/// A manifest based provider with a bad type (only supported in self describing)
/// </summary>
internal class BadEventSource_Bad_Type_UserClass : EventSource
{
public void Event1(UserClass myClass) { WriteEvent(1, myClass); }
}
}
| |
using System;
using System.Collections;
using System.Windows.Forms;
using System.Text;
using System.Threading;
using NationalInstruments.UI;
using NationalInstruments.UI.WindowsForms;
using Data;
using DAQ.FakeData;
using System.Collections.Generic;
namespace ScanMaster.GUI
{
/// <summary>
/// </summary>
public class ControllerWindow : System.Windows.Forms.Form
{
// the application controller
private Controller controller;
private String latestLine;
private bool newLineAvailable = false;
private ProfileManager manager;
public String Prompt = ":> ";
private List<string> commands = new List<string>(new string[] {""});
private int commandMarker = 0;
private System.Windows.Forms.MainMenu mainMenu1;
private System.Windows.Forms.MenuItem menuItem2;
private System.Windows.Forms.MenuItem menuItem3;
private System.Windows.Forms.MenuItem menuItem5;
private System.Windows.Forms.MenuItem menuItem6;
private System.ComponentModel.IContainer components;
private System.Windows.Forms.StatusBar statusBar1;
private NationalInstruments.UI.XAxis pmtXAxis;
private System.Windows.Forms.MenuItem menuItem7;
private System.Windows.Forms.MenuItem menuItem12;
private System.Windows.Forms.MenuItem menuItem13;
private System.Windows.Forms.MenuItem menuItem14;
private System.Windows.Forms.Button renameButton;
private System.Windows.Forms.Label currentProfileLabel;
private System.Windows.Forms.TextBox commandTextBox;
private System.Windows.Forms.TextBox outputTextBox;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.Button deleteButton;
private System.Windows.Forms.Button cloneButton;
private System.Windows.Forms.Button newButton;
private System.Windows.Forms.Button selectButton;
private System.Windows.Forms.ListBox profileListBox;
private System.Windows.Forms.MenuItem viewerMenu;
private System.Windows.Forms.MenuItem fileMenu;
private System.Windows.Forms.MenuItem acquireMenu;
private System.Windows.Forms.MenuItem menuItem1;
private System.Windows.Forms.MenuItem menuItem4;
private System.Windows.Forms.MenuItem menuItem9;
private System.Windows.Forms.MenuItem schonMenu;
private System.Windows.Forms.MenuItem menuItem10;
private System.Windows.Forms.MenuItem menuItem11;
private System.Windows.Forms.MenuItem patternMenu;
private System.Windows.Forms.MenuItem menuItem8;
private System.Windows.Forms.MenuItem menuItem15;
public ControllerWindow(Controller controller)
{
this.controller = controller;
this.manager = controller.ProfileManager;
InitializeComponent();
// build the viewer menu
viewerMenu.MenuItems.Clear();
Hashtable viewers = controller.ViewerManager.Viewers;
foreach (DictionaryEntry de in viewers)
{
MenuItem item = new MenuItem(de.Key.ToString());
item.Click +=new EventHandler(viewerClicked);
viewerMenu.MenuItems.Add(item);
}
// build the Schon menu
foreach (DictionaryEntry de in DataFaker.FakeScans)
{
MenuItem item = new MenuItem(de.Key.ToString());
item.Click +=new EventHandler(schonClicked);
schonMenu.MenuItems.Add(item);
}
}
protected override void Dispose( bool disposing )
{
if( disposing )
{
if (components != null)
{
components.Dispose();
}
}
base.Dispose( disposing );
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(ControllerWindow));
this.mainMenu1 = new System.Windows.Forms.MainMenu(this.components);
this.fileMenu = new System.Windows.Forms.MenuItem();
this.menuItem13 = new System.Windows.Forms.MenuItem();
this.menuItem12 = new System.Windows.Forms.MenuItem();
this.menuItem9 = new System.Windows.Forms.MenuItem();
this.menuItem4 = new System.Windows.Forms.MenuItem();
this.menuItem14 = new System.Windows.Forms.MenuItem();
this.menuItem2 = new System.Windows.Forms.MenuItem();
this.menuItem7 = new System.Windows.Forms.MenuItem();
this.menuItem15 = new System.Windows.Forms.MenuItem();
this.menuItem3 = new System.Windows.Forms.MenuItem();
this.acquireMenu = new System.Windows.Forms.MenuItem();
this.menuItem5 = new System.Windows.Forms.MenuItem();
this.menuItem6 = new System.Windows.Forms.MenuItem();
this.viewerMenu = new System.Windows.Forms.MenuItem();
this.patternMenu = new System.Windows.Forms.MenuItem();
this.menuItem10 = new System.Windows.Forms.MenuItem();
this.menuItem11 = new System.Windows.Forms.MenuItem();
this.menuItem1 = new System.Windows.Forms.MenuItem();
this.menuItem8 = new System.Windows.Forms.MenuItem();
this.schonMenu = new System.Windows.Forms.MenuItem();
this.pmtXAxis = new NationalInstruments.UI.XAxis();
this.statusBar1 = new System.Windows.Forms.StatusBar();
this.renameButton = new System.Windows.Forms.Button();
this.currentProfileLabel = new System.Windows.Forms.Label();
this.commandTextBox = new System.Windows.Forms.TextBox();
this.outputTextBox = new System.Windows.Forms.TextBox();
this.label1 = new System.Windows.Forms.Label();
this.deleteButton = new System.Windows.Forms.Button();
this.cloneButton = new System.Windows.Forms.Button();
this.newButton = new System.Windows.Forms.Button();
this.selectButton = new System.Windows.Forms.Button();
this.profileListBox = new System.Windows.Forms.ListBox();
this.SuspendLayout();
//
// mainMenu1
//
this.mainMenu1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.fileMenu,
this.acquireMenu,
this.viewerMenu,
this.patternMenu,
this.menuItem1,
this.schonMenu});
//
// fileMenu
//
this.fileMenu.Index = 0;
this.fileMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem13,
this.menuItem12,
this.menuItem9,
this.menuItem4,
this.menuItem14,
this.menuItem2,
this.menuItem7,
this.menuItem15,
this.menuItem3});
this.fileMenu.Text = "File";
//
// menuItem13
//
this.menuItem13.Index = 0;
this.menuItem13.Text = "Load profile set ...";
this.menuItem13.Click += new System.EventHandler(this.LoadProfileSetHandler);
//
// menuItem12
//
this.menuItem12.Index = 1;
this.menuItem12.Text = "Save profile set ...";
this.menuItem12.Click += new System.EventHandler(this.SaveProfileSetHandler);
//
// menuItem9
//
this.menuItem9.Index = 2;
this.menuItem9.Text = "-";
//
// menuItem4
//
this.menuItem4.Index = 3;
this.menuItem4.Text = "Load average data ...";
this.menuItem4.Click += new System.EventHandler(this.LoadDataHandler);
//
// menuItem14
//
this.menuItem14.Index = 4;
this.menuItem14.Text = "-";
//
// menuItem2
//
this.menuItem2.Index = 5;
this.menuItem2.Text = "Save scan data ...";
this.menuItem2.Click += new System.EventHandler(this.SaveDataHandler);
//
// menuItem7
//
this.menuItem7.Index = 6;
this.menuItem7.Shortcut = System.Windows.Forms.Shortcut.CtrlS;
this.menuItem7.Text = "Save average data ...";
this.menuItem7.Click += new System.EventHandler(this.SaveAverageDataHandler);
//
// menuItem15
//
this.menuItem15.Index = 7;
this.menuItem15.Text = "-";
//
// menuItem3
//
this.menuItem3.Index = 8;
this.menuItem3.Text = "Exit";
this.menuItem3.Click += new System.EventHandler(this.MenuExitClicked);
//
// acquireMenu
//
this.acquireMenu.Index = 1;
this.acquireMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem5,
this.menuItem6});
this.acquireMenu.Text = "Acquire";
//
// menuItem5
//
this.menuItem5.Index = 0;
this.menuItem5.Shortcut = System.Windows.Forms.Shortcut.CtrlG;
this.menuItem5.Text = "Start";
this.menuItem5.Click += new System.EventHandler(this.AcquireStartClicked);
//
// menuItem6
//
this.menuItem6.Index = 1;
this.menuItem6.Shortcut = System.Windows.Forms.Shortcut.CtrlC;
this.menuItem6.Text = "Stop";
this.menuItem6.Click += new System.EventHandler(this.AcquireStopClicked);
//
// viewerMenu
//
this.viewerMenu.Index = 2;
this.viewerMenu.Text = "Viewers";
//
// patternMenu
//
this.patternMenu.Index = 3;
this.patternMenu.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem10,
this.menuItem11});
this.patternMenu.Text = "Pattern";
//
// menuItem10
//
this.menuItem10.Index = 0;
this.menuItem10.Shortcut = System.Windows.Forms.Shortcut.CtrlF;
this.menuItem10.Text = "Start pattern output";
this.menuItem10.Click += new System.EventHandler(this.menuItem10_Click);
//
// menuItem11
//
this.menuItem11.Index = 1;
this.menuItem11.Shortcut = System.Windows.Forms.Shortcut.CtrlX;
this.menuItem11.Text = "Stop pattern output";
this.menuItem11.Click += new System.EventHandler(this.menuItem11_Click);
//
// menuItem1
//
this.menuItem1.Index = 4;
this.menuItem1.MenuItems.AddRange(new System.Windows.Forms.MenuItem[] {
this.menuItem8});
this.menuItem1.Text = "Debug";
this.menuItem1.Visible = false;
//
// menuItem8
//
this.menuItem8.Index = 0;
this.menuItem8.Text = "Test interlock";
this.menuItem8.Click += new System.EventHandler(this.menuItem8_Click);
//
// schonMenu
//
this.schonMenu.Index = 5;
this.schonMenu.Text = "Schon\'s menu";
//
// pmtXAxis
//
this.pmtXAxis.Mode = NationalInstruments.UI.AxisMode.Fixed;
//
// statusBar1
//
this.statusBar1.Location = new System.Drawing.Point(0, 644);
this.statusBar1.Name = "statusBar1";
this.statusBar1.Size = new System.Drawing.Size(1260, 32);
this.statusBar1.SizingGrip = false;
this.statusBar1.TabIndex = 13;
this.statusBar1.Text = "Ready";
//
// renameButton
//
this.renameButton.Location = new System.Drawing.Point(154, 550);
this.renameButton.Name = "renameButton";
this.renameButton.Size = new System.Drawing.Size(120, 33);
this.renameButton.TabIndex = 23;
this.renameButton.Text = "Rename ...";
this.renameButton.Click += new System.EventHandler(this.RenameHandler);
//
// currentProfileLabel
//
this.currentProfileLabel.Location = new System.Drawing.Point(13, 456);
this.currentProfileLabel.Name = "currentProfileLabel";
this.currentProfileLabel.Size = new System.Drawing.Size(371, 35);
this.currentProfileLabel.TabIndex = 22;
this.currentProfileLabel.Text = "Current profile: ";
//
// commandTextBox
//
this.commandTextBox.BackColor = System.Drawing.Color.Black;
this.commandTextBox.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.commandTextBox.ForeColor = System.Drawing.Color.Red;
this.commandTextBox.Location = new System.Drawing.Point(448, 550);
this.commandTextBox.Name = "commandTextBox";
this.commandTextBox.Size = new System.Drawing.Size(781, 30);
this.commandTextBox.TabIndex = 20;
this.commandTextBox.TextChanged += new System.EventHandler(this.commandTextBox_TextChanged);
this.commandTextBox.KeyUp += new System.Windows.Forms.KeyEventHandler(this.KeyUpHandler);
//
// outputTextBox
//
this.outputTextBox.BackColor = System.Drawing.Color.Black;
this.outputTextBox.Cursor = System.Windows.Forms.Cursors.Arrow;
this.outputTextBox.Font = new System.Drawing.Font("Courier New", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.outputTextBox.ForeColor = System.Drawing.Color.Lime;
this.outputTextBox.Location = new System.Drawing.Point(448, 47);
this.outputTextBox.Multiline = true;
this.outputTextBox.Name = "outputTextBox";
this.outputTextBox.ReadOnly = true;
this.outputTextBox.ScrollBars = System.Windows.Forms.ScrollBars.Vertical;
this.outputTextBox.Size = new System.Drawing.Size(781, 491);
this.outputTextBox.TabIndex = 21;
//
// label1
//
this.label1.Location = new System.Drawing.Point(13, 12);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(160, 35);
this.label1.TabIndex = 19;
this.label1.Text = "Profiles:";
//
// deleteButton
//
this.deleteButton.Location = new System.Drawing.Point(13, 550);
this.deleteButton.Name = "deleteButton";
this.deleteButton.Size = new System.Drawing.Size(120, 33);
this.deleteButton.TabIndex = 18;
this.deleteButton.Text = "Delete";
this.deleteButton.Click += new System.EventHandler(this.DeleteHandler);
//
// cloneButton
//
this.cloneButton.Location = new System.Drawing.Point(294, 503);
this.cloneButton.Name = "cloneButton";
this.cloneButton.Size = new System.Drawing.Size(120, 33);
this.cloneButton.TabIndex = 17;
this.cloneButton.Text = "Clone";
this.cloneButton.Click += new System.EventHandler(this.CloneHandler);
//
// newButton
//
this.newButton.Location = new System.Drawing.Point(154, 503);
this.newButton.Name = "newButton";
this.newButton.Size = new System.Drawing.Size(120, 33);
this.newButton.TabIndex = 16;
this.newButton.Text = "New";
this.newButton.Click += new System.EventHandler(this.NewProfileHandler);
//
// selectButton
//
this.selectButton.Location = new System.Drawing.Point(13, 503);
this.selectButton.Name = "selectButton";
this.selectButton.Size = new System.Drawing.Size(120, 33);
this.selectButton.TabIndex = 15;
this.selectButton.Text = "Select";
this.selectButton.Click += new System.EventHandler(this.SelectProfileHandler);
//
// profileListBox
//
this.profileListBox.ItemHeight = 20;
this.profileListBox.Location = new System.Drawing.Point(13, 47);
this.profileListBox.Name = "profileListBox";
this.profileListBox.Size = new System.Drawing.Size(371, 384);
this.profileListBox.TabIndex = 14;
this.profileListBox.DoubleClick += new System.EventHandler(this.SelectProfileHandler);
//
// ControllerWindow
//
this.AutoScaleBaseSize = new System.Drawing.Size(8, 19);
this.ClientSize = new System.Drawing.Size(1260, 676);
this.Controls.Add(this.renameButton);
this.Controls.Add(this.currentProfileLabel);
this.Controls.Add(this.commandTextBox);
this.Controls.Add(this.outputTextBox);
this.Controls.Add(this.label1);
this.Controls.Add(this.deleteButton);
this.Controls.Add(this.cloneButton);
this.Controls.Add(this.newButton);
this.Controls.Add(this.selectButton);
this.Controls.Add(this.profileListBox);
this.Controls.Add(this.statusBar1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.MaximizeBox = false;
this.Menu = this.mainMenu1;
this.Name = "ControllerWindow";
this.Text = "ScanMaster 2k8";
this.Closing += new System.ComponentModel.CancelEventHandler(this.ControllerWindow_Closing);
this.Load += new System.EventHandler(this.ControllerWindow_Load);
this.ResumeLayout(false);
this.PerformLayout();
}
#endregion
private void AcquireStartClicked(object sender, System.EventArgs e)
{
controller.AcquireStart(-1);
}
private void AcquireStopClicked(object sender, System.EventArgs e)
{
controller.AcquireStop();
}
private void MenuExitClicked(object sender, System.EventArgs e)
{
Close();
}
private void SaveDataHandler(object sender, System.EventArgs e)
{
controller.SaveData();
}
private void SaveAverageDataHandler(object sender, System.EventArgs e)
{
controller.SaveAverageData();
}
private void LoadProfileSetHandler(object sender, System.EventArgs e)
{
controller.LoadProfileSet();
}
private void SaveProfileSetHandler(object sender, System.EventArgs e)
{
controller.SaveProfileSet();
}
private void ControllerWindow_Closing(object sender, System.ComponentModel.CancelEventArgs e)
{
controller.StopApplication();
}
private void KeyUpHandler(object sender, System.Windows.Forms.KeyEventArgs e)
{
// if enter is pressed we should process the command
if (e.KeyData == Keys.Enter)
{
String command = commandTextBox.Text;
commands.Add(command);
commandMarker = commands.Count;
commandTextBox.Clear();
// echo the command
WriteLine(Prompt + command);
lock(this)
{
latestLine = command;
newLineAvailable = true;
}
}
// if up is pressed return the previous command in the list in the usual way
if (e.KeyData == Keys.Up)
{
commandMarker--;
if (commandMarker<0) commandMarker = 0;
commandTextBox.Clear();
commandTextBox.Text= commands[commandMarker];
commandTextBox.Select(commandTextBox.Text.Length,0);
}
// if down is pressed return the next command in the usual way
if (e.KeyData == Keys.Down)
{
commandMarker++;
if (commandMarker > commands.Count) commandMarker = commands.Count;
commandTextBox.Clear();
if (commandMarker == commands.Count)
{
}
else
{
commandTextBox.Text = commands[commandMarker];
commandTextBox.Select(commandTextBox.Text.Length, 0);
}
}
// tab attempts to autocomplete the command
if (e.KeyData == Keys.Tab)
{
String[] suggestions = manager.Processor.GetCommandSuggestions(commandTextBox.Text);
if (suggestions == null) return;
if (suggestions.Length == 1)
{
commandTextBox.Text = suggestions[0] + " ";
commandTextBox.SelectionStart = commandTextBox.Text.Length;
return;
}
StringBuilder sb = new StringBuilder();
foreach (String s in suggestions) sb.Append(s + "\t");
sb.Append(Environment.NewLine);
WriteLine(sb.ToString());
}
// escape clears the current text
if (e.KeyData == Keys.Escape) commandTextBox.Clear();
}
// this method disables the annoying thunk noise when enter, tab, escape are pressed !
protected override bool ProcessDialogKey(System.Windows.Forms.Keys keyData)
{
if(keyData == Keys.Enter) return true;
if(keyData == Keys.Tab) return true;
if(keyData == Keys.Escape) return true;
return false;
}
private delegate void AppendTextDelegate(String text);
public void WriteLine(String text)
{
outputTextBox.BeginInvoke(new AppendTextDelegate(outputTextBox.AppendText),
new object[] {text + Environment.NewLine});
}
public String GetNextLine()
{
for (;;)
{
lock(this)
{
if (newLineAvailable)
{
newLineAvailable = false;
String returnLine = latestLine;
latestLine = null;
return returnLine;
}
}
Thread.Sleep(20);
}
}
private void SelectProfileHandler(object sender, System.EventArgs e)
{
if (profileListBox.SelectedIndex == -1) return;
else
{
manager.SelectProfile(profileListBox.SelectedIndex);
}
}
private void NewProfileHandler(object sender, System.EventArgs e)
{
manager.AddNewProfile();
UpdateUI();
}
private void CloneHandler(object sender, System.EventArgs e)
{
if (profileListBox.SelectedIndex == -1) return;
else
{
manager.CloneProfile(profileListBox.SelectedIndex);
UpdateUI();
}
}
private void DeleteHandler(object sender, System.EventArgs e)
{
if (profileListBox.SelectedIndex == -1) return;
else
{
manager.DeleteProfile(profileListBox.SelectedIndex);
UpdateUI();
}
}
private void RenameHandler(object sender, System.EventArgs e)
{
if (profileListBox.SelectedIndex == -1) return;
else
{
ProfileRenameDialog dialog = new ProfileRenameDialog();
Profile selectedProfile = ((Profile)manager.Profiles[profileListBox.SelectedIndex]);
dialog.ProfileName = selectedProfile.Name;
if (dialog.ShowDialog() == DialogResult.OK)
{
selectedProfile.Name = dialog.ProfileName;
UpdateUI();
}
}
}
public void UpdateUI()
{
profileListBox.Invoke(new UpdateDelegate(ReallyUpdateUI), null);
}
private delegate void UpdateDelegate();
private void ReallyUpdateUI()
{
profileListBox.Items.Clear();
if (manager.Profiles.Count != 0)
{
foreach (Profile p in manager.Profiles) profileListBox.Items.Add(p.Name);
if (manager.CurrentProfile == null) currentProfileLabel.Text = "Current profile: ";
else currentProfileLabel.Text = "Current profile: " + manager.CurrentProfile.Name;
}
else
{
// this works around a bug in visual studio/winforms!
profileListBox.Items.Add("Dummy profile (do not select!)");
}
}
public void DisableMenus()
{
fileMenu.Enabled = false;
acquireMenu.Enabled = false;
// viewerMenu.Enabled = false;
schonMenu.Enabled = false;
// patternMenu.Enabled = false;
}
public void EnableMenus()
{
fileMenu.Enabled = true;
acquireMenu.Enabled = true;
// viewerMenu.Enabled = true;
schonMenu.Enabled = true;
// patternMenu.Enabled = true;
}
public System.Drawing.Color OutputColor
{
set
{
outputTextBox.ForeColor = value;
}
}
private void viewerClicked(object sender, EventArgs e)
{
MenuItem item = (MenuItem)sender;
((Viewer)Controller.GetController().ViewerManager.Viewers[item.Text]).ToggleVisible();
}
private void schonClicked(object sender, EventArgs e)
{
MenuItem item = (MenuItem)sender;
Controller.GetController().LoadData(DataFaker.GetFakeDataPath(item.Text));
}
private void LoadDataHandler(object sender, System.EventArgs e)
{
Controller.GetController().LoadData();
}
private void menuItem10_Click(object sender, System.EventArgs e)
{
Controller.GetController().OutputPattern();
}
private void menuItem11_Click(object sender, System.EventArgs e)
{
Controller.GetController().StopPatternOutput();
}
private void menuItem8_Click(object sender, System.EventArgs e)
{
DAQ.HAL.BrilliantLaser laser = ((DAQ.HAL.BrilliantLaser)DAQ.Environment.Environs.Hardware.YAG);
// laser.Connect();
bool test = laser.InterlockFailed;
// laser.Disconnect();
}
private void ControllerWindow_Load(object sender, EventArgs e)
{
UpdateUI();
}
// thread-safe wrapper for setting window title.
public void SetWindowTitle(string text)
{
BeginInvoke(new SetTextDelegate(SetWindowTitleInternal), new object[] { text });
}
private delegate void SetTextDelegate(string text);
private void SetWindowTitleInternal(string text)
{
Text = text;
}
private void commandTextBox_TextChanged(object sender, EventArgs e)
{
}
}
}
| |
//
// Reaktion - An audio reactive animation toolkit for Unity.
//
// Copyright (C) 2013, 2014 Keijiro Takahashi
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
//
#if UNITY_STANDALONE_OSX && UNITY_PRO_LICENSE
#define ENABLE_NATIVE_PLUGIN
#endif
using UnityEngine;
using System.Runtime.InteropServices;
namespace Reaktion {
public static class Perlin
{
#if !ENABLE_NATIVE_PLUGIN
//
// Based on the original implementation by Ken Perlin
// http://mrl.nyu.edu/~perlin/noise/
//
#region Noise functions
public static float Noise (float x)
{
var X = Mathf.FloorToInt (x) & 0xff;
x -= Mathf.Floor (x);
return Lerp (Fade (x), Grad(X, x), Grad (X + 1, x - 1));
}
public static float Noise (float x, float y)
{
var X = Mathf.FloorToInt (x) & 0xff;
var Y = Mathf.FloorToInt (y) & 0xff;
x -= Mathf.Floor (x);
y -= Mathf.Floor (y);
var u = Fade (x);
var v = Fade (y);
var A = (perm [X ] + Y) & 0xff;
var B = (perm [X + 1] + Y) & 0xff;
return Lerp (v, Lerp (u, Grad (A , x, y ), Grad (B, x - 1, y )),
Lerp (u, Grad (A + 1, x, y - 1), Grad (B + 1, x - 1, y - 1)));
}
public static float Noise (Vector2 coord)
{
return Noise (coord.x, coord.y);
}
public static float Noise (float x, float y, float z)
{
var X = Mathf.FloorToInt (x) & 0xff;
var Y = Mathf.FloorToInt (y) & 0xff;
var Z = Mathf.FloorToInt (z) & 0xff;
x -= Mathf.Floor (x);
y -= Mathf.Floor (y);
z -= Mathf.Floor (z);
var u = Fade (x);
var v = Fade (y);
var w = Fade (z);
var A = (perm [X ] + Y) & 0xff;
var B = (perm [X + 1] + Y) & 0xff;
var AA = (perm [A ] + Z) & 0xff;
var BA = (perm [B ] + Z) & 0xff;
var AB = (perm [A + 1] + Z) & 0xff;
var BB = (perm [B + 1] + Z) & 0xff;
return Lerp (w, Lerp (v, Lerp (u, Grad (AA , x , y , z ), Grad (BA , x - 1, y , z )),
Lerp (u, Grad (AB , x , y - 1, z ), Grad (BB , x - 1, y - 1, z ))),
Lerp (v, Lerp (u, Grad (AA + 1, x , y , z - 1), Grad (BA + 1, x - 1, y , z - 1)),
Lerp (u, Grad (AB + 1, x , y - 1, z - 1), Grad (BB + 1, x - 1, y - 1, z - 1))));
}
public static float Noise (Vector3 coord)
{
return Noise (coord.x, coord.y, coord.z);
}
#endregion
#region fBm functions
public static float Fbm (float x, int octave)
{
var f = 0.0f;
var w = 0.5f;
for (var i = 0; i < octave; i++) {
f += w * Noise (x);
x *= 2.0f;
w *= 0.5f;
}
return f;
}
public static float Fbm (Vector2 coord, int octave)
{
var f = 0.0f;
var w = 0.5f;
for (var i = 0; i < octave; i++) {
f += w * Noise (coord);
coord *= 2.0f;
w *= 0.5f;
}
return f;
}
public static float Fbm (Vector3 coord, int octave)
{
var f = 0.0f;
var w = 0.5f;
for (var i = 0; i < octave; i++) {
f += w * Noise (coord);
coord *= 2.0f;
w *= 0.5f;
}
return f;
}
#endregion
#region Private functions
static float Fade (float t)
{
return t * t * t * (t * (t * 6 - 15) + 10);
}
static float Lerp (float t, float a, float b)
{
return a + t * (b - a);
}
static float Grad (int i, float x)
{
return (perm [i] & 1) != 0 ? x : -x;
}
static float Grad (int i, float x, float y)
{
var h = perm [i];
return ((h & 1) != 0 ? x : -x) + ((h & 2) != 0 ? y : -y);
}
static float Grad (int i, float x, float y, float z)
{
var h = perm [i] & 15;
var u = h < 8 ? x : y;
var v = h < 4 ? y : (h == 12 || h == 14 ? x : z);
return ((h & 1) != 0 ? u : -u) + ((h & 2) != 0 ? v : -v);
}
static int[] perm = {
151,160,137,91,90,15,
131,13,201,95,96,53,194,233,7,225,140,36,103,30,69,142,8,99,37,240,21,10,23,
190, 6,148,247,120,234,75,0,26,197,62,94,252,219,203,117,35,11,32,57,177,33,
88,237,149,56,87,174,20,125,136,171,168, 68,175,74,165,71,134,139,48,27,166,
77,146,158,231,83,111,229,122,60,211,133,230,220,105,92,41,55,46,245,40,244,
102,143,54, 65,25,63,161, 1,216,80,73,209,76,132,187,208, 89,18,169,200,196,
135,130,116,188,159,86,164,100,109,198,173,186, 3,64,52,217,226,250,124,123,
5,202,38,147,118,126,255,82,85,212,207,206,59,227,47,16,58,17,182,189,28,42,
223,183,170,213,119,248,152, 2,44,154,163, 70,221,153,101,155,167, 43,172,9,
129,22,39,253, 19,98,108,110,79,113,224,232,178,185, 112,104,218,246,97,228,
251,34,242,193,238,210,144,12,191,179,162,241, 81,51,145,235,249,14,239,107,
49,192,214, 31,181,199,106,157,184, 84,204,176,115,121,50,45,127, 4,150,254,
138,236,205,93,222,114,67,29,24,72,243,141,128,195,78,66,215,61,156,180,
151
};
#endregion
#else // ENABLE_NATIVE_PLUGIN
//
// The native implementation.
//
#region Noise functions
public static float Noise (float x)
{
return KvantNoise1D (x);
}
public static float Noise (float x, float y)
{
return KvantNoise2D (x, y);
}
public static float Noise (Vector2 coord)
{
return KvantNoise2D (coord.x, coord.y);
}
public static float Noise (float x, float y, float z)
{
return KvantNoise3D (x, y, z);
}
public static float Noise (Vector3 coord)
{
return KvantNoise3D (coord.x, coord.y, coord.z);
}
#endregion
#region Fractal functions
public static float Fbm (float x, int octave)
{
return KvantFBM1D (x, octave);
}
public static float Fbm (Vector2 coord, int octave)
{
return KvantFBM2D (coord.x, coord.y, octave);
}
public static float Fbm (Vector3 coord, int octave)
{
return KvantFBM3D (coord.x, coord.y, coord.z, octave);
}
#endregion
#region Native plug-in interface
[DllImport ("Kvant")]
private static extern float KvantNoise1D (float x);
[DllImport ("Kvant")]
private static extern float KvantNoise2D (float x, float y);
[DllImport ("Kvant")]
private static extern float KvantNoise3D (float x, float y, float z);
[DllImport ("Kvant")]
private static extern float KvantFBM1D (float x, int octave);
[DllImport ("Kvant")]
private static extern float KvantFBM2D (float x, float y, int octave);
[DllImport ("Kvant")]
private static extern float KvantFBM3D (float x, float y, float z, int octave);
#endregion
#endif // ENABLE_NATIVE_PLUGIN
}
} // namespace Reaktion
| |
using System;
using System.Collections;
using System.Data;
using PCSComUtils.PCSExc;
using PCSComUtils.Common;
using PCSComUtils.Framework.TableFrame.DS;
namespace PCSComUtils.Framework.TableFrame.BO
{
public class TableManagementBO
{
private const string THIS = "PCSComUtils.Framework.TableFrame.BO.ITableManagementBO";
const string COPY_OF = "copy of ";
public TableManagementBO()
{
}
/// <Description>
/// This method checks business rule and call Add() method of DS class
/// </Description>
/// <Inputs>
/// Value object
/// </Inputs>
/// <Outputs>
/// N/A
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Add(object pobjObjectVO)
{
try
{
sys_TableAndGroupDS templateDS = new sys_TableAndGroupDS();
templateDS.Add(pobjObjectVO);
}
catch(PCSDBException ex)
{
throw ex;
}
}
public object GetTableInfo(int pintTableID)
{
try
{
sys_TableDS dssys_TableDS = new sys_TableDS();
return dssys_TableDS.GetObjectVO(pintTableID);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
public object GetGroupInfo(int pintGroupID)
{
try
{
sys_TableGroupDS dssys_TableGroupDS = new sys_TableGroupDS();
return dssys_TableGroupDS.GetObjectVO(pintGroupID);
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw new Exception(ex.Message, ex);
}
}
//**************************************************************************
/// <Description>
/// This method not implements yet
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID,string VOclass)
{
const string METHOD_NAME = THIS + ".GetObjectVO()";
throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME,new Exception());
}
//**************************************************************************
/// <Description>
/// This method not implements yet
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
///
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(object pObjectVO)
{
const string METHOD_NAME = THIS + ".Delete()";
throw new PCSException(ErrorCode.NOT_IMPLEMENT, METHOD_NAME,new Exception());
}
//**************************************************************************
/// <Description>
/// This method checks business rule and call Delete() method of DS class
/// </Description>
/// <Inputs>
/// pintID
/// </Inputs>
/// <Outputs>
/// Delete a record from Database
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Delete(int pintID)
{
try
{
sys_TableAndGroupDS templateDS = new sys_TableAndGroupDS();
templateDS.Delete(pintID);
}
catch(PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to get data
/// </Description>
/// <Inputs>
/// pintID
/// </Inputs>
/// <Outputs>
/// Value object
/// </Outputs>
/// <Returns>
/// object
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public object GetObjectVO(int pintID)
{
try
{
sys_TableAndGroupDS templateDS = new sys_TableAndGroupDS();
return templateDS.GetObjectVO(pintID);
}
catch(PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to update data
/// </Description>
/// <Inputs>
/// pobjObjecVO
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void Update(object pobjObjecVO)
{
try
{
sys_TableAndGroupDS templateDS = new sys_TableAndGroupDS();
templateDS.Update(pobjObjecVO);
}
catch(PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all data
/// </Description>
/// <Inputs>
///
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// DataSet
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
///
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public DataSet List()
{
try
{
sys_TableAndGroupDS templateDS = new sys_TableAndGroupDS();
return templateDS.List();
}
catch(PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to update a DataSet
/// </Description>
/// <Inputs>
/// DataSet
/// </Inputs>
/// <Outputs>
/// N/A
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// HungLa
/// </Authors>
/// <History>
/// 13-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void UpdateDataSet(DataSet pData)
{
try
{
sys_TableAndGroupDS templateDS = new sys_TableAndGroupDS();
templateDS.UpdateDataSet(pData);
}
catch(PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all row in sys_table
/// </Description>
/// <Inputs>
/// N/A
/// </Inputs>
/// <Outputs>
/// object sys_TableVO
/// </Outputs>
/// <Returns>
/// ArrayList
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 27-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public ArrayList GetAllTable()
{
const string METHOD_NAME = "GetAllTable()";
sys_TableDS dsSysTable = new sys_TableDS();
sys_TableVO objTableVO;
ArrayList arr = new ArrayList();
DataSet dset = new DataSet();
try
{
dset = dsSysTable.List();
}
catch (PCSDBException ex)
{
throw ex;
}
try
{
if (dset.Tables[0] != null)
{
foreach (DataRow row in dset.Tables[0].Rows)
{
objTableVO = new sys_TableVO();
objTableVO.TableID = int.Parse(row[sys_TableTable.TABLEID_FLD].ToString());
objTableVO.Code = row[sys_TableTable.CODE_FLD].ToString().Trim();
objTableVO.TableName = row[sys_TableTable.TABLENAME_FLD].ToString().Trim();
objTableVO.TableOrView = row[sys_TableTable.TABLEORVIEW_FLD].ToString().Trim();
objTableVO.Height = int.Parse(row[sys_TableTable.HEIGHT_FLD].ToString());
objTableVO.IsViewOnly = bool.Parse(row[sys_TableTable.ISVIEWONLY_FLD].ToString());
//insert into array
arr.Add(objTableVO);
}
}
else
arr = null;
return arr;
}
catch (Exception ex)
{
throw new PCSBOException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
}
//**************************************************************************
/// <Description>
/// This method uses to get all row in sys_tableandgroup
/// </Description>
/// <Inputs>
/// N/A
/// </Inputs>
/// <Outputs>
/// object sys_TableandGroupVO
/// </Outputs>
/// <Returns>
/// ArrayList
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 27-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public ArrayList GetAllTableAndGroup()
{
const string METHOD_NAME = "GetAllTableAndGroup()";
sys_TableAndGroupDS objAnd = new sys_TableAndGroupDS();
sys_TableAndGroupVO objAndVO;
ArrayList arr = new ArrayList();
try
{
DataSet dset = new DataSet();
dset = objAnd.List();
foreach (DataRow row in dset.Tables[0].Rows)
{
objAndVO = new sys_TableAndGroupVO();
objAndVO.TableAndGroupID = int.Parse(row["TableAndGroupId"].ToString());
objAndVO.TableGroupID = int.Parse(row["TableGroupID"].ToString());
objAndVO.TableID = int.Parse(row["TableID"].ToString());
objAndVO.TableOrder = int.Parse(row["TableOrder"].ToString());
//add into array
arr.Add(objAndVO);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
return arr;
}
//**************************************************************************
/// <Description>
/// This method uses to get all row in sys_tablegroup
/// </Description>
/// <Inputs>
/// N/A
/// </Inputs>
/// <Outputs>
/// object sys_TableGroupVO
/// </Outputs>
/// <Returns>
/// ArrayList
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 27-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public ArrayList GetAllGroup()
{
const string METHOD_NAME = "GetAllGroup()";
sys_TableGroupDS dsSysTableGroup = new sys_TableGroupDS();
sys_TableGroupVO voSysTableGroup;
ArrayList arr = new ArrayList();
try
{
DataSet dset = new DataSet();
dset = dsSysTableGroup.List();
foreach (DataRow row in dset.Tables[0].Rows)
{
voSysTableGroup = new sys_TableGroupVO();
voSysTableGroup.TableGroupID = int.Parse(row[sys_TableGroupTable.TABLEGROUPID_FLD].ToString());
voSysTableGroup.Code = row[sys_TableGroupTable.CODE_FLD].ToString().Trim();
voSysTableGroup.TableGroupName = row[sys_TableGroupTable.TABLEGROUPNAME_FLD].ToString().Trim();
voSysTableGroup.GroupOrder = int.Parse(row[sys_TableGroupTable.GROUPORDER_FLD].ToString());
// add object sys_TableGroupVO into array
arr.Add(voSysTableGroup);
}
}
catch (Exception ex)
{
throw new PCSDBException(ErrorCode.OTHER_ERROR, METHOD_NAME, ex);
}
return arr;
}
//**************************************************************************
/// <Description>
/// This method uses to delete a row in sys_table
/// </Description>
/// <Inputs>
/// TableID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
/// dataset
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 28-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void DeleteTable(int pintTableID)
{
try
{
sys_TableDS dsSysTable = new sys_TableDS();
sys_TableAndGroupDS dsTableAndGroup = new sys_TableAndGroupDS();
dsTableAndGroup.Delete(pintTableID);
dsSysTable.Delete(pintTableID);
}
catch (Exception ex)
{
throw (ex);
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete a row in sys_table
/// </Description>
/// <Inputs>
/// TableID
/// </Inputs>
/// <Outputs>
/// void
/// </Outputs>
/// <Returns>
/// dataset
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 28-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void DeleteTable(int pintTableID,int pintTableGroupID)
{
try
{
sys_TableAndGroupDS objsys_TableAndGroupDS = new sys_TableAndGroupDS();
sys_TableFieldDS objsys_TableFieldDS = new sys_TableFieldDS();
sys_TableDS dsSysTable = new sys_TableDS();
//first check to see if this TableID is in another group
int intNoOfTableInGroup = objsys_TableAndGroupDS.CountTableInGroup(pintTableID);
//First delete the Sys_TableAndGroup
if (intNoOfTableInGroup > 1)
{
objsys_TableAndGroupDS.DeleteTableAndGroup(pintTableID,pintTableGroupID);
}
else
{
objsys_TableAndGroupDS.Delete(pintTableID);
//objsys_TableAndGroupDS.DeleteTableAndGroup(pintTableID,pintTableGroupID);
//Second delete the Table Field
objsys_TableFieldDS.DeleteTable(pintTableID);
//the last is used to delete the sys_TableDS
//sys_TableAndGroupDS dsTableAndGroup = new sys_TableAndGroupDS();
dsSysTable.Delete(pintTableID);
}
}
catch (Exception ex)
{
throw (ex);
}
}
//**************************************************************************
/// <Description>
/// This method uses to copy total tables inside the specified tablegroup
/// </Description>
/// <Inputs>
/// GroupID
/// </Inputs>
/// <Outputs>
/// sys_tablegroup and sys_table
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 28-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void CopyGroup(int pintGroupID)
{
try
{ //copy old object in tablegroup and add it into database
sys_TableGroupDS dsSysTableGroup = new sys_TableGroupDS();
//create object to contain the current TableGroup row
sys_TableGroupVO voOldTableGroup = new sys_TableGroupVO();
voOldTableGroup = (sys_TableGroupVO)dsSysTableGroup.GetObjectVO(pintGroupID);
//create new object which will be copiedobject
sys_TableGroupVO voNewTableGroup = new sys_TableGroupVO();
voNewTableGroup.Code = COPY_OF + voOldTableGroup.Code;
voNewTableGroup.TableGroupName = COPY_OF + voOldTableGroup.TableGroupName;
voNewTableGroup.GroupOrder = dsSysTableGroup.MaxGroupOrder() + 1;
int intNewGroupID = dsSysTableGroup.AddGroupAndReturnID(voNewTableGroup);
//Copy from all tables from old group to a new group
//initialize the sys_TableAndGroupDs
sys_TableAndGroupDS objSys_TableAndGroupDS = new sys_TableAndGroupDS();
objSys_TableAndGroupDS.CopyTwoGroup(pintGroupID,intNewGroupID);
//dsSysTableGroup.Add(voNewTableGroup);
//return groupid for new tablegroup row
/*
int intGroupID = dsSysTableGroup.MaxGroupID();
sys_TableDS dsSysTable = new sys_TableDS();
sys_TableAndGroupDS dsTableAndGroup = new sys_TableAndGroupDS();
DataSet sysAndDSET = new DataSet();
sysAndDSET = dsTableAndGroup.List();
int nTableOrder = dsSysTable.MaxTableOrder(intGroupID);
foreach (DataRow r in sysAndDSET.Tables[0].Rows)
{
if (r["TableGroupID"].Equals(pintGroupID))
{
//get back tableid of copied table
int intTableID = int.Parse(r["TableID"].ToString());
//get back old row in sysTable
sys_TableVO oldTableVO = new sys_TableVO();
oldTableVO = (sys_TableVO)dsSysTable.GetObjectVO(intTableID);
//create new row in sysTable which will be a copied row
sys_TableVO voSysTable = new sys_TableVO();
voSysTable.Code = COPY_OF + oldTableVO.Code;
voSysTable.TableName = COPY_OF + oldTableVO.TableName;
voSysTable.TableOrView = oldTableVO.TableOrView;
voSysTable.Height = oldTableVO.Height;
//insert new row into sysTable
dsSysTable.Add(voSysTable);
int intNewTableID = dsSysTable.MaxTableID();
//create new row in sysTableAndGroup which will be a copied row
sys_TableAndGroupVO voTableAndGroup = new sys_TableAndGroupVO();
voTableAndGroup.TableGroupID = intGroupID;
voTableAndGroup.TableID = intNewTableID;
voTableAndGroup.TableOrder = ++nTableOrder;
//insert new row into sysTableAndGroup
dsTableAndGroup.Add(voTableAndGroup);
}
}
*/
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to copy total tables inside the specified tablegroup
/// </Description>
/// <Inputs>
/// GroupID
/// </Inputs>
/// <Outputs>
/// sys_tablegroup and sys_table
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 28-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int CopyGroupAndReturnMaxID(int pintGroupID)
{
try
{ //copy old object in tablegroup and add it into database
sys_TableGroupDS dsSysTableGroup = new sys_TableGroupDS();
//create object to contain the current TableGroup row
sys_TableGroupVO voOldTableGroup = new sys_TableGroupVO();
voOldTableGroup = (sys_TableGroupVO)dsSysTableGroup.GetObjectVO(pintGroupID);
//create new object which will be copiedobject
sys_TableGroupVO voNewTableGroup = new sys_TableGroupVO();
voNewTableGroup.Code = COPY_OF + voOldTableGroup.Code;
voNewTableGroup.TableGroupName = COPY_OF + voOldTableGroup.TableGroupName;
voNewTableGroup.GroupOrder = dsSysTableGroup.MaxGroupOrder() + 1;
int intNewGroupID = dsSysTableGroup.AddGroupAndReturnID(voNewTableGroup);
//Copy from all tables from old group to a new group
//initialize the sys_TableAndGroupDs
sys_TableAndGroupDS objSys_TableAndGroupDS = new sys_TableAndGroupDS();
objSys_TableAndGroupDS.CopyTwoGroup(pintGroupID,intNewGroupID);
return intNewGroupID;
//dsSysTableGroup.Add(voNewTableGroup);
//return groupid for new tablegroup row
/*
int intGroupID = dsSysTableGroup.MaxGroupID();
sys_TableDS dsSysTable = new sys_TableDS();
sys_TableAndGroupDS dsTableAndGroup = new sys_TableAndGroupDS();
DataSet sysAndDSET = new DataSet();
sysAndDSET = dsTableAndGroup.List();
int nTableOrder = dsSysTable.MaxTableOrder(intGroupID);
foreach (DataRow r in sysAndDSET.Tables[0].Rows)
{
if (r["TableGroupID"].Equals(pintGroupID))
{
//get back tableid of copied table
int intTableID = int.Parse(r["TableID"].ToString());
//get back old row in sysTable
sys_TableVO oldTableVO = new sys_TableVO();
oldTableVO = (sys_TableVO)dsSysTable.GetObjectVO(intTableID);
//create new row in sysTable which will be a copied row
sys_TableVO voSysTable = new sys_TableVO();
voSysTable.Code = COPY_OF + oldTableVO.Code;
voSysTable.TableName = COPY_OF + oldTableVO.TableName;
voSysTable.TableOrView = oldTableVO.TableOrView;
voSysTable.Height = oldTableVO.Height;
//insert new row into sysTable
dsSysTable.Add(voSysTable);
int intNewTableID = dsSysTable.MaxTableID();
//create new row in sysTableAndGroup which will be a copied row
sys_TableAndGroupVO voTableAndGroup = new sys_TableAndGroupVO();
voTableAndGroup.TableGroupID = intGroupID;
voTableAndGroup.TableID = intNewTableID;
voTableAndGroup.TableOrder = ++nTableOrder;
//insert new row into sysTableAndGroup
dsTableAndGroup.Add(voTableAndGroup);
}
}
*/
}
catch (PCSDBException ex)
{
throw ex;
}
catch (Exception ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to delete a row in sys_tablegroup
/// </Description>
/// <Inputs>
/// GroupID
/// </Inputs>
/// <Outputs>
/// N/A
/// </Outputs>
/// <Returns>
/// void
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 28-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void DeleteGroup(int pintGroupID)
{
try
{
sys_TableAndGroupDS dsTableAndGroup = new sys_TableAndGroupDS();
sys_TableDS dsSysTable = new sys_TableDS();
DataSet dset = new DataSet();
dset = dsTableAndGroup.List();
DataTable dtable = dset.Tables[0];
foreach (DataRow row in dtable.Rows)
{
if (row[sys_TableAndGroupTable.TABLEGROUPID_FLD].Equals(pintGroupID))
{
int intTableID = int.Parse(row[sys_TableAndGroupTable.TABLEID_FLD].ToString());
dsTableAndGroup.Delete(intTableID);
dsSysTable.Delete(intTableID);
}
}
sys_TableGroupDS dsSysTableGroup = new sys_TableGroupDS();
dsSysTableGroup.Delete(pintGroupID);
}
catch (PCSDBException ex)
{
throw ex;
}
}
//**************************************************************************
/// <Description>
/// This method uses to change up order of a row in sys_table
/// </Description>
/// <Inputs>
/// TableID
/// </Inputs>
/// <Outputs>
/// changes
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 29-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int MoveUpTable(int pintTableID)
{
int intTableOrder = 0;
try
{
sys_TableAndGroupDS dsTableAndGroup = new sys_TableAndGroupDS();
sys_TableDS dsSysTable = new sys_TableDS();
sys_TableAndGroupVO objAndVOPre = new sys_TableAndGroupVO();
sys_TableAndGroupVO objAndVOCur = new sys_TableAndGroupVO();
ArrayList arrobjAnd = new ArrayList();
int intGroupID = dsTableAndGroup.GetGroupIDByTableID(pintTableID);
arrobjAnd = dsTableAndGroup.GetObjectVOs(intGroupID);
for (int i = 0; i < arrobjAnd.Count; i++)
{
sys_TableAndGroupVO obj = (sys_TableAndGroupVO)arrobjAnd[i];
if (obj.TableID == pintTableID)
{
int mCurTableOrder = obj.TableOrder;
if (mCurTableOrder > 1)
{
objAndVOPre = (sys_TableAndGroupVO)arrobjAnd[i-1];
objAndVOCur = (sys_TableAndGroupVO)arrobjAnd[i];
objAndVOCur.TableOrder = objAndVOPre.TableOrder;
objAndVOPre.TableOrder = mCurTableOrder;
intTableOrder = objAndVOPre.TableOrder;
//update two rows into database
dsTableAndGroup.Update(objAndVOPre);
dsTableAndGroup.Update(objAndVOCur);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return intTableOrder;
}
//**************************************************************************
/// <Description>
/// This method uses to change up order of a row in sys_table
/// </Description>
/// <Inputs>
/// TableID
/// </Inputs>
/// <Outputs>
/// changes
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 29-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int MoveUpTable(int pintTableID, int pintTableGroupID)
{
int intTableOrder = 0;
try
{
sys_TableAndGroupDS dsTableAndGroup = new sys_TableAndGroupDS();
sys_TableDS dsSysTable = new sys_TableDS();
sys_TableAndGroupVO objAndVOPre = new sys_TableAndGroupVO();
sys_TableAndGroupVO objAndVOCur = new sys_TableAndGroupVO();
ArrayList arrobjAnd = new ArrayList();
int intGroupID = pintTableGroupID ; // dsTableAndGroup.GetGroupIDByTableID(pintTableID);
arrobjAnd = dsTableAndGroup.GetObjectVOs(intGroupID);
for (int i = 0; i < arrobjAnd.Count; i++)
{
sys_TableAndGroupVO obj = (sys_TableAndGroupVO)arrobjAnd[i];
if (obj.TableID == pintTableID)
{
int mCurTableOrder = obj.TableOrder;
if (mCurTableOrder > 1)
{
objAndVOPre = (sys_TableAndGroupVO)arrobjAnd[i-1];
objAndVOCur = (sys_TableAndGroupVO)arrobjAnd[i];
objAndVOCur.TableOrder = objAndVOPre.TableOrder;
objAndVOPre.TableOrder = mCurTableOrder;
intTableOrder = objAndVOPre.TableOrder;
//update two rows into database
dsTableAndGroup.Update(objAndVOPre);
dsTableAndGroup.Update(objAndVOCur);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return intTableOrder;
}
//**************************************************************************
/// <Description>
/// This method uses to change down of a row in sys_table
/// </Description>
/// <Inputs>
/// TableID
/// </Inputs>
/// <Outputs>
/// changes
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 29-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int MoveDownTable(int pintTableID)
{
int intTableOrder = 0;
try
{
sys_TableAndGroupDS dsTableAndGroup = new sys_TableAndGroupDS();
sys_TableDS dsSysTable = new sys_TableDS();
sys_TableAndGroupVO objAndVONex = new sys_TableAndGroupVO();
sys_TableAndGroupVO objAndVOCur = new sys_TableAndGroupVO();
ArrayList arrobjAnd = new ArrayList();
int intGroupID = dsTableAndGroup.GetGroupIDByTableID(pintTableID);
arrobjAnd = dsTableAndGroup.GetObjectVOs(intGroupID);
int intNum = arrobjAnd.Count;
for (int i = 0; i < intNum; i++)
{
sys_TableAndGroupVO obj = (sys_TableAndGroupVO)arrobjAnd[i];
if (obj.TableID == pintTableID)
{
int mCurTableOrder = obj.TableOrder;
if (mCurTableOrder < intNum)
{
objAndVONex = (sys_TableAndGroupVO)arrobjAnd[i+1];
objAndVOCur = (sys_TableAndGroupVO)arrobjAnd[i];
objAndVOCur.TableOrder = objAndVONex.TableOrder;
objAndVONex.TableOrder = mCurTableOrder;
intTableOrder = objAndVONex.TableOrder;
//update two rows into database
dsTableAndGroup.Update(objAndVONex);
dsTableAndGroup.Update(objAndVOCur);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return intTableOrder;
}
//**************************************************************************
/// <Description>
/// This method uses to change down of a row in sys_table
/// </Description>
/// <Inputs>
/// TableID
/// </Inputs>
/// <Outputs>
/// changes
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 29-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int MoveDownTable(int pintTableID, int pintTableGroupID)
{
int intTableOrder = 0;
try
{
sys_TableAndGroupDS dsTableAndGroup = new sys_TableAndGroupDS();
sys_TableDS dsSysTable = new sys_TableDS();
sys_TableAndGroupVO objAndVONex = new sys_TableAndGroupVO();
sys_TableAndGroupVO objAndVOCur = new sys_TableAndGroupVO();
ArrayList arrobjAnd = new ArrayList();
int intGroupID = pintTableGroupID ; //dsTableAndGroup.GetGroupIDByTableID(pintTableID);
arrobjAnd = dsTableAndGroup.GetObjectVOs(intGroupID);
int intNum = arrobjAnd.Count;
for (int i = 0; i < intNum; i++)
{
sys_TableAndGroupVO obj = (sys_TableAndGroupVO)arrobjAnd[i];
if (obj.TableID == pintTableID)
{
int mCurTableOrder = obj.TableOrder;
if (mCurTableOrder < intNum)
{
objAndVONex = (sys_TableAndGroupVO)arrobjAnd[i+1];
objAndVOCur = (sys_TableAndGroupVO)arrobjAnd[i];
objAndVOCur.TableOrder = objAndVONex.TableOrder;
objAndVONex.TableOrder = mCurTableOrder;
intTableOrder = objAndVONex.TableOrder;
//update two rows into database
dsTableAndGroup.Update(objAndVONex);
dsTableAndGroup.Update(objAndVOCur);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return intTableOrder;
}
//**************************************************************************
/// <Description>
/// This method uses to change up order of TableGroup
/// </Description>
/// <Inputs>
/// GroupID
/// </Inputs>
/// <Outputs>
/// changes
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 29-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int MoveUpGroup(int pintGroupID)
{
int intGroupOrder = 0;
try
{
sys_TableGroupDS dsSysTableGroup = new sys_TableGroupDS();
sys_TableGroupVO voSysTableGroupPre = new sys_TableGroupVO();
sys_TableGroupVO voSysTableGroupCur = new sys_TableGroupVO();
ArrayList arrobjGroup = new ArrayList();
arrobjGroup = dsSysTableGroup.GetObjectVOs();
for (int i = 0; i < arrobjGroup.Count; i++)
{
sys_TableGroupVO voSysTableGroup = (sys_TableGroupVO)arrobjGroup[i];
int intGroupID = voSysTableGroup.TableGroupID;
if (intGroupID.Equals(pintGroupID))
{
int intCurGroupOrder = voSysTableGroup.GroupOrder;
if (intCurGroupOrder > 1)
{
voSysTableGroupPre = (sys_TableGroupVO)arrobjGroup[i-1];
voSysTableGroupCur = (sys_TableGroupVO)arrobjGroup[i];
voSysTableGroupCur.GroupOrder = voSysTableGroupPre.GroupOrder;
voSysTableGroupPre.GroupOrder = intCurGroupOrder;
intGroupOrder = voSysTableGroupPre.GroupOrder;
//update two rows into database
dsSysTableGroup.Update(voSysTableGroupPre);
dsSysTableGroup.Update(voSysTableGroupCur);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return intGroupOrder;
}
//**************************************************************************
/// <Description>
/// This method uses to change down order of TableGroup
/// </Description>
/// <Inputs>
/// GroupID
/// </Inputs>
/// <Outputs>
/// changes
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 29-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int MoveDownGroup(int pintGroupID)
{
int intGroupOrder = 0;
try
{
sys_TableGroupDS dsSysTableGroup = new sys_TableGroupDS();
sys_TableGroupVO voSysTableGroupNex = new sys_TableGroupVO();
sys_TableGroupVO voSysTableGroupCur = new sys_TableGroupVO();
ArrayList arrobjGroup = new ArrayList();
arrobjGroup = dsSysTableGroup.GetObjectVOs();
int intNum = arrobjGroup.Count;
for (int i = 0; i < intNum; i++)
{
sys_TableGroupVO voSysTableGroup = (sys_TableGroupVO)arrobjGroup[i];
int intGroupID = voSysTableGroup.TableGroupID;
if (intGroupID.Equals(pintGroupID))
{
int intCurGroupOrder = voSysTableGroup.GroupOrder;
if (intCurGroupOrder < intNum)
{
voSysTableGroupNex = (sys_TableGroupVO)arrobjGroup[i+1];
voSysTableGroupCur = (sys_TableGroupVO)arrobjGroup[i];
voSysTableGroupCur.GroupOrder = voSysTableGroupNex.GroupOrder;
voSysTableGroupNex.GroupOrder = intCurGroupOrder;
intGroupOrder = voSysTableGroupNex.GroupOrder;
//update two rows into database
dsSysTableGroup.Update(voSysTableGroupNex);
dsSysTableGroup.Update(voSysTableGroupCur);
}
}
}
}
catch (Exception ex)
{
throw (ex);
}
return intGroupOrder;
}
//**************************************************************************
/// <Description>
/// This method uses to check order of Table
/// </Description>
/// <Inputs>
/// GroupID,TableID
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 30-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void TablePosition(int pintGroupID,int pintTableOrder,ref bool blnMin,ref bool blnMax)
{
sys_TableDS dsSysTable = new sys_TableDS();
int intMaxTableOrder = dsSysTable.MaxTableOrder(pintGroupID);
int intMinTableOrder = dsSysTable.MinTableOrder(pintGroupID);
if ((pintTableOrder < intMaxTableOrder)&&(pintTableOrder > intMinTableOrder))
{
blnMin = false;
blnMax = false;
}
else if (pintTableOrder.Equals(intMinTableOrder))
blnMin = true;
else if (pintTableOrder.Equals(intMaxTableOrder))
blnMax = true;
}
//**************************************************************************
/// <Description>
/// This method uses to check order of TableGroup
/// </Description>
/// <Inputs>
/// GroupID
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 30-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void GroupPosition(int pintGroupOrder,ref bool blnMin,ref bool blnMax)
{
sys_TableGroupDS dsSysTableGroup = new sys_TableGroupDS();
int intMaxGroupOrder = dsSysTableGroup.MaxGroupOrder();
int intMinGroupOrder = dsSysTableGroup.MinGroupOrder();
if ((pintGroupOrder < intMaxGroupOrder)&&(pintGroupOrder > intMinGroupOrder))
{
blnMin = false;
blnMax = false;
}
else if (pintGroupOrder.Equals(intMinGroupOrder))
blnMin = true;
else if (pintGroupOrder.Equals(intMaxGroupOrder))
blnMax = true;
}
//**************************************************************************
/// <Description>
/// This method uses to get the position of a table in a specific group
/// </Description>
/// <Inputs>
/// GroupID,TableID
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 30-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public int GetTablePositionInGroup(int pintGroupID,int pintTableId)
{
try
{
sys_TableAndGroupDS objSysTableAndGroupDS = new sys_TableAndGroupDS();
return objSysTableAndGroupDS.GetTablePositionInGroup(pintGroupID,pintTableId);
}
catch (PCSDBException ex)
{
throw ex;
}
}
#region ITableManagementBO Members
//**************************************************************************
/// <Description>
/// This method uses to copy a table into a specific group
/// </Description>
/// <Inputs>
/// GroupID,TableID
/// </Inputs>
/// <Outputs>
///
/// </Outputs>
/// <Returns>
/// bool
/// </Returns>
/// <Authors>
/// NgocHT
/// </Authors>
/// <History>
/// 30-Dec-2004
/// </History>
/// <Notes>
/// </Notes>
//**************************************************************************
public void CopyTable(int pintTableId, int pintGroupID)
{
// TODO: Add TableManagementBO.CopyTable implementation
const string METHOD_NAME = THIS + ".CopyTable()";
try
{
//Check to see if this table is already existed in this group
//Initialize the DS class
sys_TableAndGroupDS objSys_TableAndGroupDS = new sys_TableAndGroupDS();
if (objSys_TableAndGroupDS.CheckIfTableExisted(pintTableId,pintGroupID))
{
throw new PCSBOException(ErrorCode.MESSAGE_TABLEMANAGEMENT_DUPLICATE_TABLE,METHOD_NAME,null);
}
//Initialize the VO class
sys_TableAndGroupVO objSysTableAndGroupVO = new sys_TableAndGroupVO();
objSysTableAndGroupVO.TableGroupID = pintGroupID;
objSysTableAndGroupVO.TableID = pintTableId;
objSysTableAndGroupVO.TableOrder = objSys_TableAndGroupDS.GetMaxTableOrder(pintGroupID);
//Save this record into database
objSys_TableAndGroupDS.Add(objSysTableAndGroupVO);
}catch (PCSBOException ex)
{
throw ex;
}
catch (PCSDBException ex)
{
throw ex.CauseException;
}
catch (Exception ex)
{
throw ex;
}
}
#endregion
}
}
| |
#if DEBUG
#define STATS_ENABLED
#endif
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using LiteNetLib.Utils;
namespace LiteNetLib
{
public sealed class NetManager
{
internal delegate void OnMessageReceived(byte[] data, int length, int errorCode, NetEndPoint remoteEndPoint);
private struct FlowMode
{
public int PacketsPerSecond;
public int StartRtt;
}
private enum NetEventType
{
Connect,
Disconnect,
Receive,
ReceiveUnconnected,
Error,
ConnectionLatencyUpdated,
DiscoveryRequest,
DiscoveryResponse
}
private sealed class NetEvent
{
public NetPeer Peer;
public NetDataReader DataReader;
public NetEventType Type;
public NetEndPoint RemoteEndPoint;
public int AdditionalData;
public DisconnectReason DisconnectReason;
}
#if DEBUG
private struct IncomingData
{
public byte[] Data;
public NetEndPoint EndPoint;
public DateTime TimeWhenGet;
}
private readonly List<IncomingData> _pingSimulationList = new List<IncomingData>();
private readonly Random _randomGenerator = new Random();
private const int MinLatencyTreshold = 5;
#endif
private readonly NetSocket _socket;
private readonly List<FlowMode> _flowModes;
private readonly NetThread _logicThread;
private readonly Queue<NetEvent> _netEventsQueue;
private readonly Stack<NetEvent> _netEventsPool;
private readonly INetEventListener _netEventListener;
private readonly Dictionary<NetEndPoint, NetPeer> _peers;
private readonly int _maxConnections;
private readonly Queue<NetEndPoint> _peersToRemove;
private readonly string _connectKey;
//config section
public bool UnconnectedMessagesEnabled = false;
public bool NatPunchEnabled = false;
public int UpdateTime { get { return _logicThread.SleepTime; } set { _logicThread.SleepTime = value; } }
public int ReliableResendTime = 500;
public int PingInterval = NetConstants.DefaultPingInterval;
public long DisconnectTimeout = 5000;
public bool SimulatePacketLoss = false;
public bool SimulateLatency = false;
public int SimulationPacketLossChance = 10;
public int SimulationMinLatency = 30;
public int SimulationMaxLatency = 100;
public bool UnsyncedEvents = false;
public bool DiscoveryEnabled = false;
public bool MergeEnabled = false;
public int ReconnectDelay = 500;
public int MaxConnectAttempts = 10;
private const int DefaultUpdateTime = 15;
//stats
public ulong PacketsSent { get; private set; }
public ulong PacketsReceived { get; private set; }
public ulong BytesSent { get; private set; }
public ulong BytesReceived { get; private set; }
//modules
public readonly NatPunchModule NatPunchModule;
/// <summary>
/// Returns true if socket listening and update thread is running
/// </summary>
public bool IsRunning
{
get { return _logicThread.IsRunning; }
}
/// <summary>
/// Local EndPoint (host and port)
/// </summary>
public NetEndPoint LocalEndPoint
{
get { return _socket.LocalEndPoint; }
}
/// <summary>
/// Connected peers count
/// </summary>
public int PeersCount
{
get { return _peers.Count; }
}
public string ConnectKey
{
get { return _connectKey; }
}
//Flow
public void AddFlowMode(int startRtt, int packetsPerSecond)
{
var fm = new FlowMode {PacketsPerSecond = packetsPerSecond, StartRtt = startRtt};
if (_flowModes.Count > 0 && startRtt < _flowModes[0].StartRtt)
{
_flowModes.Insert(0, fm);
}
else
{
_flowModes.Add(fm);
}
}
internal int GetPacketsPerSecond(int flowMode)
{
if (flowMode < 0 || _flowModes.Count == 0)
return 0;
return _flowModes[flowMode].PacketsPerSecond;
}
internal int GetMaxFlowMode()
{
return _flowModes.Count - 1;
}
internal int GetStartRtt(int flowMode)
{
if (flowMode < 0 || _flowModes.Count == 0)
return 0;
return _flowModes[flowMode].StartRtt;
}
/// <summary>
/// NetManager constructor with maxConnections = 1 (usable for client)
/// </summary>
/// <param name="listener">Network events listener</param>
/// <param name="connectKey">Application key (must be same with remote host for establish connection)</param>
public NetManager(INetEventListener listener, string connectKey) : this(listener, 1, connectKey)
{
}
/// <summary>
/// NetManager constructor
/// </summary>
/// <param name="listener">Network events listener</param>
/// <param name="maxConnections">Maximum connections (incoming and outcoming)</param>
/// <param name="connectKey">Application key (must be same with remote host for establish connection)</param>
public NetManager(INetEventListener listener, int maxConnections, string connectKey)
{
_logicThread = new NetThread("LogicThread", DefaultUpdateTime, UpdateLogic);
_socket = new NetSocket(ReceiveLogic);
_netEventListener = listener;
_flowModes = new List<FlowMode>();
_netEventsQueue = new Queue<NetEvent>();
_netEventsPool = new Stack<NetEvent>();
NatPunchModule = new NatPunchModule(this, _socket);
_connectKey = connectKey;
_peers = new Dictionary<NetEndPoint, NetPeer>();
_peersToRemove = new Queue<NetEndPoint>(maxConnections);
_maxConnections = maxConnections;
_connectKey = connectKey;
}
internal void ConnectionLatencyUpdated(NetPeer fromPeer, int latency)
{
var evt = CreateEvent(NetEventType.ConnectionLatencyUpdated);
evt.Peer = fromPeer;
evt.AdditionalData = latency;
EnqueueEvent(evt);
}
internal bool SendRaw(byte[] message, NetEndPoint remoteEndPoint)
{
return SendRaw(message, 0, message.Length, remoteEndPoint);
}
internal bool SendRaw(byte[] message, int start, int length, NetEndPoint remoteEndPoint)
{
if (!IsRunning)
return false;
int errorCode = 0;
bool result = _socket.SendTo(message, start, length, remoteEndPoint, ref errorCode) > 0;
//10040 message to long... need to check
//10065 no route to host
if (errorCode != 0 && errorCode != 10040 && errorCode != 10065)
{
//Send error
NetPeer fromPeer;
if (_peers.TryGetValue(remoteEndPoint, out fromPeer))
{
DisconnectPeer(fromPeer, DisconnectReason.SocketSendError, errorCode, false, null, 0, 0);
}
var netEvent = CreateEvent(NetEventType.Error);
netEvent.RemoteEndPoint = remoteEndPoint;
netEvent.AdditionalData = errorCode;
EnqueueEvent(netEvent);
return false;
}
if (errorCode == 10040)
{
NetUtils.DebugWrite(ConsoleColor.Red, "[SRD] 10040, datalen: {0}", length);
return false;
}
#if STATS_ENABLED
PacketsSent++;
BytesSent += (uint)length;
#endif
return result;
}
private void DisconnectPeer(
NetPeer peer,
DisconnectReason reason,
int socketErrorCode,
bool sendDisconnectPacket,
byte[] data,
int start,
int count)
{
if (sendDisconnectPacket)
{
if (count + 8 >= peer.Mtu)
{
//Drop additional data
data = null;
count = 0;
NetUtils.DebugWriteError("Disconnect additional data size more than MTU - 8!");
}
var disconnectPacket = NetPacket.CreateRawPacket(PacketProperty.Disconnect, 8 + count);
FastBitConverter.GetBytes(disconnectPacket, 1, peer.ConnectId);
if (data != null)
{
Buffer.BlockCopy(data, start, disconnectPacket, 9, count);
}
SendRaw(disconnectPacket, peer.EndPoint);
}
var netEvent = CreateEvent(NetEventType.Disconnect);
netEvent.Peer = peer;
netEvent.AdditionalData = socketErrorCode;
netEvent.DisconnectReason = reason;
EnqueueEvent(netEvent);
lock (_peersToRemove)
{
_peersToRemove.Enqueue(peer.EndPoint);
}
}
private void ClearPeers()
{
lock (_peers)
{
#if WINRT && !UNITY_EDITOR
_socket.ClearPeers();
#endif
_peers.Clear();
}
}
private NetEvent CreateEvent(NetEventType type)
{
NetEvent evt = null;
lock (_netEventsPool)
{
if (_netEventsPool.Count > 0)
{
evt = _netEventsPool.Pop();
}
}
if(evt == null)
{
evt = new NetEvent {DataReader = new NetDataReader()};
}
evt.Type = type;
return evt;
}
private void EnqueueEvent(NetEvent evt)
{
if (UnsyncedEvents)
{
ProcessEvent(evt);
}
else
{
lock (_netEventsQueue)
{
_netEventsQueue.Enqueue(evt);
}
}
}
private void ProcessEvent(NetEvent evt)
{
switch (evt.Type)
{
case NetEventType.Connect:
_netEventListener.OnPeerConnected(evt.Peer);
break;
case NetEventType.Disconnect:
var info = new DisconnectInfo
{
Reason = evt.DisconnectReason,
AdditionalData = evt.DataReader,
SocketErrorCode = evt.AdditionalData
};
_netEventListener.OnPeerDisconnected(evt.Peer, info);
break;
case NetEventType.Receive:
_netEventListener.OnNetworkReceive(evt.Peer, evt.DataReader);
break;
case NetEventType.ReceiveUnconnected:
_netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.Default);
break;
case NetEventType.DiscoveryRequest:
_netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.DiscoveryRequest);
break;
case NetEventType.DiscoveryResponse:
_netEventListener.OnNetworkReceiveUnconnected(evt.RemoteEndPoint, evt.DataReader, UnconnectedMessageType.DiscoveryResponse);
break;
case NetEventType.Error:
_netEventListener.OnNetworkError(evt.RemoteEndPoint, evt.AdditionalData);
break;
case NetEventType.ConnectionLatencyUpdated:
_netEventListener.OnNetworkLatencyUpdate(evt.Peer, evt.AdditionalData);
break;
}
//Recycle
evt.DataReader.Clear();
evt.Peer = null;
evt.AdditionalData = 0;
evt.RemoteEndPoint = null;
lock (_netEventsPool)
{
_netEventsPool.Push(evt);
}
}
//Update function
private void UpdateLogic()
{
#if DEBUG
if (SimulateLatency)
{
var time = DateTime.UtcNow;
lock (_pingSimulationList)
{
for (int i = 0; i < _pingSimulationList.Count; i++)
{
var incomingData = _pingSimulationList[i];
if (incomingData.TimeWhenGet <= time)
{
DataReceived(incomingData.Data, incomingData.Data.Length, incomingData.EndPoint);
_pingSimulationList.RemoveAt(i);
i--;
}
}
}
}
#endif
//Process acks
lock (_peers)
{
int delta = _logicThread.SleepTime;
foreach (NetPeer netPeer in _peers.Values)
{
if (netPeer.ConnectionState == ConnectionState.Connected && netPeer.TimeSinceLastPacket > DisconnectTimeout)
{
netPeer.DebugWrite("Disconnect by timeout: {0} > {1}", netPeer.TimeSinceLastPacket, DisconnectTimeout);
var netEvent = CreateEvent(NetEventType.Disconnect);
netEvent.Peer = netPeer;
netEvent.DisconnectReason = DisconnectReason.Timeout;
EnqueueEvent(netEvent);
lock (_peersToRemove)
{
_peersToRemove.Enqueue(netPeer.EndPoint);
}
}
else if(netPeer.ConnectionState == ConnectionState.Disconnected)
{
var netEvent = CreateEvent(NetEventType.Disconnect);
netEvent.Peer = netPeer;
netEvent.DisconnectReason = DisconnectReason.ConnectionFailed;
EnqueueEvent(netEvent);
lock (_peersToRemove)
{
_peersToRemove.Enqueue(netPeer.EndPoint);
}
}
else
{
netPeer.Update(delta);
}
}
lock (_peersToRemove)
{
while (_peersToRemove.Count > 0)
{
var ep = _peersToRemove.Dequeue();
_peers.Remove(ep);
#if WINRT && !UNITY_EDITOR
_socket.RemovePeer(ep);
#endif
}
}
}
}
private void ReceiveLogic(byte[] data, int length, int errorCode, NetEndPoint remoteEndPoint)
{
//Receive some info
if (errorCode == 0)
{
#if DEBUG
bool receivePacket = true;
if (SimulatePacketLoss && _randomGenerator.Next(100/SimulationPacketLossChance) == 0)
{
receivePacket = false;
}
else if (SimulateLatency)
{
int latency = _randomGenerator.Next(SimulationMinLatency, SimulationMaxLatency);
if (latency > MinLatencyTreshold)
{
byte[] holdedData = new byte[length];
Buffer.BlockCopy(data, 0, holdedData, 0, length);
lock (_pingSimulationList)
{
_pingSimulationList.Add(new IncomingData
{
Data = holdedData,
EndPoint = remoteEndPoint,
TimeWhenGet = DateTime.UtcNow.AddMilliseconds(latency)
});
}
receivePacket = false;
}
}
if (receivePacket) //DataReceived
#endif
//ProcessEvents
DataReceived(data, length, remoteEndPoint);
}
else //Error on receive
{
ClearPeers();
var netEvent = CreateEvent(NetEventType.Error);
netEvent.AdditionalData = errorCode;
EnqueueEvent(netEvent);
}
}
private void DataReceived(byte[] reusableBuffer, int count, NetEndPoint remoteEndPoint)
{
#if STATS_ENABLED
PacketsReceived++;
BytesReceived += (uint) count;
#endif
//Try get packet property
PacketProperty property;
if (!NetPacket.GetPacketProperty(reusableBuffer, out property))
return;
//Check unconnected
switch (property)
{
case PacketProperty.DiscoveryRequest:
if(DiscoveryEnabled)
{
var netEvent = CreateEvent(NetEventType.DiscoveryRequest);
netEvent.RemoteEndPoint = remoteEndPoint;
netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
EnqueueEvent(netEvent);
}
return;
case PacketProperty.DiscoveryResponse:
{
var netEvent = CreateEvent(NetEventType.DiscoveryResponse);
netEvent.RemoteEndPoint = remoteEndPoint;
netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
EnqueueEvent(netEvent);
}
return;
case PacketProperty.UnconnectedMessage:
if (UnconnectedMessagesEnabled)
{
var netEvent = CreateEvent(NetEventType.ReceiveUnconnected);
netEvent.RemoteEndPoint = remoteEndPoint;
netEvent.DataReader.SetSource(NetPacket.GetUnconnectedData(reusableBuffer, count));
EnqueueEvent(netEvent);
}
return;
case PacketProperty.NatIntroduction:
case PacketProperty.NatIntroductionRequest:
case PacketProperty.NatPunchMessage:
{
if (NatPunchEnabled)
NatPunchModule.ProcessMessage(remoteEndPoint, property, NetPacket.GetUnconnectedData(reusableBuffer, count));
return;
}
}
//Check normal packets
NetPacket packet;
NetPeer netPeer;
//Check peers
Monitor.Enter(_peers);
int peersCount = _peers.Count;
if (_peers.TryGetValue(remoteEndPoint, out netPeer))
{
Monitor.Exit(_peers);
packet = netPeer.GetPacketFromPool(init: false);
//Bad packet check
if (!packet.FromBytes(reusableBuffer, 0, count))
{
netPeer.Recycle(packet);
return;
}
//Send
if (packet.Property == PacketProperty.Disconnect)
{
if (BitConverter.ToInt64(packet.RawData, 1) != netPeer.ConnectId)
{
//Old or incorrect disconnect
netPeer.Recycle(packet);
return;
}
var netEvent = CreateEvent(NetEventType.Disconnect);
netEvent.Peer = netPeer;
netEvent.DataReader.SetSource(packet.RawData, 5, packet.RawData.Length - 5);
netEvent.DisconnectReason = DisconnectReason.RemoteConnectionClose;
EnqueueEvent(netEvent);
lock (_peersToRemove)
{
_peersToRemove.Enqueue(netPeer.EndPoint);
}
//do not recycle because no sense)
}
else if (packet.Property == PacketProperty.ConnectAccept)
{
if (netPeer.ProcessConnectAccept(packet))
{
var connectEvent = CreateEvent(NetEventType.Connect);
connectEvent.Peer = netPeer;
EnqueueEvent(connectEvent);
}
netPeer.Recycle(packet);
}
else
{
netPeer.ProcessPacket(packet);
}
return;
}
try
{
//Else add new peer
packet = new NetPacket();
if (!packet.FromBytes(reusableBuffer, 0, count))
{
//Bad packet
return;
}
if (peersCount < _maxConnections && packet.Property == PacketProperty.ConnectRequest)
{
int protoId = BitConverter.ToInt32(packet.RawData, 1);
if (protoId != NetConstants.ProtocolId)
{
NetUtils.DebugWrite(ConsoleColor.Cyan,
"[NS] Peer connect reject. Invalid protocol ID: " + protoId);
return;
}
string peerKey = Encoding.UTF8.GetString(packet.RawData, 13, packet.RawData.Length - 13);
if (peerKey != _connectKey)
{
NetUtils.DebugWrite(ConsoleColor.Cyan, "[NS] Peer connect reject. Invalid key: " + peerKey);
return;
}
//Getting new id for peer
long connectionId = BitConverter.ToInt64(packet.RawData, 5);
//response with id
NetUtils.DebugWrite(ConsoleColor.Cyan, "[NS] Received peer connect request Id: {0}, EP: {1}",
netPeer.ConnectId, remoteEndPoint);
netPeer = new NetPeer(this, remoteEndPoint, connectionId);
//clean incoming packet
netPeer.Recycle(packet);
_peers.Add(remoteEndPoint, netPeer);
var netEvent = CreateEvent(NetEventType.Connect);
netEvent.Peer = netPeer;
EnqueueEvent(netEvent);
}
}
finally
{
Monitor.Exit(_peers);
}
}
internal void ReceiveFromPeer(NetPacket packet, NetEndPoint remoteEndPoint)
{
NetPeer fromPeer;
if (_peers.TryGetValue(remoteEndPoint, out fromPeer))
{
NetUtils.DebugWrite(ConsoleColor.Cyan, "[NC] Received message");
var netEvent = CreateEvent(NetEventType.Receive);
netEvent.Peer = fromPeer;
netEvent.RemoteEndPoint = fromPeer.EndPoint;
netEvent.DataReader.SetSource(packet.GetPacketData());
EnqueueEvent(netEvent);
}
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="writer">DataWriter with data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
public void SendToAll(NetDataWriter writer, SendOptions options)
{
SendToAll(writer.Data, 0, writer.Length, options);
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="data">Data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
public void SendToAll(byte[] data, SendOptions options)
{
SendToAll(data, 0, data.Length, options);
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="data">Data</param>
/// <param name="start">Start of data</param>
/// <param name="length">Length of data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
public void SendToAll(byte[] data, int start, int length, SendOptions options)
{
lock (_peers)
{
foreach (NetPeer netPeer in _peers.Values)
{
netPeer.Send(data, start, length, options);
}
}
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="writer">DataWriter with data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
/// <param name="excludePeer">Excluded peer</param>
public void SendToAll(NetDataWriter writer, SendOptions options, NetPeer excludePeer)
{
SendToAll(writer.Data, 0, writer.Length, options, excludePeer);
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="data">Data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
/// <param name="excludePeer">Excluded peer</param>
public void SendToAll(byte[] data, SendOptions options, NetPeer excludePeer)
{
SendToAll(data, 0, data.Length, options, excludePeer);
}
/// <summary>
/// Send data to all connected peers
/// </summary>
/// <param name="data">Data</param>
/// <param name="start">Start of data</param>
/// <param name="length">Length of data</param>
/// <param name="options">Send options (reliable, unreliable, etc.)</param>
/// <param name="excludePeer">Excluded peer</param>
public void SendToAll(byte[] data, int start, int length, SendOptions options, NetPeer excludePeer)
{
lock (_peers)
{
foreach (NetPeer netPeer in _peers.Values)
{
if (netPeer != excludePeer)
{
netPeer.Send(data, start, length, options);
}
}
}
}
/// <summary>
/// Start logic thread and listening on available port
/// </summary>
public bool Start()
{
return Start(0);
}
/// <summary>
/// Start logic thread and listening on selected port
/// </summary>
/// <param name="port">port to listen</param>
public bool Start(int port)
{
if (IsRunning)
{
return false;
}
_netEventsQueue.Clear();
if (!_socket.Bind(port))
return false;
_logicThread.Start();
return true;
}
/// <summary>
/// Send message without connection
/// </summary>
/// <param name="message">Raw data</param>
/// <param name="remoteEndPoint">Packet destination</param>
/// <returns>Operation result</returns>
public bool SendUnconnectedMessage(byte[] message, NetEndPoint remoteEndPoint)
{
return SendUnconnectedMessage(message, 0, message.Length, remoteEndPoint);
}
/// <summary>
/// Send message without connection
/// </summary>
/// <param name="writer">Data serializer</param>
/// <param name="remoteEndPoint">Packet destination</param>
/// <returns>Operation result</returns>
public bool SendUnconnectedMessage(NetDataWriter writer, NetEndPoint remoteEndPoint)
{
return SendUnconnectedMessage(writer.Data, 0, writer.Length, remoteEndPoint);
}
/// <summary>
/// Send message without connection
/// </summary>
/// <param name="message">Raw data</param>
/// <param name="start">data start</param>
/// <param name="length">data length</param>
/// <param name="remoteEndPoint">Packet destination</param>
/// <returns>Operation result</returns>
public bool SendUnconnectedMessage(byte[] message, int start, int length, NetEndPoint remoteEndPoint)
{
if (!IsRunning)
return false;
var packet = NetPacket.CreateRawPacket(PacketProperty.UnconnectedMessage, message, start, length);
return SendRaw(packet, remoteEndPoint);
}
public bool SendDiscoveryRequest(NetDataWriter writer, int port)
{
return SendDiscoveryRequest(writer.Data, 0, writer.Length, port);
}
public bool SendDiscoveryRequest(byte[] data, int port)
{
return SendDiscoveryRequest(data, 0, data.Length, port);
}
public bool SendDiscoveryRequest(byte[] data, int start, int length, int port)
{
if (!IsRunning)
return false;
var packet = NetPacket.CreateRawPacket(PacketProperty.DiscoveryRequest, data, start, length);
return _socket.SendBroadcast(packet, 0, packet.Length, port);
}
public bool SendDiscoveryResponse(NetDataWriter writer, NetEndPoint remoteEndPoint)
{
return SendDiscoveryResponse(writer.Data, 0, writer.Length, remoteEndPoint);
}
public bool SendDiscoveryResponse(byte[] data, NetEndPoint remoteEndPoint)
{
return SendDiscoveryResponse(data, 0, data.Length, remoteEndPoint);
}
public bool SendDiscoveryResponse(byte[] data, int start, int length, NetEndPoint remoteEndPoint)
{
if (!IsRunning)
return false;
var packet = NetPacket.CreateRawPacket(PacketProperty.DiscoveryResponse, data, start, length);
return SendRaw(packet, remoteEndPoint);
}
/// <summary>
/// Receive all pending events. Call this in game update code
/// </summary>
public void PollEvents()
{
if (UnsyncedEvents)
return;
while (_netEventsQueue.Count > 0)
{
NetEvent evt;
lock (_netEventsQueue)
{
evt = _netEventsQueue.Dequeue();
}
ProcessEvent(evt);
}
}
/// <summary>
/// Connect to remote host
/// </summary>
/// <param name="address">Server IP or hostname</param>
/// <param name="port">Server Port</param>
public void Connect(string address, int port)
{
//Create target endpoint
NetEndPoint ep = new NetEndPoint(address, port);
Connect(ep);
}
/// <summary>
/// Connect to remote host
/// </summary>
/// <param name="target">Server end point (ip and port)</param>
public void Connect(NetEndPoint target)
{
if (!IsRunning)
{
throw new Exception("Client is not running");
}
lock (_peers)
{
if (_peers.ContainsKey(target) || _peers.Count >= _maxConnections)
{
//Already connected
return;
}
//Create reliable connection
//And request connection
var newPeer = new NetPeer(this, target, 0);
_peers.Add(target, newPeer);
}
}
/// <summary>
/// Force closes connection and stop all threads.
/// </summary>
public void Stop()
{
//Send disconnect packets
lock (_peers)
foreach (NetPeer netPeer in _peers.Values)
{
var disconnectPacket = NetPacket.CreateRawPacket(PacketProperty.Disconnect, 8);
FastBitConverter.GetBytes(disconnectPacket, 1, netPeer.ConnectId);
SendRaw(disconnectPacket, netPeer.EndPoint);
}
//Clear
ClearPeers();
//Stop
if (IsRunning)
{
_logicThread.Stop();
_socket.Close();
}
}
/// <summary>
/// Get first peer. Usefull for Client mode
/// </summary>
/// <returns></returns>
public NetPeer GetFirstPeer()
{
lock (_peers)
{
using (var enumerator = _peers.Values.GetEnumerator())
{
if (enumerator.MoveNext())
return enumerator.Current;
}
}
return null;
}
/// <summary>
/// Get copy of current connected peers
/// </summary>
/// <returns>Array with connected peers</returns>
public NetPeer[] GetPeers()
{
NetPeer[] peers;
int num = 0;
lock (_peers)
{
peers = new NetPeer[_peers.Count];
foreach (NetPeer netPeer in _peers.Values)
{
peers[num++] = netPeer;
}
}
return peers;
}
/// <summary>
/// Get copy of current connected peers (without allocations)
/// </summary>
/// <param name="peers">List that will contain result</param>
public void GetPeersNonAlloc(List<NetPeer> peers)
{
peers.Clear();
lock (_peers)
{
foreach (NetPeer netPeer in _peers.Values)
{
peers.Add(netPeer);
}
}
}
/// <summary>
/// Disconnect peer from server
/// </summary>
/// <param name="peer">peer to disconnect</param>
public void DisconnectPeer(NetPeer peer)
{
DisconnectPeer(peer, null, 0, 0);
}
/// <summary>
/// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8)
/// </summary>
/// <param name="peer">peer to disconnect</param>
/// <param name="data">additional data</param>
public void DisconnectPeer(NetPeer peer, byte[] data)
{
DisconnectPeer(peer, data, 0, data.Length);
}
/// <summary>
/// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8)
/// </summary>
/// <param name="peer">peer to disconnect</param>
/// <param name="writer">additional data</param>
public void DisconnectPeer(NetPeer peer, NetDataWriter writer)
{
DisconnectPeer(peer, writer.Data, 0, writer.Length);
}
/// <summary>
/// Disconnect peer from server and send additional data (Size must be less or equal MTU - 8)
/// </summary>
/// <param name="peer">peer to disconnect</param>
/// <param name="data">additional data</param>
/// <param name="start">data start</param>
/// <param name="count">data length</param>
public void DisconnectPeer(NetPeer peer, byte[] data, int start, int count)
{
if (peer != null && _peers.ContainsKey(peer.EndPoint))
{
DisconnectPeer(peer, DisconnectReason.DisconnectPeerCalled, 0, true, data, start, count);
}
}
}
}
| |
// CRC32.cs - Computes CRC32 data checksum of a data stream
// Copyright (C) 2001 Mike Krueger
//
// This file was translated from java, it was part of the GNU Classpath
// Copyright (C) 1999, 2000, 2001 Free Software Foundation, Inc.
//
// 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.
//
// Linking this library statically or dynamically with other modules is
// making a combined work based on this library. Thus, the terms and
// conditions of the GNU General Public License cover the whole
// combination.
//
// As a special exception, the copyright holders of this library give you
// permission to link this library with independent modules to produce an
// executable, regardless of the license terms of these independent
// modules, and to copy and distribute the resulting executable under
// terms of your choice, provided that you also meet, for each linked
// independent module, the terms and conditions of the license of that
// module. An independent module is a module which is not derived from
// or based on this library. If you modify this library, you may extend
// this exception to your version of the library, but you are not
// obligated to do so. If you do not wish to do so, delete this
// exception statement from your version.
// *************************************************************************
//
// Name: Crc32.cs
//
// Created: 19-02-2008 SharedCache.com, rschuetz
// Modified: 19-02-2008 SharedCache.com, rschuetz : Creation
// *************************************************************************
using System;
using System.Collections.Generic;
using System.Text;
namespace SharedCache.WinServiceCommon.SharpZipLib.Checksum
{
/// <summary>
/// Generate a table for a byte-wise 32-bit CRC calculation on the polynomial:
/// x^32+x^26+x^23+x^22+x^16+x^12+x^11+x^10+x^8+x^7+x^5+x^4+x^2+x+1.
///
/// Polynomials over GF(2) are represented in binary, one bit per coefficient,
/// with the lowest powers in the most significant bit. Then adding polynomials
/// is just exclusive-or, and multiplying a polynomial by x is a right shift by
/// one. If we call the above polynomial p, and represent a byte as the
/// polynomial q, also with the lowest power in the most significant bit (so the
/// byte 0xb1 is the polynomial x^7+x^3+x+1), then the CRC is (q*x^32) mod p,
/// where a mod b means the remainder after dividing a by b.
///
/// This calculation is done using the shift-register method of multiplying and
/// taking the remainder. The register is initialized to zero, and for each
/// incoming bit, x^32 is added mod p to the register if the bit is a one (where
/// x^32 mod p is p+x^32 = x^26+...+1), and the register is multiplied mod p by
/// x (which is shifting right by one and adding x^32 mod p if the bit shifted
/// out is a one). We start with the highest power (least significant bit) of
/// q and repeat for all eight bits of q.
///
/// The table is simply the CRC of all possible eight bit values. This is all
/// the information needed to generate CRC's on data a byte at a time for all
/// combinations of CRC register values and incoming bytes.
/// </summary>
public sealed class Crc32 : IChecksum
{
readonly static uint CrcSeed = 0xFFFFFFFF;
readonly static uint[] CrcTable = new uint[] {
0x00000000, 0x77073096, 0xEE0E612C, 0x990951BA, 0x076DC419,
0x706AF48F, 0xE963A535, 0x9E6495A3, 0x0EDB8832, 0x79DCB8A4,
0xE0D5E91E, 0x97D2D988, 0x09B64C2B, 0x7EB17CBD, 0xE7B82D07,
0x90BF1D91, 0x1DB71064, 0x6AB020F2, 0xF3B97148, 0x84BE41DE,
0x1ADAD47D, 0x6DDDE4EB, 0xF4D4B551, 0x83D385C7, 0x136C9856,
0x646BA8C0, 0xFD62F97A, 0x8A65C9EC, 0x14015C4F, 0x63066CD9,
0xFA0F3D63, 0x8D080DF5, 0x3B6E20C8, 0x4C69105E, 0xD56041E4,
0xA2677172, 0x3C03E4D1, 0x4B04D447, 0xD20D85FD, 0xA50AB56B,
0x35B5A8FA, 0x42B2986C, 0xDBBBC9D6, 0xACBCF940, 0x32D86CE3,
0x45DF5C75, 0xDCD60DCF, 0xABD13D59, 0x26D930AC, 0x51DE003A,
0xC8D75180, 0xBFD06116, 0x21B4F4B5, 0x56B3C423, 0xCFBA9599,
0xB8BDA50F, 0x2802B89E, 0x5F058808, 0xC60CD9B2, 0xB10BE924,
0x2F6F7C87, 0x58684C11, 0xC1611DAB, 0xB6662D3D, 0x76DC4190,
0x01DB7106, 0x98D220BC, 0xEFD5102A, 0x71B18589, 0x06B6B51F,
0x9FBFE4A5, 0xE8B8D433, 0x7807C9A2, 0x0F00F934, 0x9609A88E,
0xE10E9818, 0x7F6A0DBB, 0x086D3D2D, 0x91646C97, 0xE6635C01,
0x6B6B51F4, 0x1C6C6162, 0x856530D8, 0xF262004E, 0x6C0695ED,
0x1B01A57B, 0x8208F4C1, 0xF50FC457, 0x65B0D9C6, 0x12B7E950,
0x8BBEB8EA, 0xFCB9887C, 0x62DD1DDF, 0x15DA2D49, 0x8CD37CF3,
0xFBD44C65, 0x4DB26158, 0x3AB551CE, 0xA3BC0074, 0xD4BB30E2,
0x4ADFA541, 0x3DD895D7, 0xA4D1C46D, 0xD3D6F4FB, 0x4369E96A,
0x346ED9FC, 0xAD678846, 0xDA60B8D0, 0x44042D73, 0x33031DE5,
0xAA0A4C5F, 0xDD0D7CC9, 0x5005713C, 0x270241AA, 0xBE0B1010,
0xC90C2086, 0x5768B525, 0x206F85B3, 0xB966D409, 0xCE61E49F,
0x5EDEF90E, 0x29D9C998, 0xB0D09822, 0xC7D7A8B4, 0x59B33D17,
0x2EB40D81, 0xB7BD5C3B, 0xC0BA6CAD, 0xEDB88320, 0x9ABFB3B6,
0x03B6E20C, 0x74B1D29A, 0xEAD54739, 0x9DD277AF, 0x04DB2615,
0x73DC1683, 0xE3630B12, 0x94643B84, 0x0D6D6A3E, 0x7A6A5AA8,
0xE40ECF0B, 0x9309FF9D, 0x0A00AE27, 0x7D079EB1, 0xF00F9344,
0x8708A3D2, 0x1E01F268, 0x6906C2FE, 0xF762575D, 0x806567CB,
0x196C3671, 0x6E6B06E7, 0xFED41B76, 0x89D32BE0, 0x10DA7A5A,
0x67DD4ACC, 0xF9B9DF6F, 0x8EBEEFF9, 0x17B7BE43, 0x60B08ED5,
0xD6D6A3E8, 0xA1D1937E, 0x38D8C2C4, 0x4FDFF252, 0xD1BB67F1,
0xA6BC5767, 0x3FB506DD, 0x48B2364B, 0xD80D2BDA, 0xAF0A1B4C,
0x36034AF6, 0x41047A60, 0xDF60EFC3, 0xA867DF55, 0x316E8EEF,
0x4669BE79, 0xCB61B38C, 0xBC66831A, 0x256FD2A0, 0x5268E236,
0xCC0C7795, 0xBB0B4703, 0x220216B9, 0x5505262F, 0xC5BA3BBE,
0xB2BD0B28, 0x2BB45A92, 0x5CB36A04, 0xC2D7FFA7, 0xB5D0CF31,
0x2CD99E8B, 0x5BDEAE1D, 0x9B64C2B0, 0xEC63F226, 0x756AA39C,
0x026D930A, 0x9C0906A9, 0xEB0E363F, 0x72076785, 0x05005713,
0x95BF4A82, 0xE2B87A14, 0x7BB12BAE, 0x0CB61B38, 0x92D28E9B,
0xE5D5BE0D, 0x7CDCEFB7, 0x0BDBDF21, 0x86D3D2D4, 0xF1D4E242,
0x68DDB3F8, 0x1FDA836E, 0x81BE16CD, 0xF6B9265B, 0x6FB077E1,
0x18B74777, 0x88085AE6, 0xFF0F6A70, 0x66063BCA, 0x11010B5C,
0x8F659EFF, 0xF862AE69, 0x616BFFD3, 0x166CCF45, 0xA00AE278,
0xD70DD2EE, 0x4E048354, 0x3903B3C2, 0xA7672661, 0xD06016F7,
0x4969474D, 0x3E6E77DB, 0xAED16A4A, 0xD9D65ADC, 0x40DF0B66,
0x37D83BF0, 0xA9BCAE53, 0xDEBB9EC5, 0x47B2CF7F, 0x30B5FFE9,
0xBDBDF21C, 0xCABAC28A, 0x53B39330, 0x24B4A3A6, 0xBAD03605,
0xCDD70693, 0x54DE5729, 0x23D967BF, 0xB3667A2E, 0xC4614AB8,
0x5D681B02, 0x2A6F2B94, 0xB40BBE37, 0xC30C8EA1, 0x5A05DF1B,
0x2D02EF8D
};
internal static uint ComputeCrc32(uint oldCrc, byte value)
{
return (uint)(Crc32.CrcTable[(oldCrc ^ value) & 0xFF] ^ (oldCrc >> 8));
}
/// <summary>
/// The crc data checksum so far.
/// </summary>
uint crc;
/// <summary>
/// Returns the CRC32 data checksum computed so far.
/// </summary>
public long Value
{
get
{
return (long)crc;
}
set
{
crc = (uint)value;
}
}
/// <summary>
/// Resets the CRC32 data checksum as if no update was ever called.
/// </summary>
public void Reset()
{
crc = 0;
}
/// <summary>
/// Updates the checksum with the int bval.
/// </summary>
/// <param name = "value">
/// the byte is taken as the lower 8 bits of value
/// </param>
public void Update(int value)
{
crc ^= CrcSeed;
crc = CrcTable[(crc ^ value) & 0xFF] ^ (crc >> 8);
crc ^= CrcSeed;
}
/// <summary>
/// Updates the checksum with the bytes taken from the array.
/// </summary>
/// <param name="buffer">
/// buffer an array of bytes
/// </param>
public void Update(byte[] buffer)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
Update(buffer, 0, buffer.Length);
}
/// <summary>
/// Adds the byte array to the data checksum.
/// </summary>
/// <param name = "buffer">
/// The buffer which contains the data
/// </param>
/// <param name = "offset">
/// The offset in the buffer where the data starts
/// </param>
/// <param name = "count">
/// The number of data bytes to update the CRC with.
/// </param>
public void Update(byte[] buffer, int offset, int count)
{
if (buffer == null)
{
throw new ArgumentNullException("buffer");
}
if (count < 0)
{
#if NETCF_1_0
throw new ArgumentOutOfRangeException("count");
#else
throw new ArgumentOutOfRangeException("count", "Count cannot be less than zero");
#endif
}
if (offset < 0 || offset + count > buffer.Length)
{
throw new ArgumentOutOfRangeException("offset");
}
crc ^= CrcSeed;
while (--count >= 0)
{
crc = CrcTable[(crc ^ buffer[offset++]) & 0xFF] ^ (crc >> 8);
}
crc ^= CrcSeed;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
using System.IO;
//using System.Diagnostics;
namespace T5CANLib.CAN
{
/// <summary>
/// CANUSBDevice is an implementation of ICANDevice for the Lawicel CANUSB device
/// (www.canusb.com).
///
/// All incomming messages are published to registered ICANListeners.
/// </summary>
public class CANUSBDevice : ICANDevice, IDisposable
{
static uint m_deviceHandle = 0;
Thread m_readThread;
Object m_synchObject = new Object();
bool m_endThread = false;
private bool m_DoLogging = false;
private string m_startuppath = @"C:\Program files\Dilemma\CarPCControl";
public string Startuppath
{
get { return m_startuppath; }
set { m_startuppath = value; }
}
public bool DoLogging
{
get { return m_DoLogging; }
set { m_DoLogging = value; }
}
/// <summary>
/// Constructor for CANUSBDevice.
/// </summary>
public CANUSBDevice()
{
/*m_readThread = new Thread(readMessages);
try
{
m_readThread.Priority = ThreadPriority.Normal; // realtime enough
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}*/
}
/// <summary>
/// Destructor for CANUSBDevice.
/// </summary>
~CANUSBDevice()
{
try
{
lock (m_synchObject)
{
m_endThread = true;
}
close();
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
}
public enum FlushFlags : byte
{
FLUSH_WAIT = 0,
FLUSH_DONTWAIT = 1,
FLUSH_EMPTY_INQUEUE = 2
}
public override float GetADCValue(uint channel)
{
return 0F;
}
// not supported by lawicel
public override float GetThermoValue()
{
return 0F;
}
public override void Delete()
{
}
public void Dispose()
{
}
public override void setPortNumber(string portnumber)
{
//nothing to do
}
override public void EnableLogging(string path2log)
{
m_DoLogging = true;
m_startuppath = path2log;
}
override public void DisableLogging()
{
m_DoLogging = false;
}
override public void clearReceiveBuffer()
{
LAWICEL.canusb_Flush(m_deviceHandle, (byte)(FlushFlags.FLUSH_DONTWAIT | FlushFlags.FLUSH_EMPTY_INQUEUE));
}
override public void clearTransmitBuffer()
{
LAWICEL.canusb_Flush(m_deviceHandle, (byte)FlushFlags.FLUSH_DONTWAIT);
}
int thrdcnt = 0;
/// <summary>
/// readMessages is the "run" method of this class. It reads all incomming messages
/// and publishes them to registered ICANListeners.
/// </summary>
public void readMessages()
{
int readResult = 0;
LAWICEL.CANMsg r_canMsg = new LAWICEL.CANMsg();
CANMessage canMessage = new CANMessage();
/* Stopwatch
while (true)
{
lock (m_synchObject)
{
if (m_endThread)
return;
}
readResult = LAWICEL.canusb_Read(m_deviceHandle, out r_canMsg);
if (readResult > 0)
{
canMessage.setID(r_canMsg.id);
canMessage.setLength(r_canMsg.len);
canMessage.setTimeStamp(r_canMsg.timestamp);
canMessage.setFlags(r_canMsg.flags);
canMessage.setData(r_canMsg.data);
if (m_DoLogging)
{
DumpCanMsg(r_canMsg, false);
}
lock (m_listeners)
{
foreach (ICANListener listener in m_listeners)
{
listener.handleMessage(canMessage);
}
}
}
else if (readResult == LAWICEL.ERROR_CANUSB_NO_MESSAGE)
{
Thread.Sleep(1);
}
}*/
while (true)
{
/*if ((thrdcnt++ % 1000) == 0)
{
Console.WriteLine("Reading messages");
}*/
lock (m_synchObject)
{
if (m_endThread)
{
m_endThread = false;
return;
}
}
readResult = LAWICEL.canusb_Read(m_deviceHandle, out r_canMsg);
if (readResult > 0)
{
canMessage.setID(r_canMsg.id);
canMessage.setLength(r_canMsg.len);
canMessage.setTimeStamp(r_canMsg.timestamp);
canMessage.setFlags(r_canMsg.flags);
canMessage.setData(r_canMsg.data);
if (m_DoLogging)
{
DumpCanMsg(r_canMsg, false);
}
lock (m_listeners)
{
foreach (ICANListener listener in m_listeners)
{
listener.handleMessage(canMessage);
}
}
}
else if (readResult == LAWICEL.ERROR_CANUSB_NO_MESSAGE)
{
Thread.Sleep(1); // changed to 0 to see performance impact <GS-13122010>
}
}
}
private string GetCharString(int value)
{
char c = Convert.ToChar(value);
string charstr = c.ToString();
if (c == 0x0d) charstr = "<CR>";
else if (c == 0x0a) charstr = "<LF>";
else if (c == 0x00) charstr = "<NULL>";
else if (c == 0x01) charstr = "<SOH>";
else if (c == 0x02) charstr = "<STX>";
else if (c == 0x03) charstr = "<ETX>";
else if (c == 0x04) charstr = "<EOT>";
else if (c == 0x05) charstr = "<ENQ>";
else if (c == 0x06) charstr = "<ACK>";
else if (c == 0x07) charstr = "<BEL>";
else if (c == 0x08) charstr = "<BS>";
else if (c == 0x09) charstr = "<TAB>";
else if (c == 0x0B) charstr = "<VT>";
else if (c == 0x0C) charstr = "<FF>";
else if (c == 0x0E) charstr = "<SO>";
else if (c == 0x0F) charstr = "<SI>";
else if (c == 0x10) charstr = "<DLE>";
else if (c == 0x11) charstr = "<DC1>";
else if (c == 0x12) charstr = "<DC2>";
else if (c == 0x13) charstr = "<DC3>";
else if (c == 0x14) charstr = "<DC4>";
else if (c == 0x15) charstr = "<NACK>";
else if (c == 0x16) charstr = "<SYN>";
else if (c == 0x17) charstr = "<ETB>";
else if (c == 0x18) charstr = "<CAN>";
else if (c == 0x19) charstr = "<EM>";
else if (c == 0x1A) charstr = "<SUB>";
else if (c == 0x1B) charstr = "<ESC>";
else if (c == 0x1C) charstr = "<FS>";
else if (c == 0x1D) charstr = "<GS>";
else if (c == 0x1E) charstr = "<RS>";
else if (c == 0x1F) charstr = "<US>";
else if (c == 0x7F) charstr = "<DEL>";
return charstr;
}
private void DumpCanMsg(LAWICEL.CANMsg r_canMsg, bool IsTransmit)
{
DateTime dt = DateTime.Now;
try
{
using (StreamWriter sw = new StreamWriter(Path.Combine(m_startuppath, dt.Year.ToString("D4") + dt.Month.ToString("D2") + dt.Day.ToString("D2") + "-CanTrace.log"), true))
{
if (IsTransmit)
{
// get the byte transmitted
int transmitvalue = (int)(r_canMsg.data & 0x000000000000FF00);
transmitvalue /= 256;
sw.WriteLine(dt.ToString("dd/MM/yyyy HH:mm:ss") + " TX: id=" + r_canMsg.id.ToString("D2") + " len= " + r_canMsg.len.ToString("X8") + " data=" + r_canMsg.data.ToString("X16") + " " + r_canMsg.flags.ToString("X2") + " character = " + GetCharString(transmitvalue) + "\t ts: " + r_canMsg.timestamp.ToString("X16") + " flags: " + r_canMsg.flags.ToString("X2"));
}
else
{
// get the byte received
int receivevalue = (int)(r_canMsg.data & 0x0000000000FF0000);
receivevalue /= (256 * 256);
sw.WriteLine(dt.ToString("dd/MM/yyyy HH:mm:ss") + " RX: id=" + r_canMsg.id.ToString("D2") + " len= " + r_canMsg.len.ToString("X8") + " data=" + r_canMsg.data.ToString("X16") + " " + r_canMsg.flags.ToString("X2") + " character = " + GetCharString(receivevalue) + "\t ts: " + r_canMsg.timestamp.ToString("X16") + " flags: " + r_canMsg.flags.ToString("X2"));
}
}
}
catch (Exception E)
{
Console.WriteLine("Failed to write to logfile: " + E.Message);
}
}
override public int GetNumberOfAdapters()
{
char[] buff = new char[32];
return LAWICEL.canusb_getFirstAdapter(buff, 32);
}
/// <summary>
/// The open method tries to connect to both busses to see if one of them is connected and
/// active. The first strategy is to listen for any CAN message. If this fails there is a
/// check to see if the application is started after an interrupted flash session. This is
/// done by sending a message to set address and length (only for P-bus).
/// </summary>
/// <returns>OpenResult.OK is returned on success. Otherwise OpenResult.OpenError is
/// returned.</returns>
override public OpenResult open()
{
if (m_deviceHandle != 0)
{
close();
}
m_deviceHandle = LAWICEL.canusb_Open(IntPtr.Zero,
"0x40:0x37",
LAWICEL.CANUSB_ACCEPTANCE_CODE_ALL,
LAWICEL.CANUSB_ACCEPTANCE_MASK_ALL,
LAWICEL.CANUSB_FLAG_TIMESTAMP);
if (m_deviceHandle > 0)
{
LAWICEL.canusb_Flush(m_deviceHandle, 0x01);
Console.WriteLine("Creating new reader thread");
m_readThread = new Thread(readMessages);
try
{
m_readThread.Priority = ThreadPriority.Normal; // realtime enough
}
catch (Exception E)
{
Console.WriteLine(E.Message);
}
if (m_readThread.ThreadState == ThreadState.Unstarted)
m_readThread.Start();
return OpenResult.OK;
}
else
{
// second try after unload of dlls?
//close();
return OpenResult.OpenError;
}
}
/// <summary>
/// The close method closes the CANUSB device.
/// </summary>
/// <returns>CloseResult.OK on success, otherwise CloseResult.CloseError.</returns>
override public CloseResult close()
{
Console.WriteLine("Close called in CANUSBDevice");
if (m_readThread != null)
{
if (m_readThread.ThreadState != ThreadState.Stopped && m_readThread.ThreadState != ThreadState.StopRequested)
{
lock (m_synchObject)
{
m_endThread = true;
}
// m_readThread.Abort();
}
}
int res = LAWICEL.canusb_Close(m_deviceHandle);
m_deviceHandle = 0;
if (LAWICEL.ERROR_CANUSB_OK == res)
{
return CloseResult.OK;
}
else
{
return CloseResult.CloseError;
}
}
/// <summary>
/// isOpen checks if the device is open.
/// </summary>
/// <returns>true if the device is open, otherwise false.</returns>
override public bool isOpen()
{
if (m_deviceHandle > 0)
return true;
else
return false;
}
/// <summary>
/// sendMessage send a CANMessage.
/// </summary>
/// <param name="a_message">A CANMessage.</param>
/// <returns>true on success, othewise false.</returns>
override public bool sendMessage(CANMessage a_message)
{
LAWICEL.CANMsg msg = new LAWICEL.CANMsg();
msg.id = a_message.getID();
msg.len = a_message.getLength();
msg.flags = a_message.getFlags();
msg.data = a_message.getData();
if (m_DoLogging)
{
DumpCanMsg(msg, true);
}
int writeResult;
writeResult = LAWICEL.canusb_Write(m_deviceHandle, ref msg);
if (writeResult == LAWICEL.ERROR_CANUSB_OK)
return true;
else
return false;
}
/// <summary>
/// waitForMessage waits for a specific CAN message give by a CAN id.
/// </summary>
/// <param name="a_canID">The CAN id to listen for</param>
/// <param name="timeout">Listen timeout</param>
/// <param name="r_canMsg">The CAN message with a_canID that we where listening for.</param>
/// <returns>The CAN id for the message we where listening for, otherwise 0.</returns>
private uint waitForMessage(uint a_canID, uint timeout, out LAWICEL.CANMsg r_canMsg)
{
int readResult = 0;
int nrOfWait = 0;
while (nrOfWait < timeout)
{
readResult = LAWICEL.canusb_Read(m_deviceHandle, out r_canMsg);
if (readResult == LAWICEL.ERROR_CANUSB_OK)
{
if (r_canMsg.id != a_canID)
continue;
return (uint)r_canMsg.id;
}
else if (readResult == LAWICEL.ERROR_CANUSB_NO_MESSAGE)
{
Thread.Sleep(1); // changed to 0 to see performance impact <GS-13122010>
nrOfWait++;
}
}
r_canMsg = new LAWICEL.CANMsg();
return 0;
}
/// <summary>
/// waitAnyMessage waits for any message to be received.
/// </summary>
/// <param name="timeout">Listen timeout</param>
/// <param name="r_canMsg">The CAN message that was first received</param>
/// <returns>The CAN id for the message received, otherwise 0.</returns>
private uint waitAnyMessage(uint timeout, out LAWICEL.CANMsg r_canMsg)
{
int readResult = 0;
int nrOfWait = 0;
while (nrOfWait < timeout)
{
readResult = LAWICEL.canusb_Read(m_deviceHandle, out r_canMsg);
if (readResult == LAWICEL.ERROR_CANUSB_OK)
{
return (uint)r_canMsg.id;
}
else if (readResult == LAWICEL.ERROR_CANUSB_NO_MESSAGE)
{
Thread.Sleep(1); // changed to 0 to see performance impact <GS-13122010>
nrOfWait++;
}
}
r_canMsg = new LAWICEL.CANMsg();
return 0;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using StructureMap.Configuration;
using StructureMap.Graph;
using StructureMap.Pipeline;
using StructureMap.Query;
using StructureMap.TypeRules;
namespace StructureMap
{
public class PipelineGraph : IPipelineGraph
{
public static IPipelineGraph For(Action<ConfigurationExpression> action)
{
var expression = new ConfigurationExpression();
action(expression);
var graph = expression.BuildGraph();
return BuildRoot(graph);
}
public static IPipelineGraph BuildRoot(PluginGraph pluginGraph)
{
return new PipelineGraph(pluginGraph, new RootInstanceGraph(pluginGraph), null, pluginGraph.SingletonCache,
new NulloTransientCache());
}
public static IPipelineGraph BuildEmpty()
{
var pluginGraph = new PluginGraph();
return new PipelineGraph(pluginGraph, new RootInstanceGraph(pluginGraph), null, pluginGraph.SingletonCache,
new NulloTransientCache());
}
private readonly PluginGraph _pluginGraph;
private readonly IInstanceGraph _instances;
private readonly IPipelineGraph _root;
private readonly IObjectCache _singletons;
private readonly IObjectCache _transients;
private readonly Profiles _profiles;
public PipelineGraph(PluginGraph pluginGraph, IInstanceGraph instances, IPipelineGraph root,
IObjectCache singletons, IObjectCache transients)
{
_pluginGraph = pluginGraph;
_instances = instances;
if (root == null)
{
_root = this;
_profiles = new Profiles(_pluginGraph, this);
ContainerCache = singletons;
}
else
{
_root = root.Root();
_profiles = root.Profiles;
ContainerCache = new ContainerSpecificObjectCache();
}
_singletons = singletons;
_transients = transients;
}
public IObjectCache ContainerCache { get; private set; }
public IPipelineGraph Root()
{
return _root;
}
public Profiles Profiles
{
get { return _profiles; }
}
public IInstanceGraph Instances
{
get { return _instances; }
}
public IObjectCache Singletons
{
get { return _singletons; }
}
public IObjectCache Transients
{
get { return _transients; }
}
public IModel ToModel()
{
return new Model(this, _pluginGraph);
}
public string Profile
{
get { return _pluginGraph.ProfileName; }
}
public ContainerRole Role
{
get { return _instances.Role; }
}
public IGraphEjector Ejector
{
get { return new GraphEjector(_pluginGraph, this); }
}
public Policies Policies
{
get
{
return _pluginGraph.Root.Policies;
}
}
public void Dispose()
{
if (Role == ContainerRole.Root)
{
_singletons.DisposeAndClear();
}
_transients.DisposeAndClear();
_pluginGraph.SafeDispose();
}
public void RegisterContainer(IContainer container)
{
var containerInstance = new ObjectInstance(container);
containerInstance.SetLifecycleTo<TransientLifecycle>();
_pluginGraph.Families[typeof (IContainer)].SetDefault(containerInstance);
}
public IPipelineGraph ToNestedGraph()
{
var nestedPluginGraph = new PluginGraph(Profile + " - Nested") {Parent = _pluginGraph};
var instances = new ComplexInstanceGraph(this, nestedPluginGraph, ContainerRole.Nested);
return new PipelineGraph(nestedPluginGraph, instances, this, _singletons,
new ContainerSpecificObjectCache());
}
public void Configure(Action<ConfigurationExpression> configure)
{
var registry = new ConfigurationExpression();
configure(registry);
if (registry.HasPolicyChanges() && Role == ContainerRole.Nested)
{
throw new StructureMapConfigurationException("Policy changes to a nested container are not allowed. Policies can only be applied to the root container");
}
var builder = new PluginGraphBuilder(_pluginGraph);
builder.Add(registry);
registry.Registries.Each(x => x.As<IPluginGraphConfiguration>().Register(builder));
registry.Registries.Each(x => builder.Add(x));
builder.RunConfigurations();
if (registry.HasPolicyChanges())
{
Instances.GetAllInstances().ToArray().Each(x => x.ClearBuildPlan());
Profiles.AllProfiles().ToArray()
.Each(x => x.Instances.GetAllInstances().ToArray().Each(i => i.ClearBuildPlan()));
}
}
public void ValidateValidNestedScoping()
{
var descriptions = new List<string>();
_pluginGraph.Families.Each(family => {
family.Instances.Where(x => !(x is IValue)).Each(instance => {
var lifecycle = instance.DetermineLifecycle(family.Lifecycle);
if (!(lifecycle is IAppropriateForNestedContainer))
{
descriptions.Add("{0} or plugin type {1} has lifecycle {2}".ToFormat(instance.Description, family.PluginType.GetFullName(), lifecycle.Description));
}
});
});
if (!descriptions.Any()) return;
var message =
"Only registrations of the default Transient, UniquePerRequest, and prebuilt objects are valid for nested containers. Remember that 'Transient' instances will be built once per nested container. If you need this functionality, try using a Child/Profile container instead\n";
message += string.Join("\n", descriptions);
throw new InvalidOperationException(message);
}
public ILifecycle DetermineLifecycle(Type pluginType, Instance instance)
{
return instance.DetermineLifecycle(_instances.DefaultLifecycleFor(pluginType));
}
}
}
| |
using System;
using Microsoft.SPOT;
using Microsoft.SPOT.Presentation.Media;
namespace Skewworks.NETMF.Controls
{
[Serializable]
public class ListboxItem : MarshalByRefObject
{
#region Variables
private string _text;
private Bitmap _image;
private bool _checked;
private Listbox _parent;
private bool _allowCheck;
private object _tag;
private Font _fnt;
private Color _bkg;
#endregion
#region Constructors
public ListboxItem(string text, bool allowCheckbox = true)
{
_text = text;
_image = null;
_checked = false;
_allowCheck = allowCheckbox;
}
public ListboxItem(string text, Bitmap image, bool allowCheckbox = true)
{
_text = text;
_image = image;
_checked = false;
_allowCheck = allowCheckbox;
}
public ListboxItem(string text, bool checkValue, bool allowCheckbox = true)
{
_text = text;
_image = null;
_checked = checkValue;
_allowCheck = allowCheckbox;
}
public ListboxItem(string text, Bitmap image, bool checkValue, bool allowCheckbox = true)
{
_text = text;
_image = image;
_checked = checkValue;
_allowCheck = allowCheckbox;
}
public ListboxItem(string text, Font font, Color backColor, bool allowCheckbox = true)
{
_text = text;
_image = null;
_checked = false;
_allowCheck = allowCheckbox;
_fnt = font;
_bkg = backColor;
}
public ListboxItem(string text, Font font, Color backColor, Bitmap image, bool allowCheckbox = true)
{
_text = text;
_image = image;
_checked = false;
_allowCheck = allowCheckbox;
_fnt = font;
_bkg = backColor;
}
public ListboxItem(string text, Font font, Color backColor, bool checkValue, bool allowCheckbox = true)
{
_text = text;
_image = null;
_checked = checkValue;
_allowCheck = allowCheckbox;
_fnt = font;
_bkg = backColor;
}
public ListboxItem(string text, Font font, Color backColor, Bitmap image, bool checkValue, bool allowCheckbox = true)
{
_text = text;
_image = image;
_checked = checkValue;
_allowCheck = allowCheckbox;
_fnt = font;
_bkg = backColor;
}
#endregion
#region Properties
public bool AllowCheckbox
{
get { return _allowCheck; }
set
{
if (_allowCheck == value)
return;
_allowCheck = value;
if (_parent != null)
_parent.Invalidate();
}
}
public Color AlternateBackColor
{
get { return _bkg; }
set
{
if (_bkg == value)
return;
_bkg = value;
if (_parent != null)
_parent.Invalidate();
}
}
public Font AlternateFont
{
get { return _fnt; }
set
{
if (_fnt == value)
return;
_fnt = value;
if (_parent != null)
_parent.Invalidate();
}
}
public bool Checked
{
get { return _checked; }
set
{
if (_checked == value)
return;
_checked = value;
if (_parent != null)
_parent.Invalidate();
}
}
public Bitmap Image
{
get { return _image; }
set
{
if (_image == value)
return;
_image = value;
if (_parent != null)
_parent.Invalidate();
}
}
internal Listbox Parent
{
get { return _parent; }
set { _parent = value; }
}
public object Tag
{
get { return _tag; }
set { _tag = value; }
}
public string Text
{
get { return _text; }
set
{
if (_text == value)
return;
_text = value;
if (_parent != null)
_parent.Invalidate();
}
}
internal rect Bounds
{
get;
set;
}
internal rect CheckboxBounds
{
get;
set;
}
#endregion
}
}
| |
/*
* CharacterSetElement.cs
*/
using System;
using System.Collections;
using System.IO;
using System.Text;
using Core.Library;
namespace Core.Library.RE {
/**
* A regular expression character set element. This element
* matches a single character inside (or outside) a character set.
* The character set is user defined and may contain ranges of
* characters. The set may also be inverted, meaning that only
* characters not inside the set will be considered to match.
*
*
*/
internal class CharacterSetElement : Element {
/**
* The dot ('.') character set. This element matches a single
* character that is not equal to a newline character.
*/
public static CharacterSetElement DOT =
new CharacterSetElement(false);
/**
* The digit character set. This element matches a single
* numeric character.
*/
public static CharacterSetElement DIGIT =
new CharacterSetElement(false);
/**
* The non-digit character set. This element matches a single
* non-numeric character.
*/
public static CharacterSetElement NON_DIGIT =
new CharacterSetElement(true);
/**
* The whitespace character set. This element matches a single
* whitespace character.
*/
public static CharacterSetElement WHITESPACE =
new CharacterSetElement(false);
/**
* The non-whitespace character set. This element matches a
* single non-whitespace character.
*/
public static CharacterSetElement NON_WHITESPACE =
new CharacterSetElement(true);
/**
* The word character set. This element matches a single word
* character.
*/
public static CharacterSetElement WORD =
new CharacterSetElement(false);
/**
* The non-word character set. This element matches a single
* non-word character.
*/
public static CharacterSetElement NON_WORD =
new CharacterSetElement(true);
/**
* The inverted character set flag.
*/
private bool inverted;
/**
* The character set content. This array may contain either
* range objects or Character objects.
*/
private ArrayList contents = new ArrayList();
/**
* Creates a new character set element. If the inverted character
* set flag is set, only characters NOT in the set will match.
*
* @param inverted the inverted character set flag
*/
public CharacterSetElement(bool inverted) {
this.inverted = inverted;
}
/**
* Adds a single character to this character set.
*
* @param c the character to add
*/
public void AddCharacter(char c) {
contents.Add(c);
}
/**
* Adds multiple characters to this character set.
*
* @param str the string with characters to add
*/
public void AddCharacters(string str) {
for (int i = 0; i < str.Length; i++) {
AddCharacter(str[i]);
}
}
/**
* Adds multiple characters to this character set.
*
* @param elem the string element with characters to add
*/
public void AddCharacters(StringElement elem) {
AddCharacters(elem.GetString());
}
/**
* Adds a character range to this character set.
*
* @param min the minimum character value
* @param max the maximum character value
*/
public void AddRange(char min, char max) {
contents.Add(new Range(min, max));
}
/**
* Adds a character subset to this character set.
*
* @param elem the character set to add
*/
public void AddCharacterSet(CharacterSetElement elem) {
contents.Add(elem);
}
/**
* Returns this element as the character set shouldn't be
* modified after creation. This partially breaks the contract
* of clone(), but as new characters are not added to the
* character set after creation, this will work correctly.
*
* @return this character set element
*/
public override object Clone() {
return this;
}
/**
* Returns the length of a matching string starting at the
* specified position. The number of matches to skip can also be
* specified, but numbers higher than zero (0) cause a failed
* match for any element that doesn't attempt to combine other
* elements.
*
* @param m the matcher being used
* @param buffer the input character buffer to match
* @param start the starting position
* @param skip the number of matches to skip
*
* @return the length of the matching string, or
* -1 if no match was found
*
* @throws IOException if an I/O error occurred
*/
public override int Match(Matcher m,
ReaderBuffer buffer,
int start,
int skip) {
int c;
if (skip != 0) {
return -1;
}
c = buffer.Peek(start);
if (c < 0) {
m.SetReadEndOfString();
return -1;
}
if (m.IsCaseInsensitive()) {
c = (int) Char.ToLower((char) c);
}
return InSet((char) c) ? 1 : -1;
}
/**
* Checks if the specified character matches this character
* set. This method takes the inverted flag into account.
*
* @param c the character to check
*
* @return true if the character matches, or
* false otherwise
*/
private bool InSet(char c) {
if (this == DOT) {
return InDotSet(c);
} else if (this == DIGIT || this == NON_DIGIT) {
return InDigitSet(c) != inverted;
} else if (this == WHITESPACE || this == NON_WHITESPACE) {
return InWhitespaceSet(c) != inverted;
} else if (this == WORD || this == NON_WORD) {
return InWordSet(c) != inverted;
} else {
return InUserSet(c) != inverted;
}
}
/**
* Checks if the specified character is present in the 'dot'
* set. This method does not consider the inverted flag.
*
* @param c the character to check
*
* @return true if the character is present, or
* false otherwise
*/
private bool InDotSet(char c) {
switch (c) {
case '\n':
case '\r':
case '\u0085':
case '\u2028':
case '\u2029':
return false;
default:
return true;
}
}
/**
* Checks if the specified character is a digit. This method
* does not consider the inverted flag.
*
* @param c the character to check
*
* @return true if the character is a digit, or
* false otherwise
*/
private bool InDigitSet(char c) {
return '0' <= c && c <= '9';
}
/**
* Checks if the specified character is a whitespace
* character. This method does not consider the inverted flag.
*
* @param c the character to check
*
* @return true if the character is a whitespace character, or
* false otherwise
*/
private bool InWhitespaceSet(char c) {
switch (c) {
case ' ':
case '\t':
case '\n':
case '\f':
case '\r':
case (char) 11:
return true;
default:
return false;
}
}
/**
* Checks if the specified character is a word character. This
* method does not consider the inverted flag.
*
* @param c the character to check
*
* @return true if the character is a word character, or
* false otherwise
*/
private bool InWordSet(char c) {
return ('a' <= c && c <= 'z')
|| ('A' <= c && c <= 'Z')
|| ('0' <= c && c <= '9')
|| c == '_';
}
/**
* Checks if the specified character is present in the user-
* defined set. This method does not consider the inverted
* flag.
*
* @param value the character to check
*
* @return true if the character is present, or
* false otherwise
*/
private bool InUserSet(char value) {
object obj;
char c;
Range r;
CharacterSetElement e;
for (int i = 0; i < contents.Count; i++) {
obj = contents[i];
if (obj is char) {
c = (char) obj;
if (c == value) {
return true;
}
} else if (obj is Range) {
r = (Range) obj;
if (r.Inside(value)) {
return true;
}
} else if (obj is CharacterSetElement) {
e = (CharacterSetElement) obj;
if (e.InSet(value)) {
return true;
}
}
}
return false;
}
/**
* Prints this element to the specified output stream.
*
* @param output the output stream to use
* @param indent the current indentation
*/
public override void PrintTo(TextWriter output, string indent) {
output.WriteLine(indent + ToString());
}
/**
* Returns a string description of this character set.
*
* @return a string description of this character set
*/
public override string ToString() {
StringBuilder buffer;
// Handle predefined character sets
if (this == DOT) {
return ".";
} else if (this == DIGIT) {
return "\\d";
} else if (this == NON_DIGIT) {
return "\\D";
} else if (this == WHITESPACE) {
return "\\s";
} else if (this == NON_WHITESPACE) {
return "\\S";
} else if (this == WORD) {
return "\\w";
} else if (this == NON_WORD) {
return "\\W";
}
// Handle user-defined character sets
buffer = new StringBuilder();
if (inverted) {
buffer.Append("^[");
} else {
buffer.Append("[");
}
for (int i = 0; i < contents.Count; i++) {
buffer.Append(contents[i]);
}
buffer.Append("]");
return buffer.ToString();
}
/**
* A character range class.
*/
private class Range {
/**
* The minimum character value.
*/
private char min;
/**
* The maximum character value.
*/
private char max;
/**
* Creates a new character range.
*
* @param min the minimum character value
* @param max the maximum character value
*/
public Range(char min, char max) {
this.min = min;
this.max = max;
}
/**
* Checks if the specified character is inside the range.
*
* @param c the character to check
*
* @return true if the character is in the range, or
* false otherwise
*/
public bool Inside(char c) {
return min <= c && c <= max;
}
/**
* Returns a string representation of this object.
*
* @return a string representation of this object
*/
public override string ToString() {
return min + "-" + max;
}
}
}
}
| |
using System;
using System.IO;
namespace Eto.Forms
{
/// <summary>
/// Event arguments when the <see cref="WebView"/> has finished loaded a uri
/// </summary>
public class WebViewLoadedEventArgs : EventArgs
{
/// <summary>
/// Gets the URI of the page that was loaded.
/// </summary>
/// <value>The URI.</value>
public Uri Uri { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Forms.WebViewLoadedEventArgs"/> class.
/// </summary>
/// <param name="uri">URI of the page that was loaded.</param>
public WebViewLoadedEventArgs(Uri uri)
{
this.Uri = uri;
}
}
/// <summary>
/// Event arguments when the <see cref="WebView"/> is loading a new uri.
/// </summary>
public class WebViewLoadingEventArgs : WebViewLoadedEventArgs
{
/// <summary>
/// Gets or sets a value indicating whether to cancel the load.
/// </summary>
/// <value><c>true</c> to cancel loading the page; otherwise, <c>false</c>.</value>
public bool Cancel { get; set; }
/// <summary>
/// Gets or sets a value indicating whether the main frame is loading, or a child frame.
/// </summary>
/// <value><c>true</c> if loading for the main frame; otherwise, <c>false</c>.</value>
public bool IsMainFrame { get; set; }
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Forms.WebViewLoadingEventArgs"/> class.
/// </summary>
/// <param name="uri">URI of the page that is loading.</param>
/// <param name="isMainFrame">If set to <c>true</c> the uri is for the main frame, otherwise <c>false</c>.</param>
public WebViewLoadingEventArgs(Uri uri, bool isMainFrame)
: base(uri)
{
this.IsMainFrame = isMainFrame;
}
}
/// <summary>
/// Event arguments for when the <see cref="WebView"/> changes its title
/// </summary>
public class WebViewTitleEventArgs : EventArgs
{
/// <summary>
/// Gets the new title for the page.
/// </summary>
/// <value>The title for the page.</value>
public string Title { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Forms.WebViewTitleEventArgs"/> class.
/// </summary>
/// <param name="title">New title for the page.</param>
public WebViewTitleEventArgs(string title)
{
this.Title = title;
}
}
/// <summary>
/// Event arguments for when the <see cref="WebView"/> prompts to open a new window.
/// </summary>
public class WebViewNewWindowEventArgs : WebViewLoadingEventArgs
{
/// <summary>
/// Gets the name of the new window.
/// </summary>
/// <value>The name of the new window.</value>
public string NewWindowName { get; private set; }
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Forms.WebViewNewWindowEventArgs"/> class.
/// </summary>
/// <param name="uri">URI of the new window.</param>
/// <param name="newWindowName">Name of the new window.</param>
public WebViewNewWindowEventArgs(Uri uri, string newWindowName)
: base(uri, false)
{
this.NewWindowName = newWindowName;
}
}
/// <summary>
/// Control to show a browser control that can display html and execute javascript.
/// </summary>
/// <remarks>
/// Most platforms have built-in support for a browser control, which by default this will use.
///
/// There are other browser implementations available, such as Chromium, etc.
/// You can create your own handler for the web view if you want to use a different browser control.
/// </remarks>
[Handler(typeof(WebView.IHandler))]
public class WebView : Control
{
new IHandler Handler { get { return (IHandler)base.Handler; } }
#region Events
/// <summary>
/// Identifier for handlers when attaching the <see cref="Navigated"/> event.
/// </summary>
public const string NavigatedEvent = "WebView.Navigated";
/// <summary>
/// Occurs when the browser has loaded a new uri and has begun loading it.
/// </summary>
/// <remarks>
/// This happens after the <see cref="DocumentLoading"/> event.
/// Once the document is fully loaded, the <see cref="DocumentLoaded"/> event will be triggered.
/// </remarks>
public event EventHandler<WebViewLoadedEventArgs> Navigated
{
add { Properties.AddHandlerEvent(NavigatedEvent, value); }
remove { Properties.RemoveEvent(NavigatedEvent, value); }
}
/// <summary>
/// Raises the <see cref="Navigated"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnNavigated(WebViewLoadedEventArgs e)
{
Properties.TriggerEvent(NavigatedEvent, this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="DocumentLoaded"/> event.
/// </summary>
public const string DocumentLoadedEvent = "WebView.DocumentLoaded";
/// <summary>
/// Occurs when the document is fully loaded.
/// </summary>
/// <remarks>
/// This event fires after the entire document has loaded and is fully rendered.
/// Usually this is a good event to use when determining when you can execute scripts
/// or interact with the document.
/// </remarks>
public event EventHandler<WebViewLoadedEventArgs> DocumentLoaded
{
add { Properties.AddHandlerEvent(DocumentLoadedEvent, value); }
remove { Properties.RemoveEvent(DocumentLoadedEvent, value); }
}
/// <summary>
/// Raises the <see cref="DocumentLoaded"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnDocumentLoaded(WebViewLoadedEventArgs e)
{
Properties.TriggerEvent(DocumentLoadedEvent, this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="DocumentLoading"/> event.
/// </summary>
public const string DocumentLoadingEvent = "WebView.DocumentLoading";
/// <summary>
/// Occurs when a document starts loading.
/// </summary>
/// <remarks>
/// This fires when the document shown is changed, and notifies which url is being loaded.
/// You can cancel the loading of a page through this event, though you should check the <see cref="WebViewLoadingEventArgs.IsMainFrame"/>
/// to determine if it is for the main frame, or a child frame.
/// </remarks>
public event EventHandler<WebViewLoadingEventArgs> DocumentLoading
{
add { Properties.AddHandlerEvent(DocumentLoadingEvent, value); }
remove { Properties.RemoveEvent(DocumentLoadingEvent, value); }
}
/// <summary>
/// Raises the <see cref="DocumentLoading"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnDocumentLoading(WebViewLoadingEventArgs e)
{
Properties.TriggerEvent(DocumentLoadingEvent, this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="OpenNewWindow"/> event.
/// </summary>
public const string OpenNewWindowEvent = "WebView.OpenNewWindow";
/// <summary>
/// Occurs when the page prompts to open a link in a new window
/// </summary>
/// <remarks>
/// This event will occur when a user or script opens a new link in a new window.
///
/// This is usually when an anchor's target is set to _blank, or a specific window name.
///
/// You must handle this event to perform an action, otherwise no action will occur.
/// </remarks>
public event EventHandler<WebViewNewWindowEventArgs> OpenNewWindow
{
add { Properties.AddHandlerEvent(OpenNewWindowEvent, value); }
remove { Properties.RemoveEvent(OpenNewWindowEvent, value); }
}
/// <summary>
/// Raises the <see cref="OpenNewWindow"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnOpenNewWindow(WebViewNewWindowEventArgs e)
{
Properties.TriggerEvent(OpenNewWindowEvent, this, e);
}
/// <summary>
/// Identifier for handlers when attaching the <see cref="DocumentTitleChanged"/> event.
/// </summary>
public const string DocumentTitleChangedEvent = "WebView.DocumentTitleChanged";
/// <summary>
/// Occurs when the title of the page has change either through navigation or a script.
/// </summary>
public event EventHandler<WebViewTitleEventArgs> DocumentTitleChanged
{
add { Properties.AddHandlerEvent(DocumentTitleChangedEvent, value); }
remove { Properties.RemoveEvent(DocumentTitleChangedEvent, value); }
}
/// <summary>
/// Raises the <see cref="DocumentTitleChanged"/> event.
/// </summary>
/// <param name="e">Event arguments.</param>
protected virtual void OnDocumentTitleChanged(WebViewTitleEventArgs e)
{
Properties.TriggerEvent(DocumentTitleChangedEvent, this, e);
}
#endregion
static WebView()
{
EventLookup.Register<WebView>(c => c.OnNavigated(null), WebView.NavigatedEvent);
EventLookup.Register<WebView>(c => c.OnDocumentLoaded(null), WebView.DocumentLoadedEvent);
EventLookup.Register<WebView>(c => c.OnDocumentLoading(null), WebView.DocumentLoadingEvent);
EventLookup.Register<WebView>(c => c.OnDocumentTitleChanged(null), WebView.DocumentTitleChangedEvent);
EventLookup.Register<WebView>(c => c.OnOpenNewWindow(null), WebView.OpenNewWindowEvent);
}
/// <summary>
/// Navigates the browser back to the previous page in history, if there is one.
/// </summary>
/// <seealso cref="CanGoBack"/>
public void GoBack()
{
Handler.GoBack();
}
/// <summary>
/// Gets a value indicating whether the browser can go back to the previous page in history.
/// </summary>
/// <seealso cref="GoBack"/>
/// <value><c>true</c> if the browser can go back; otherwise, <c>false</c>.</value>
public bool CanGoBack
{
get{ return Handler.CanGoBack; }
}
/// <summary>
/// Navigates the browser forward to the next page in history, if there is one.
/// </summary>
/// <seealso cref="CanGoForward"/>
public void GoForward()
{
Handler.GoForward();
}
/// <summary>
/// Gets a value indicating whether the browser can go forward to the next page.
/// </summary>
/// <seealso cref="GoForward"/>
/// <value><c>true</c> if the browser can go forward; otherwise, <c>false</c>.</value>
public bool CanGoForward
{
get { return Handler.CanGoForward; }
}
/// <summary>
/// Gets or sets the URL of the currently navigated page.
/// </summary>
/// <remarks>
/// Setting this will cause the current page to stop loading (if not already loaded), and begin loading another page.
/// Loading the new page can be cancelled by the <see cref="DocumentLoading"/> event.
/// </remarks>
/// <value>The URL of the currently navigated page.</value>
public Uri Url
{
get { return Handler.Url; }
set { Handler.Url = value; }
}
/// <summary>
/// Stops loading the current page.
/// </summary>
/// <remarks>
/// You can determine if the page is finished loading by the <see cref="DocumentLoaded"/> event.
/// </remarks>
public void Stop()
{
Handler.Stop();
}
/// <summary>
/// Reloads the current page
/// </summary>
public void Reload()
{
Handler.Reload();
}
/// <summary>
/// Executes the specified javascript in the context of the current page, returning its result.
/// </summary>
/// <returns>The script to execute.</returns>
/// <param name="script">Script result.</param>
public string ExecuteScript(string script)
{
return Handler.ExecuteScript(script);
}
/// <summary>
/// Gets the document title of the current page.
/// </summary>
/// <value>The document title.</value>
public string DocumentTitle
{
get { return Handler.DocumentTitle; }
}
/// <summary>
/// Loads the specified stream as html into the control.
/// </summary>
/// <param name="stream">Stream containing the html to load.</param>
/// <param name="baseUri">Base URI to load associated resources. Can be a url or file path.</param>
public void LoadHtml(Stream stream, Uri baseUri = null)
{
using (var reader = new StreamReader(stream))
{
Handler.LoadHtml(reader.ReadToEnd(), baseUri);
}
}
/// <summary>
/// Loads the specified html string.
/// </summary>
/// <param name="html">Html string to load.</param>
/// <param name="baseUri">Base URI to load associated resources. Can be a url or file path.</param>
public void LoadHtml(string html, Uri baseUri = null)
{
Handler.LoadHtml(html, baseUri);
}
/// <summary>
/// Shows the print dialog for the current page.
/// </summary>
/// <remarks>
/// This prompts the browser to print its contents.
/// </remarks>
public void ShowPrintDialog()
{
Handler.ShowPrintDialog();
}
/// <summary>
/// Gets or sets a value indicating whether the user can click to show the context menu.
/// </summary>
/// <remarks>
/// This is useful when using a browser control with content that should not be changed.
/// The context menu can show navigation items which may cause the page to reload so setting this
/// value to false will ensure the user can only interact with the page as is.
/// </remarks>
/// <value><c>true</c> if the context menu is enabled; otherwise, <c>false</c>.</value>
public bool BrowserContextMenuEnabled
{
get { return Handler.BrowserContextMenuEnabled; }
set { Handler.BrowserContextMenuEnabled = value; }
}
/// <summary>
/// Callback interface for the <see cref="WebView"/>.
/// </summary>
public new interface ICallback : Control.ICallback
{
/// <summary>
/// Raises the navigated event.
/// </summary>
void OnNavigated(WebView widget, WebViewLoadedEventArgs e);
/// <summary>
/// Raises the document loaded event.
/// </summary>
void OnDocumentLoaded(WebView widget, WebViewLoadedEventArgs e);
/// <summary>
/// Raises the document loading event.
/// </summary>
void OnDocumentLoading(WebView widget, WebViewLoadingEventArgs e);
/// <summary>
/// Raises the open new window event.
/// </summary>
void OnOpenNewWindow(WebView widget, WebViewNewWindowEventArgs e);
/// <summary>
/// Raises the document title changed event.
/// </summary>
void OnDocumentTitleChanged(WebView widget, WebViewTitleEventArgs e);
}
static readonly object callback = new Callback();
/// <summary>
/// Gets an instance of an object used to perform callbacks to the widget from handler implementations
/// </summary>
/// <returns>The callback instance to use for this widget</returns>
protected override object GetCallback()
{
return callback;
}
/// <summary>
/// Callback implementation for handlers of the <see cref="WebView"/>
/// </summary>
protected new class Callback : Control.Callback, ICallback
{
/// <summary>
/// Raises the navigated event.
/// </summary>
public void OnNavigated(WebView widget, WebViewLoadedEventArgs e)
{
widget.Platform.Invoke(() => widget.OnNavigated(e));
}
/// <summary>
/// Raises the document loaded event.
/// </summary>
public void OnDocumentLoaded(WebView widget, WebViewLoadedEventArgs e)
{
widget.Platform.Invoke(() => widget.OnDocumentLoaded(e));
}
/// <summary>
/// Raises the document loading event.
/// </summary>
public void OnDocumentLoading(WebView widget, WebViewLoadingEventArgs e)
{
widget.Platform.Invoke(() => widget.OnDocumentLoading(e));
}
/// <summary>
/// Raises the open new window event.
/// </summary>
public void OnOpenNewWindow(WebView widget, WebViewNewWindowEventArgs e)
{
widget.Platform.Invoke(() => widget.OnOpenNewWindow(e));
}
/// <summary>
/// Raises the document title changed event.
/// </summary>
public void OnDocumentTitleChanged(WebView widget, WebViewTitleEventArgs e)
{
widget.Platform.Invoke(() => widget.OnDocumentTitleChanged(e));
}
}
/// <summary>
/// Handler interface for the <see cref="WebView"/>.
/// </summary>
public new interface IHandler : Control.IHandler
{
/// <summary>
/// Gets or sets the URL of the currently navigated page.
/// </summary>
/// <remarks>
/// Setting this will cause the current page to stop loading (if not already loaded), and begin loading another page.
/// Loading the new page can be cancelled by the <see cref="DocumentLoading"/> event.
/// </remarks>
/// <value>The URL of the currently navigated page.</value>
Uri Url { get; set; }
/// <summary>
/// Loads the specified html string.
/// </summary>
/// <param name="html">Html string to load.</param>
/// <param name="baseUri">Base URI to load associated resources. Can be a url or file path.</param>
void LoadHtml(string html, Uri baseUri);
/// <summary>
/// Navigates the browser back to the previous page in history, if there is one.
/// </summary>
/// <seealso cref="CanGoBack"/>
void GoBack();
/// <summary>
/// Gets a value indicating whether the browser can go back to the previous page in history.
/// </summary>
/// <seealso cref="GoBack"/>
/// <value><c>true</c> if the browser can go back; otherwise, <c>false</c>.</value>
bool CanGoBack { get; }
/// <summary>
/// Navigates the browser forward to the next page in history, if there is one.
/// </summary>
/// <seealso cref="CanGoForward"/>
void GoForward();
/// <summary>
/// Gets a value indicating whether the browser can go forward to the next page.
/// </summary>
/// <seealso cref="GoForward"/>
/// <value><c>true</c> if the browser can go forward; otherwise, <c>false</c>.</value>
bool CanGoForward { get; }
/// <summary>
/// Stops loading the current page.
/// </summary>
/// <remarks>
/// You can determine if the page is finished loading by the <see cref="DocumentLoaded"/> event.
/// </remarks>
void Stop();
/// <summary>
/// Reloads the current page
/// </summary>
void Reload();
/// <summary>
/// Gets the document title of the current page.
/// </summary>
/// <value>The document title.</value>
string DocumentTitle { get; }
/// <summary>
/// Executes the specified javascript in the context of the current page, returning its result.
/// </summary>
/// <returns>The script to execute.</returns>
/// <param name="script">Script result.</param>
string ExecuteScript(string script);
/// <summary>
/// Shows the print dialog for the current page.
/// </summary>
/// <remarks>
/// This prompts the browser to print its contents.
/// </remarks>
void ShowPrintDialog();
/// <summary>
/// Gets or sets a value indicating whether the user can click to show the context menu.
/// </summary>
/// <remarks>
/// This is useful when using a browser control with content that should not be changed.
/// The context menu can show navigation items which may cause the page to reload so setting this
/// value to false will ensure the user can only interact with the page as is.
/// </remarks>
/// <value><c>true</c> if the context menu is enabled; otherwise, <c>false</c>.</value>
bool BrowserContextMenuEnabled { get; set; }
}
}
}
| |
//
// BaseTiffFile.cs:
//
// Author:
// Mike Gemuende ([email protected])
//
// Copyright (C) 2010 Mike Gemuende
//
// This library is free software; you can redistribute it and/or modify
// it under the terms of the GNU Lesser General Public License version
// 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful, but
// WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307
// USA
//
using System;
using TagLib.Image;
using TagLib.IFD;
namespace TagLib.Tiff
{
/// <summary>
/// This class extends <see cref="TagLib.Image.File" /> to provide some basic behavior
/// for Tiff based file formats.
/// </summary>
public abstract class BaseTiffFile : TagLib.Image.File
{
#region Public Properties
/// <summary>
/// Indicates if the current file is in big endian or little endian format.
/// </summary>
/// <remarks>
/// The method <see cref="ReadHeader()"/> must be called from a subclass to
/// properly initialize this property.
/// </remarks>
public bool IsBigEndian {
get; private set;
}
#endregion
#region Protected Properties
/// <summary>
/// The identifier used to recognize the file. This is 42 for most TIFF files.
/// </summary>
protected ushort Magic {
get; set;
}
#endregion
#region Constructors
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified path in the local file
/// system.
/// </summary>
/// <param name="path">
/// A <see cref="string" /> object containing the path of the
/// file to use in the new instance.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="path" /> is <see langword="null" />.
/// </exception>
protected BaseTiffFile (string path) : base (path)
{
Magic = 42;
}
/// <summary>
/// Constructs and initializes a new instance of <see
/// cref="File" /> for a specified file abstraction.
/// </summary>
/// <param name="abstraction">
/// A <see cref="IFileAbstraction" /> object to use when
/// reading from and writing to the file.
/// </param>
/// <exception cref="ArgumentNullException">
/// <paramref name="abstraction" /> is <see langword="null"
/// />.
/// </exception>
protected BaseTiffFile (IFileAbstraction abstraction) : base (abstraction)
{
Magic = 42;
}
#endregion
#region Protected Methods
/// <summary>
/// Reads and validates the TIFF header at the current position.
/// </summary>
/// <returns>
/// A <see cref="System.UInt32"/> with the offset value to the first
/// IFD contained in the file.
/// </returns>
/// <remarks>
/// This method should only be called, when the current read position is
/// the beginning of the file.
/// </remarks>
protected uint ReadHeader ()
{
// TIFF header:
//
// 2 bytes Indicating the endianess (II or MM)
// 2 bytes Tiff Magic word (usually 42)
// 4 bytes Offset to first IFD
ByteVector header = ReadBlock (8);
if (header.Count != 8)
throw new CorruptFileException ("Unexpected end of header");
string order = header.Mid (0, 2).ToString ();
if (order == "II") {
IsBigEndian = false;
} else if (order == "MM") {
IsBigEndian = true;
} else {
throw new CorruptFileException ("Unknown Byte Order");
}
if (header.Mid (2, 2).ToUShort (IsBigEndian) != Magic)
throw new CorruptFileException (String.Format ("TIFF Magic ({0}) expected", Magic));
uint first_ifd_offset = header.Mid (4, 4).ToUInt (IsBigEndian);
return first_ifd_offset;
}
/// <summary>
/// Reads IFDs starting from the given offset.
/// </summary>
/// <param name="offset">
/// A <see cref="System.UInt32"/> with the IFD offset to start
/// reading from.
/// </param>
protected void ReadIFD (uint offset)
{
ReadIFD (offset, -1);
}
/// <summary>
/// Reads a certain number of IFDs starting from the given offset.
/// </summary>
/// <param name="offset">
/// A <see cref="System.UInt32"/> with the IFD offset to start
/// reading from.
/// </param>
/// <param name="ifd_count">
/// A <see cref="System.Int32"/> with the number of IFDs to read.
/// </param>
protected void ReadIFD (uint offset, int ifd_count)
{
long length = 0;
try {
length = Length;
} catch (Exception) {
// Use a safety-value of 4 gigabyte.
length = 1073741824L * 4;
}
var ifd_tag = GetTag (TagTypes.TiffIFD, true) as IFDTag;
var reader = CreateIFDReader (this, IsBigEndian, ifd_tag.Structure, 0, offset, (uint) length);
reader.Read (ifd_count);
}
/// <summary>
/// Creates an IFD reader to parse the file.
/// </summary>
/// <param name="file">
/// A <see cref="File"/> to read from.
/// </param>
/// <param name="is_bigendian">
/// A <see cref="System.Boolean"/>, it must be true, if the data of the IFD should be
/// read as bigendian, otherwise false.
/// </param>
/// <param name="structure">
/// A <see cref="IFDStructure"/> that will be populated.
/// </param>
/// <param name="base_offset">
/// A <see cref="System.Int64"/> value describing the base were the IFD offsets
/// refer to. E.g. in Jpegs the IFD are located in an Segment and the offsets
/// inside the IFD refer from the beginning of this segment. So <paramref
/// name="base_offset"/> must contain the beginning of the segment.
/// </param>
/// <param name="ifd_offset">
/// A <see cref="System.UInt32"/> value with the beginning of the IFD relative to
/// <paramref name="base_offset"/>.
/// </param>
/// <param name="max_offset">
/// A <see cref="System.UInt32"/> value with maximal possible offset. This is to limit
/// the size of the possible data;
/// </param>
protected virtual IFDReader CreateIFDReader (BaseTiffFile file, bool is_bigendian, IFDStructure structure, long base_offset, uint ifd_offset, uint max_offset)
{
return new IFDReader (file, is_bigendian, structure, base_offset, ifd_offset, max_offset);
}
/// <summary>
/// Renders a TIFF header with the given offset to the first IFD.
/// The returned data has length 8.
/// </summary>
/// <param name="first_ifd_offset">
/// A <see cref="System.UInt32"/> with the offset to the first IFD
/// to be included in the header.
/// </param>
/// <returns>
/// A <see cref="ByteVector"/> with the rendered header of length 8.
/// </returns>
protected ByteVector RenderHeader (uint first_ifd_offset)
{
ByteVector data = new ByteVector ();
if (IsBigEndian)
data.Add ("MM");
else
data.Add ("II");
data.Add (ByteVector.FromUShort (Magic, IsBigEndian));
data.Add (ByteVector.FromUInt (first_ifd_offset, IsBigEndian));
return data;
}
#endregion
}
}
| |
using System;
using System.IO;
using System.ComponentModel;
using System.Collections.Generic;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using ChargeBee.Internal;
using ChargeBee.Api;
using ChargeBee.Models.Enums;
namespace ChargeBee.Models
{
public class Address : Resource
{
#region Methods
public static RetrieveRequest Retrieve(ApiConfig apiConfig)
{
string url = ApiUtil.BuildUrl(apiConfig, "addresses");
return new RetrieveRequest(url, HttpMethod.GET);
}
public static UpdateRequest Update(ApiConfig apiConfig)
{
string url = ApiUtil.BuildUrl(apiConfig, "addresses");
return new UpdateRequest(url, HttpMethod.POST);
}
#endregion
#region Properties
public string Label
{
get { return GetValue<string>("label", true); }
}
public string FirstName
{
get { return GetValue<string>("first_name", false); }
}
public string LastName
{
get { return GetValue<string>("last_name", false); }
}
public string Email
{
get { return GetValue<string>("email", false); }
}
public string Company
{
get { return GetValue<string>("company", false); }
}
public string Phone
{
get { return GetValue<string>("phone", false); }
}
public string Addr
{
get { return GetValue<string>("addr", false); }
}
public string ExtendedAddr
{
get { return GetValue<string>("extended_addr", false); }
}
public string ExtendedAddr2
{
get { return GetValue<string>("extended_addr2", false); }
}
public string City
{
get { return GetValue<string>("city", false); }
}
public string StateCode
{
get { return GetValue<string>("state_code", false); }
}
public string State
{
get { return GetValue<string>("state", false); }
}
public string Country
{
get { return GetValue<string>("country", false); }
}
public string Zip
{
get { return GetValue<string>("zip", false); }
}
public string SubscriptionId
{
get { return GetValue<string>("subscription_id", true); }
}
#endregion
#region Requests
public class RetrieveRequest : EntityRequest<RetrieveRequest>
{
public RetrieveRequest(string url, HttpMethod method)
: base(url, method)
{
}
public RetrieveRequest SubscriptionId(string subscriptionId)
{
m_params.Add("subscription_id", subscriptionId);
return this;
}
public RetrieveRequest Label(string label)
{
m_params.Add("label", label);
return this;
}
}
public class UpdateRequest : EntityRequest<UpdateRequest>
{
public UpdateRequest(string url, HttpMethod method)
: base(url, method)
{
}
public UpdateRequest SubscriptionId(string subscriptionId)
{
m_params.Add("subscription_id", subscriptionId);
return this;
}
public UpdateRequest Label(string label)
{
m_params.Add("label", label);
return this;
}
public UpdateRequest FirstName(string firstName)
{
m_params.AddOpt("first_name", firstName);
return this;
}
public UpdateRequest LastName(string lastName)
{
m_params.AddOpt("last_name", lastName);
return this;
}
public UpdateRequest Email(string email)
{
m_params.AddOpt("email", email);
return this;
}
public UpdateRequest Company(string company)
{
m_params.AddOpt("company", company);
return this;
}
public UpdateRequest Phone(string phone)
{
m_params.AddOpt("phone", phone);
return this;
}
public UpdateRequest Addr(string addr)
{
m_params.AddOpt("addr", addr);
return this;
}
public UpdateRequest ExtendedAddr(string extendedAddr)
{
m_params.AddOpt("extended_addr", extendedAddr);
return this;
}
public UpdateRequest ExtendedAddr2(string extendedAddr2)
{
m_params.AddOpt("extended_addr2", extendedAddr2);
return this;
}
public UpdateRequest City(string city)
{
m_params.AddOpt("city", city);
return this;
}
public UpdateRequest StateCode(string stateCode)
{
m_params.AddOpt("state_code", stateCode);
return this;
}
public UpdateRequest State(string state)
{
m_params.AddOpt("state", state);
return this;
}
public UpdateRequest Zip(string zip)
{
m_params.AddOpt("zip", zip);
return this;
}
public UpdateRequest Country(string country)
{
m_params.AddOpt("country", country);
return this;
}
}
#endregion
#region Subclasses
#endregion
}
}
| |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// This code is licensed under the MIT License (MIT).
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using System;
using Windows.Foundation;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
using Windows.UI.Xaml.Media;
using Windows.Media.DialProtocol;
using ScreenCasting.Data.Azure;
using ScreenCasting.Data.Common;
using Windows.Devices.Enumeration;
using System.Threading.Tasks;
using Windows.Media.Casting;
using ScreenCasting.Controls;
using ScreenCasting.Util;
using Windows.UI.ViewManagement;
using Windows.ApplicationModel.Core;
using Windows.UI.Core;
using Windows.Storage;
namespace ScreenCasting
{
public sealed partial class Scenario06 : Page
{
private const int MAX_RESULTS = 10;
private MainPage rootPage;
private DevicePicker picker = null;
private DeviceInformation activeDevice = null;
private object activeCastConnectionHandler = null;
private VideoMetaData video = null;
int thisViewId;
public Scenario06()
{
this.InitializeComponent();
rootPage = MainPage.Current;
//Subscribe to player events
player.MediaOpened += Player_MediaOpened;
player.MediaFailed += Player_MediaFailed;
player.CurrentStateChanged += Player_CurrentStateChanged;
// Get an Azure hosted video
AzureDataProvider dataProvider = new AzureDataProvider();
video = dataProvider.GetRandomVideo();
//Set the source on the player
rootPage.NotifyUser(string.Format("Opening '{0}'", video.Title), NotifyType.StatusMessage);
this.player.Source = video.VideoLink;
this.LicenseText.Text = "License: " + video.License;
//Configure the DIAL launch arguments for the current video
this.dial_launch_args_textbox.Text = string.Format("v={0}&t=0&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id);
//Subscribe for the clicked event on the custom cast button
((MediaTransportControlsWithCustomCastButton)this.player.TransportControls).CastButtonClicked += TransportControls_CastButtonClicked;
// Instantiate the Device Picker
picker = new DevicePicker();
//Hook up device selected event
picker.DeviceSelected += Picker_DeviceSelected;
//Hook up device disconnected event
picker.DisconnectButtonClicked += Picker_DisconnectButtonClicked;
//Hook up device disconnected event
picker.DevicePickerDismissed += Picker_DevicePickerDismissed;
//Add the DIAL Filter, so that the application only shows DIAL devices that have the application installed or advertise that they can install them.
//BUG: picker.Filter.SupportedDeviceSelectors.Add(DialDevice.GetDeviceSelector(this.dial_appname_textbox.Text));
picker.Filter.SupportedDeviceSelectors.Add("System.Devices.DevObjectType:=6 AND System.Devices.AepContainer.ProtocolIds:~~{0E261DE4-12F0-46E6-91BA-428607CCEF64} AND System.Devices.AepContainer.Categories:~~Multimedia.ApplicationLauncher.DIAL");
//Add the CAST API Filter, so that the application only shows Miracast, Bluetooth, DLNA devices that can render the video
// BUG: picker.Filter.SupportedDeviceSelectors.Add(await CastingDevice.GetDeviceSelectorFromCastingSourceAsync(player.GetAsCastingSource()));
// BUG: picker.Filter.SupportedDeviceSelectors.Add(CastingDevice.GetDeviceSelector(CastingPlaybackTypes.Video));
picker.Filter.SupportedDeviceSelectors.Add("System.Devices.InterfaceClassGuid:=\"{D0875FB4-2196-4c7a-A63D-E416ADDD60A1}\"" + " AND System.Devices.InterfaceEnabled:=System.StructuredQueryType.Boolean#True");
//Add projection manager filter
picker.Filter.SupportedDeviceSelectors.Add(ProjectionManager.GetDeviceSelector());
pvb.ProjectionStopping += Pvb_ProjectionStopping;
}
ProjectionViewBroker pvb = new ProjectionViewBroker();
private void TransportControls_CastButtonClicked(object sender, EventArgs e)
{
//Pause Current Playback
player.Pause();
rootPage.NotifyUser("Show Device Picker Button Clicked", NotifyType.StatusMessage);
//Get the custom transport controls
MediaTransportControlsWithCustomCastButton mtc = (MediaTransportControlsWithCustomCastButton)this.player.TransportControls;
//Retrieve the location of the casting button
GeneralTransform transform = mtc.CastButton.TransformToVisual(Window.Current.Content as UIElement);
Point pt = transform.TransformPoint(new Point(0, 0));
//Show the picker above our Show Device Picker button
picker.Show(new Rect(pt.X, pt.Y, mtc.CastButton.ActualWidth, mtc.CastButton.ActualHeight), Windows.UI.Popups.Placement.Above);
}
#region Windows.Devices.Enumeration.DevicePicker Methods
private async void Picker_DeviceSelected(DevicePicker sender, DeviceSelectedEventArgs args)
{
string deviceId = args.SelectedDevice.Id;
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
//Update the display status for the selected device to connecting.
try { picker.SetDisplayStatus(args.SelectedDevice, "Connecting", DevicePickerDisplayStatusOptions.ShowProgress); } catch { }
//The selectedDeviceInfo instance is needed to be able to update the picker.
DeviceInformation selectedDeviceInfo = args.SelectedDevice;
#if DEBUG
// The args.SelectedCastingDevice is proxied from the picker process. The picker process is
// dismissmed as soon as you break into the debugger. Creating a non-proxied version
// allows debugging since the proxied version stops working once the picker is dismissed.
selectedDeviceInfo = await DeviceInformation.CreateFromIdAsync(args.SelectedDevice.Id);
#endif
bool castSucceeded = false;
// If the ProjectionManager API did not work and the device id will have 'dial' in it.
castSucceeded = await TryLaunchDialAppAsync(selectedDeviceInfo);
// If it doesn't try the ProjectionManager API.
if (!castSucceeded)
castSucceeded = await TryProjectionManagerCastAsync(selectedDeviceInfo);
//If DIAL and ProjectionManager did not work for the selected device, try the CAST API
if (!castSucceeded)
castSucceeded = await TryCastMediaElementAsync(selectedDeviceInfo);
if (castSucceeded)
{
//Update the display status for the selected device. Try Catch in case the picker is not visible anymore.
try { picker.SetDisplayStatus(selectedDeviceInfo, "Connected", DevicePickerDisplayStatusOptions.ShowDisconnectButton); } catch { }
// Hide the picker now that all the work is completed. Try Catch in case the picker is not visible anymore.
try { picker.Hide(); } catch { }
}
else
{
//Show a retry button when connecting to the selected device failed.
try { picker.SetDisplayStatus(selectedDeviceInfo, "Connecting failed", DevicePickerDisplayStatusOptions.ShowRetryButton); } catch { }
}
});
}
private async void Picker_DevicePickerDismissed(DevicePicker sender, object args)
{
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
if (activeDevice == null)
{
player.Play();
}
});
}
private async void Picker_DisconnectButtonClicked(DevicePicker sender, DeviceDisconnectButtonClickedEventArgs args)
{
//Casting must occur from the UI thread. This dispatches the casting calls to the UI thread.
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, async () =>
{
rootPage.NotifyUser("Disconnect Button clicked", NotifyType.StatusMessage);
//Update the display status for the selected device.
sender.SetDisplayStatus(args.Device, "Disconnecting", DevicePickerDisplayStatusOptions.ShowProgress);
bool disconnected = false;
if (this.activeCastConnectionHandler is ProjectionViewBroker)
disconnected = TryStopProjectionManagerAsync((ProjectionViewBroker)activeCastConnectionHandler);
if (this.activeCastConnectionHandler is DialApp)
disconnected = await TryStopDialAppAsync((DialApp)activeCastConnectionHandler);
if (this.activeCastConnectionHandler is CastingConnection)
disconnected = await TryDisconnectCastingSessionAsync((CastingConnection)activeCastConnectionHandler);
if (disconnected)
{
//Update the display status for the selected device.
try { sender.SetDisplayStatus(args.Device, "Disconnected", DevicePickerDisplayStatusOptions.None); } catch { }
// Set the active device variables to null
activeDevice = null;
activeCastConnectionHandler = null;
//Hide the picker
sender.Hide();
}
else
{
//Update the display status for the selected device.
sender.SetDisplayStatus(args.Device, "Disconnect failed", DevicePickerDisplayStatusOptions.ShowDisconnectButton);
}
});
}
#endregion
#region ProjectionManager APIs
private async Task<bool> TryProjectionManagerCastAsync(DeviceInformation device)
{
bool projectionManagerCastAsyncSucceeded = false;
if ((activeDevice ==null && ProjectionManager.ProjectionDisplayAvailable && device == null) || device != null)
{
thisViewId = Windows.UI.ViewManagement.ApplicationView.GetForCurrentView().Id;
// If projection is already in progress, then it could be shown on the monitor again
// Otherwise, we need to create a new view to show the presentation
if (rootPage.ProjectionViewPageControl == null)
{
// First, create a new, blank view
var thisDispatcher = Window.Current.Dispatcher;
await CoreApplication.CreateNewView().Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
// ViewLifetimeControl is a wrapper to make sure the view is closed only
// when the app is done with it
rootPage.ProjectionViewPageControl = ViewLifetimeControl.CreateForCurrentView();
// Assemble some data necessary for the new page
pvb.MainPageDispatcher = thisDispatcher;
pvb.ProjectionViewPageControl = rootPage.ProjectionViewPageControl;
pvb.MainViewId = thisViewId;
// Display the page in the view. Note that the view will not become visible
// until "StartProjectingAsync" is called
var rootFrame = new Frame();
rootFrame.Navigate(typeof(ProjectionViewPage), pvb);
Window.Current.Content = rootFrame;
Window.Current.Activate();
});
}
try
{
// Start/StopViewInUse are used to signal that the app is interacting with the
// view, so it shouldn't be closed yet, even if the user loses access to it
rootPage.ProjectionViewPageControl.StartViewInUse();
try
{
rootPage.NotifyUser(string.Format("Starting projection of '{0}' on a second view '{1}' using ProjectionManager", video.Title, device.Name), NotifyType.StatusMessage);
await ProjectionManager.StartProjectingAsync(rootPage.ProjectionViewPageControl.Id, thisViewId, device);
}
catch (Exception ex)
{
if (!ProjectionManager.ProjectionDisplayAvailable)
throw ex;
}
if (pvb.ProjectedPage != null)
{
this.player.Pause();
await pvb.ProjectedPage.SetMediaSource(this.player.Source, this.player.Position);
}
if (device != null)
{
activeDevice = device;
activeCastConnectionHandler = pvb;
}
projectionManagerCastAsyncSucceeded = true;
rootPage.NotifyUser(string.Format("Displaying '{0}' on a second view '{1}' using ProjectionManager", video.Title, device.Name), NotifyType.StatusMessage);
}
catch (Exception)
{
rootPage.NotifyUser("The projection view is being disposed", NotifyType.ErrorMessage);
}
ApplicationView.GetForCurrentView().ExitFullScreenMode();
}
return projectionManagerCastAsyncSucceeded;
}
private bool TryStopProjectionManagerAsync(ProjectionViewBroker broker)
{
broker.ProjectedPage.StopProjecting();
return true;
}
private async void Pvb_ProjectionStopping(object sender, EventArgs e)
{
ProjectionViewBroker broker = sender as ProjectionViewBroker;
TimeSpan position = broker.ProjectedPage.Player.Position;
Uri source = broker.ProjectedPage.Player.Source;
await rootPage.Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Resuming playback on the first screen", NotifyType.StatusMessage);
this.player.Source = source;
this.player.Position = position;
this.player.Play();
rootPage.ProjectionViewPageControl = null;
});
}
#endregion
#region Windows.Media.Casting APIs
private async Task<bool> TryCastMediaElementAsync(DeviceInformation device)
{
bool castMediaElementSucceeded = false;
//Verify whether the selected device supports DLNA, Bluetooth, or Miracast.
rootPage.NotifyUser(string.Format("Checking to see if device {0} supports Miracast, Bluetooth, or DLNA", device.Name), NotifyType.StatusMessage);
CastingConnection connection = null;
//Check to see whether we are casting to the same device
if (activeDevice != null && device.Id == activeDevice.Id)
connection = activeCastConnectionHandler as CastingConnection;
else // if not casting to the same device reset the active device related variables.
{
activeDevice = null;
activeCastConnectionHandler = null;
}
// If we can re-use the existing connection
if (connection == null || connection.State == CastingConnectionState.Disconnected || connection.State == CastingConnectionState.Disconnecting)
{
CastingDevice castDevice = null;
activeDevice = null;
//Try to create a CastingDevice instannce. If it doesn't succeed, the selected device does not support playback of the video source.
rootPage.NotifyUser(string.Format("Attempting to resolve casting device for '{0}'", device.Name), NotifyType.StatusMessage);
try { castDevice = await CastingDevice.FromIdAsync(device.Id); } catch { }
if (castDevice == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' does not support playback of this media", device.Name), NotifyType.StatusMessage);
}
else
{
//Create a casting conneciton from our selected casting device
rootPage.NotifyUser(string.Format("Creating connection for '{0}'", device.Name), NotifyType.StatusMessage);
connection = castDevice.CreateCastingConnection();
//Hook up the casting events
connection.ErrorOccurred += Connection_ErrorOccurred;
connection.StateChanged += Connection_StateChanged;
}
//Cast the content loaded in the media element to the selected casting device
rootPage.NotifyUser(string.Format("Casting to '{0}'", device.Name), NotifyType.StatusMessage);
CastingSource source = null;
// Get the casting source
try { source = player.GetAsCastingSource(); } catch { }
if (source == null)
{
rootPage.NotifyUser(string.Format("Failed to get casting source for video '{0}'", video.Title), NotifyType.ErrorMessage);
}
else
{
CastingConnectionErrorStatus status = await connection.RequestStartCastingAsync(source);
if (status == CastingConnectionErrorStatus.Succeeded)
{
//Remember the device to which casting succeeded
activeDevice = device;
//Remember the current active connection.
activeCastConnectionHandler = connection;
castMediaElementSucceeded = true;
player.Play();
}
else
{
rootPage.NotifyUser(string.Format("Failed to cast to '{0}'", device.Name), NotifyType.ErrorMessage);
}
}
}
return castMediaElementSucceeded;
}
private async void Connection_StateChanged(CastingConnection sender, object args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Casting Connection State Changed: " + sender.State, NotifyType.StatusMessage);
});
}
private async void Connection_ErrorOccurred(CastingConnection sender, CastingConnectionErrorOccurredEventArgs args)
{
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal, () =>
{
rootPage.NotifyUser("Casting Error Occured: " + args.Message, NotifyType.ErrorMessage);
activeDevice = null;
activeCastConnectionHandler = null;
});
}
private async Task<bool> TryDisconnectCastingSessionAsync(CastingConnection connection)
{
bool disconnected = false;
//Disconnect the casting session
CastingConnectionErrorStatus status = await connection.DisconnectAsync();
if (status == CastingConnectionErrorStatus.Succeeded)
{
rootPage.NotifyUser("Connection disconnected successfully.", NotifyType.StatusMessage);
disconnected = true;
}
else
{
rootPage.NotifyUser(string.Format("Failed to disconnect connection with reason {0}.", status.ToString()), NotifyType.ErrorMessage);
}
return disconnected;
}
#endregion
#region Windows.Media.DialProtocol APIs
private async Task<bool> TryLaunchDialAppAsync(DeviceInformation device)
{
bool dialAppLaunchSucceeded = false;
//Update the launch arguments to include the Position
this.dial_launch_args_textbox.Text = string.Format("v={0}&t={1}&pairingCode=E4A8136D-BCD3-45F4-8E49-AE01E9A46B5F", video.Id, player.Position.Ticks);
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("Checking to see if device {0} supports DIAL", device.Name), NotifyType.StatusMessage);
DialDevice dialDevice = null;
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("Attempting to resolve DIAL device for '{0}'", device.Name), NotifyType.StatusMessage);
string[] newIds = (string[])device.Properties["{0BBA1EDE-7566-4F47-90EC-25FC567CED2A} 2"];
if (newIds.Length > 0)
{
string deviceId = newIds[0];
try { dialDevice = await DialDevice.FromIdAsync(deviceId); } catch { }
}
if (dialDevice == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' does not support DIAL", device.Name), NotifyType.StatusMessage);
}
else
{
//Get the DialApp object for the specific application on the selected device
DialApp app = dialDevice.GetDialApp(this.dial_appname_textbox.Text);
if (app == null)
{
//Try to create a DIAL device. If it doesn't succeed, the selected device does not support DIAL.
rootPage.NotifyUser(string.Format("'{0}' cannot find app with ID '{1}'", device.Name, this.dial_appname_textbox.Text), NotifyType.StatusMessage);
}
else
{
rootPage.NotifyUser(string.Format("Attempting to launch '{0}'", app.AppName), NotifyType.StatusMessage);
//Launch the application on the 1st screen device
DialAppLaunchResult result = await app.RequestLaunchAsync(this.dial_launch_args_textbox.Text);
//Verify to see whether the application was launched
if (result == DialAppLaunchResult.Launched)
{
//Remember the device to which casting succeeded
activeDevice = device;
//DIAL is sessionsless but the DIAL app allows us to get the state and "disconnect".
//Disconnect in the case of DIAL is equivalenet to stopping the app.
activeCastConnectionHandler = app;
rootPage.NotifyUser(string.Format("Launched '{0}'", app.AppName), NotifyType.StatusMessage);
//This is where you will need to add you application specific communication between your 1st and 2nd screen applications
//...
dialAppLaunchSucceeded = true;
}
}
}
return dialAppLaunchSucceeded;
}
private async Task<bool> TryStopDialAppAsync(DialApp app)
{
bool stopped = false;
//Get the current application state
DialAppStateDetails stateDetails = await app.GetAppStateAsync();
switch (stateDetails.State)
{
case DialAppState.NetworkFailure:
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Network Failure while getting application state", NotifyType.ErrorMessage);
break;
}
case DialAppState.Stopped:
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Application was already stopped.", NotifyType.StatusMessage);
break;
}
default:
{
DialAppStopResult result = await app.StopAsync();
if (result == DialAppStopResult.Stopped)
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser("Application stopped successfully.", NotifyType.StatusMessage);
}
else
{
if (result == DialAppStopResult.StopFailed || result == DialAppStopResult.NetworkFailure)
{
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser(string.Format("Error occured trying to stop application. Status: '{0}'", result.ToString()), NotifyType.StatusMessage);
}
else //in case of DialAppStopResult.OperationNotSupported, there is not much more you can do. You could implement your own
// mechanism to stop the application on that device.
{
stopped = true;
// In case getting the application state failed because of a network failure, you could add retry logic
rootPage.NotifyUser(string.Format("Stop is not supported by device: '{0}'", activeDevice.Name), NotifyType.ErrorMessage);
}
}
break;
}
}
return stopped;
}
#endregion
#region Media Element Status Methods
private void Player_CurrentStateChanged(object sender, RoutedEventArgs e)
{
// Update status
rootPage.NotifyUser(string.Format("{0} '{1}'", this.player.CurrentState, video.Title), NotifyType.StatusMessage);
}
private void Player_MediaFailed(object sender, ExceptionRoutedEventArgs e)
{
rootPage.NotifyUser(string.Format("Failed to load '{0}'", video.Title), NotifyType.ErrorMessage);
}
private void Player_MediaOpened(object sender, RoutedEventArgs e)
{
rootPage.NotifyUser(string.Format("Openend '{0}'", video.Title), NotifyType.StatusMessage);
player.Play();
}
#endregion
protected override void OnNavigatedTo(NavigationEventArgs e)
{
rootPage = MainPage.Current;
}
}
}
| |
//#define PROFILE
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
using UnityEditor;
using UnityEngine;
using Vexe.Editor.Types;
using Vexe.Editor.Windows;
using Vexe.Runtime.Extensions;
using Vexe.Runtime.Helpers;
using Vexe.Runtime.Types;
using UnityObject = UnityEngine.Object;
namespace Vexe.Editor.Drawers
{
public abstract class SequenceDrawer<TSequence, TElement> : ObjectDrawer<TSequence> where TSequence : IList<TElement>
{
private readonly Type _elementType;
private List<EditorMember> _elements;
private SequenceOptions _options;
private bool _shouldDrawAddingArea;
private int _newSize;
private int _advancedKey;
private int _lastUpdatedCount = -1;
private Attribute[] _perItemAttributes;
private TextFilter _filter;
private string _originalDisplay;
public bool UpdateCount = true;
private bool isAdvancedChecked
{
get { return prefs[_advancedKey]; }
set { prefs[_advancedKey] = value; }
}
protected abstract TSequence GetNew();
public SequenceDrawer()
{
_elementType = typeof(TElement);
_elements = new List<EditorMember>();
}
protected override void Initialize()
{
var displayAttr = attributes.GetAttribute<DisplayAttribute>();
_options = new SequenceOptions(displayAttr != null ? displayAttr.SeqOpt : Seq.None);
if (_options.Readonly)
displayText += " (Readonly)";
_advancedKey = RuntimeHelper.CombineHashCodes(id, "advanced");
_shouldDrawAddingArea = !_options.Readonly && _elementType.IsA<UnityObject>();
var perItem = attributes.GetAttribute<PerItemAttribute>();
if (perItem != null)
{
if (perItem.ExplicitAttributes == null)
_perItemAttributes = attributes.Where(x => !(x is PerItemAttribute)).ToArray();
else _perItemAttributes = attributes.Where(x => perItem.ExplicitAttributes.Contains(x.GetType().Name.Replace("Attribute", ""))).ToArray();
}
if (_options.Filter)
_filter = new TextFilter(null, id, true, prefs, null);
_originalDisplay = displayText;
if (memberValue == null)
memberValue = GetNew();
member.CollectionCount = memberValue.Count;
}
public override void OnGUI()
{
if (memberValue == null)
memberValue = GetNew();
member.CollectionCount = memberValue.Count;
if (UpdateCount && _lastUpdatedCount != memberValue.Count)
{
_lastUpdatedCount = memberValue.Count;
displayText = Regex.Replace(_originalDisplay, @"\$count", _lastUpdatedCount.ToString());
}
bool showAdvanced = _options.Advanced && !_options.Readonly;
// header
using (gui.Horizontal())
{
foldout = gui.Foldout(displayText, foldout, Layout.Auto);
if (_options.Filter)
_filter.Field(gui, 70f);
gui.FlexibleSpace();
if (showAdvanced)
isAdvancedChecked = gui.CheckButton(isAdvancedChecked, "advanced mode");
if (!_options.Readonly)
{
using (gui.State(memberValue.Count > 0))
{
if (gui.ClearButton("elements"))
{
Clear();
}
if (gui.RemoveButton("last element"))
{
RemoveLast();
}
}
if (gui.AddButton("element", MiniButtonStyle.ModRight))
{
AddValue();
}
}
}
if (!foldout)
return;
if (memberValue.IsEmpty())
{
using (gui.Indent())
gui.HelpBox("Sequence is empty");
}
else
{
// body
using (gui.Vertical(_options.GuiBox ? GUI.skin.box : GUIStyle.none))
{
// advanced area
if (isAdvancedChecked)
{
using (gui.Indent((GUI.skin.box)))
{
using (gui.Horizontal())
{
_newSize = gui.Int("New size", _newSize);
if (gui.MiniButton("c", "Commit", MiniButtonStyle.ModRight))
{
if (_newSize != memberValue.Count)
memberValue.AdjustSize(_newSize, RemoveAt, AddValue);
}
}
using (gui.Horizontal())
{
gui.Label("Commands");
if (gui.MiniButton("Shuffle", "Shuffle list (randomize the order of the list's elements", (Layout)null))
Shuffle();
if (gui.MoveDownButton())
memberValue.Shift(true);
if (gui.MoveUpButton())
memberValue.Shift(false);
if (!_elementType.IsValueType && gui.MiniButton("N", "Filter nulls"))
{
for (int i = memberValue.Count - 1; i > -1; i--)
if (memberValue[i] == null)
RemoveAt(i);
}
}
}
}
using (gui.Indent(_options.GuiBox ? GUI.skin.box : GUIStyle.none))
{
#if PROFILE
Profiler.BeginSample("Sequence Elements");
#endif
for (int iLoop = 0; iLoop < memberValue.Count; iLoop++)
{
var i = iLoop;
var elementValue = memberValue[i];
if (_filter != null && elementValue != null)
{
string elemStr = elementValue.ToString();
if (!_filter.IsMatch(elemStr))
continue;
}
using (gui.Horizontal())
{
if (_options.LineNumbers)
gui.NumericLabel(i);
var previous = elementValue;
gui.BeginCheck();
{
using (gui.Vertical())
{
var element = GetElement(i);
using (gui.If(!_options.Readonly && _elementType.IsNumeric(), gui.LabelWidth(15f)))
gui.Member(element, @ignoreComposition: _perItemAttributes == null);
}
}
if (gui.HasChanged())
{
if (_options.Readonly)
{
memberValue[i] = previous;
}
else if (_options.UniqueItems)
{
int occurances = 0;
for (int k = 0; k < memberValue.Count; k++)
{
if (memberValue[i].GenericEquals(memberValue[k]))
{
occurances++;
if (occurances > 1)
{
memberValue[i] = previous;
break;
}
}
}
}
}
if (isAdvancedChecked)
{
var c = elementValue as Component;
var go = c == null ? elementValue as GameObject : c.gameObject;
if (go != null)
gui.InspectButton(go);
if (showAdvanced)
{
if (gui.MoveDownButton())
{
MoveElementDown(i);
}
if (gui.MoveUpButton())
{
MoveElementUp(i);
}
}
}
if (!_options.Readonly && _options.PerItemRemove && gui.RemoveButton("element", MiniButtonStyle.ModRight))
{
RemoveAt(i);
}
///Only valid for Classes implementing ICloneable
if (typeof(ICloneable).IsAssignableFrom(_elementType) && elementValue != null)
{
if (!_options.Readonly && _options.PerItemDuplicate && gui.AddButton("element", MiniButtonStyle.ModRight))
{
ICloneable _elementToClone = (ICloneable)elementValue;
TElement cloned = (TElement)_elementToClone.Clone();
AddValue(cloned);
}
}
}
}
#if PROFILE
Profiler.EndSample();
#endif
}
}
}
// footer
if (_shouldDrawAddingArea)
{
Action<UnityObject> addOnDrop = obj =>
{
var go = obj as GameObject;
object value;
if (go != null)
{
value = _elementType == typeof(GameObject) ? (UnityObject)go : go.GetComponent(_elementType);
}
else value = obj;
AddValue((TElement)value);
};
using (gui.Indent())
{
gui.DragDropArea<UnityObject>(
@label: "+Drag-Drop+",
@labelSize: 14,
@style: EditorStyles.toolbarButton,
@canSetVisualModeToCopy: dragObjects => dragObjects.All(obj =>
{
var go = obj as GameObject;
var isGo = go != null;
if (_elementType == typeof(GameObject))
{
return isGo;
}
return isGo ? go.GetComponent(_elementType) != null : obj.GetType().IsA(_elementType);
}),
@cursor: MouseCursor.Link,
@onDrop: addOnDrop,
@onMouseUp: () => SelectionWindow.Show(new Tab<UnityObject>(
@getValues: () => UnityObject.FindObjectsOfType(_elementType),
@getCurrent: () => null,
@setTarget: item =>
{
AddValue((TElement)(object)item);
},
@getValueName: value => value.name,
@title: _elementType.Name + "s")),
@preSpace: 2f,
@postSpace: 35f,
@height: 15f
);
}
gui.Space(3f);
}
}
private EditorMember GetElement(int index)
{
if (index >= _elements.Count)
{
var element = EditorMember.WrapIListElement(
@attributes: _perItemAttributes,
@elementName: _elementType.IsNumeric() && !_options.Readonly ? "~" : string.Empty,
@elementType: typeof(TElement),
@elementId: RuntimeHelper.CombineHashCodes(id, index)
);
element.InitializeIList(memberValue, index, rawTarget, unityTarget);
_elements.Add(element);
return element;
}
var e = _elements[index];
e.InitializeIList(memberValue, index, rawTarget, unityTarget);
return e;
}
// List ops
#region
protected abstract void Clear();
protected abstract void RemoveAt(int atIndex);
protected abstract void Insert(int index, TElement value);
private void Shuffle()
{
memberValue.Shuffle();
}
private void MoveElementDown(int i)
{
memberValue.MoveElementDown(i);
}
private void MoveElementUp(int i)
{
memberValue.MoveElementUp(i);
}
private void RemoveLast()
{
RemoveAt(memberValue.Count - 1);
}
private void AddValue(TElement value)
{
Insert(memberValue.Count, value);
}
private void AddValue()
{
AddValue((TElement)_elementType.GetDefaultValueEmptyIfString());
}
#endregion
private struct SequenceOptions
{
public readonly bool Readonly;
public readonly bool Advanced;
public readonly bool LineNumbers;
public readonly bool PerItemRemove;
public readonly bool PerItemDuplicate;
public readonly bool GuiBox;
public readonly bool UniqueItems;
public readonly bool Filter;
public SequenceOptions(Seq options)
{
Readonly = options.HasFlag(Seq.Readonly);
Advanced = options.HasFlag(Seq.Advanced);
LineNumbers = options.HasFlag(Seq.LineNumbers);
PerItemRemove = options.HasFlag(Seq.PerItemRemove);
PerItemDuplicate = options.HasFlag(Seq.PerItemDuplicate);
GuiBox = options.HasFlag(Seq.GuiBox);
UniqueItems = options.HasFlag(Seq.UniqueItems);
Filter = options.HasFlag(Seq.Filter);
}
}
}
public class ArrayDrawer<T> : SequenceDrawer<T[], T>
{
protected override T[] GetNew()
{
return new T[0];
}
protected override void RemoveAt(int atIndex)
{
memberValue = memberValue.ToList().RemoveAtAndGet(atIndex).ToArray();
}
protected override void Clear()
{
memberValue = memberValue.ToList().ClearAndGet().ToArray();
}
protected override void Insert(int index, T value)
{
memberValue = memberValue.ToList().InsertAndGet(index, value).ToArray();
foldout = true;
}
}
public class ListDrawer<T> : SequenceDrawer<List<T>, T>
{
protected override List<T> GetNew()
{
return new List<T>();
}
protected override void RemoveAt(int index)
{
memberValue.RemoveAt(index);
}
protected override void Clear()
{
memberValue.Clear();
}
protected override void Insert(int index, T value)
{
memberValue.Insert(index, value);
foldout = true;
}
}
}
| |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
namespace Eto.Parse
{
/// <summary>
/// Base parser class to define a parsing rule
/// </summary>
/// <remarks>
/// All parsers should derive from this class to define the various ways to parse text.
/// There are other base parsers that define base functionality such as a <see cref="ListParser"/>
/// for parsers that contain a list of children parsers, or <see cref="UnaryParser"/> for parsers
/// that contain a single child.
/// </remarks>
public abstract partial class Parser : ICloneable
{
bool hasNamedChildren;
ParseMode mode;
string name;
bool addError;
bool addErrorSet;
bool addMatch;
bool addMatchSet;
enum ParseMode
{
Simple,
NameOrError,
NamedChildren
}
#region Properties
/// <summary>
/// Gets or sets the name of the match added to the match result tree
/// </summary>
/// <remarks>
/// When you set this property, it affects the match result tree returned from the <see cref="Grammar.Match(string)"/>
/// method. Each parser that is named will get a node entry in the match tree if it has succesfully matched
/// on the input string. This allows you to
///
/// If this is set to <c>null</c>, this parser will not add a node to the match tree, but any named
/// children will still add to the match tree (if any).
///
/// If you set the name, the parser will automatically set <see cref="Parser.AddError"/> to <c>true</c>
/// to give back information when this parser does not match, unless AddError has already been set
/// to something else explicitly.
/// </remarks>
/// <value>The name to give the match in the match result tree</value>
public string Name
{
get { return name; }
set
{
name = value;
if (!addErrorSet && name != null)
addError = true;
if (!addMatchSet && name != null)
addMatch = true;
}
}
/// <summary>
/// Gets or sets the default separator to use for parsers that support a separator
/// </summary>
/// <value>The default separator.</value>
public static Parser DefaultSeparator { get; set; }
/// <summary>
/// Gets or sets a value indicating that this parser should add to the errors list when not matched
/// </summary>
/// <value><c>true</c> to add errors; otherwise, <c>false</c>.</value>
public bool AddError
{
get { return addError; }
set
{
addError = value;
addErrorSet = true;
}
}
public bool AddMatch
{
get { return addMatch; }
set
{
addMatch = value;
addMatchSet = true;
}
}
internal bool Reusable { get; set; }
/// <summary>
/// Gets a name of the parser used to describe its intent, used for the error message or display tree
/// </summary>
/// <value>The descriptive name</value>
public virtual string DescriptiveName
{
get
{
if (this.name != null)
return this.name;
var type = GetType();
var name = type.Name;
if (type.GetTypeInfo().Assembly == typeof(Parser).GetTypeInfo().Assembly && name.EndsWith("Parser", StringComparison.Ordinal))
name = name.Substring(0, name.LastIndexOf("Parser", StringComparison.Ordinal));
return name;
}
}
/// <summary>
/// Gets a value indicating that this parser has named children
/// </summary>
/// <remarks>
/// This is useful to know when to use <see cref="ParseArgs.Push"/> before parsing children, and
/// <see cref="ParseArgs.PopFailed"/> / <see cref="ParseArgs.PopSuccess"/> after.
///
/// Using Push/Pop methods allow you to keep track of and discard (or keep) child matches based
/// on the success or failure.
///
/// This is set during initialization of the grammar before the first parse is performed.
/// </remarks>
protected bool HasNamedChildren { get { return hasNamedChildren; } }
#endregion
#region Events
/// <summary>
/// Event to handle when this parser is matched
/// </summary>
/// <remarks>
/// This event is fired only for matches that have a <see cref="Parser.Name"/> defined.
/// </remarks>
public event Action<Match> Matched;
/// <summary>
/// Raises the <see cref="Matched"/> event
/// </summary>
/// <param name="match">Match</param>
protected virtual void OnMatched(Match match)
{
if (Matched != null)
Matched(match);
}
internal void TriggerMatch(Match match)
{
OnMatched(match);
}
/// <summary>
/// Event to handle before this parser is matched
/// </summary>
public event Action<Match> PreMatch;
/// <summary>
/// Raises the <see cref="PreMatch"/> event
/// </summary>
/// <param name="match">Match</param>
protected virtual void OnPreMatch(Match match)
{
if (PreMatch != null)
PreMatch(match);
}
internal void TriggerPreMatch(Match match)
{
OnPreMatch(match);
}
#endregion
/// <summary>
/// Initializes a new instance of the <see cref="Eto.Parse.Parser"/> class.
/// </summary>
protected Parser()
{
}
/// <summary>
/// Initializes a new copy of the <see cref="Eto.Parse.Parser"/> class
/// </summary>
/// <param name="other">Parser to copy</param>
/// <param name="args">Arguments for the copy</param>
protected Parser(Parser other, ParserCloneArgs args)
{
Name = other.Name;
addMatch = other.addMatch;
addMatchSet = other.addMatchSet;
addError = other.addError;
addErrorSet = other.addErrorSet;
args.Add(other, this);
}
/// <summary>
/// Gets an enumeration of all child parsers of this instance
/// </summary>
public IEnumerable<Parser> Children
{
get
{
return Scan(null);
}
}
internal IEnumerable<Parser> Scan(Action<Parser> action = null, Func<Parser, bool> filter = null)
{
var visited = new HashSet<Parser>();
var stack = new Stack<Parser>();
stack.Push(this);
while (stack.Count > 0)
{
var current = stack.Pop();
action?.Invoke(current);
visited.Add(current);
foreach (var item in current.GetChildren())
{
if (!visited.Contains(item) && (filter == null || filter(item)))
stack.Push(item);
}
}
return visited;
}
protected virtual IEnumerable<Parser> GetChildren()
{
yield break;
}
/// <summary>
/// Gets the error message to display for this parser
/// </summary>
/// <remarks>
/// By default, this will use the DescriptiveName
/// </remarks>
/// <returns>The error message to display when not matched</returns>
public virtual string GetErrorMessage(ParserErrorArgs args)
{
return DescriptiveName;
}
public string GetErrorMessage(bool detailed = false)
{
return GetErrorMessage(new ParserErrorArgs(detailed));
}
/// <summary>
/// Parses the input at the current position
/// </summary>
/// <remarks>
/// Implementors of a Parser should implement <see cref="InnerParse"/> to perform the logic of their parser.
/// </remarks>
/// <param name="args">Parsing arguments</param>
/// <returns>The length of the successfully matched value (can be zero), or -1 if not matched</returns>
public int Parse(ParseArgs args)
{
if (mode == ParseMode.Simple)
{
var match = InnerParse(args);
if (match >= 0)
return match;
args.SetChildError();
return match;
}
else if (mode == ParseMode.NamedChildren)
{
args.Push();
var pos = args.Scanner.Position;
var match = InnerParse(args);
if (match < 0)
{
args.PopFailed();
if (AddError)
{
args.AddError(this);
return -1;
}
args.SetChildError();
return -1;
}
if (AddMatch)
{
args.PopMatch(this, pos, match);
return match;
}
args.PopSuccess();
return match;
}
else // if (mode == ParseMode.NameOrError)
{
var pos = args.Scanner.Position;
var match = InnerParse(args);
if (match < 0)
{
if (!AddError)
{
args.SetChildError();
}
else
{
args.AddError(this);
}
}
else if (AddMatch)
{
args.AddMatch(this, pos, match);
}
return match;
}
}
/// <summary>
/// Override to implement the main parsing logic for this parser
/// </summary>
/// <remarks>
/// Never call this method directly, always call <see cref="Parse"/> when calling parse routines.
/// </remarks>
/// <returns>The length of the successfully matched value (can be zero), or -1 if not matched</returns>
/// <param name="args">Parsing arguments</param>
protected abstract int InnerParse(ParseArgs args);
bool initialized;
/// <summary>
/// Called to initialize the parser when used in a grammar
/// </summary>
/// <remarks>
/// This is used to perform certain tasks like caching information for performance, or to deal with
/// things like left recursion in the grammar.
/// </remarks>
/// <param name="args">Initialization arguments</param>
public void Initialize(ParserInitializeArgs args)
{
if (!initialized && args.Push(this))
{
initialized = true;
var parent = args.Parent;
args.Parent = this;
InnerInitialize(args);
args.Parent = parent;
hasNamedChildren = (Children.Any(r => r.AddMatch || r.hasNamedChildren));
var parentNamed = false;
if (parent != null && hasNamedChildren)
{
var parentHasMatches = parent.Scan(filter: p => p != this).Any(p => p.AddMatch);
//parentNamed = parent.Scan(filter: p => p != this).Any(p => p.AddMatch);
parentNamed = parent.AddMatch;
}
mode = (hasNamedChildren && (AddMatch/* || parentNamed*/)) ? ParseMode.NamedChildren : AddMatch || AddError ? ParseMode.NameOrError : ParseMode.Simple;
args.Pop();
}
}
protected virtual void InnerInitialize(ParserInitializeArgs args)
{
}
/// <summary>
/// Gets a value indicating that the specified <paramref name="parser"/> is contained within this instance
/// </summary>
/// <param name="parser">Parser to search for</param>
public bool Contains(Parser parser)
{
return Contains(new ParserContainsArgs(parser));
}
/// <summary>
/// Gets a value indicating that a parser is contained within this instance
/// </summary>
/// <param name="args">Arguments specifying which parser to search for and recursion</param>
public virtual bool Contains(ParserContainsArgs args)
{
return args.Parser == this;
}
/// <summary>
/// Determines whether this instance is left recursive with the specified parser
/// </summary>
/// <returns><c>true</c> if this instance is left recursive the specified parser; otherwise, <c>false</c>.</returns>
/// <param name="parser">Parser.</param>
public bool IsLeftRecursive(Parser parser)
{
return IsLeftRecursive(new ParserContainsArgs(parser));
}
/// <summary>
/// Determines whether this instance is left recursive with the specified parser
/// </summary>
/// <remarks>
/// This variant can be overridden by implementors to determine left recursion. Use the <paramref name="args"/>
/// to ensure infinite recursion does not occur using Push/Pop.
/// </remarks>
/// <returns><c>true</c> if this instance is left recursive the specified parser; otherwise, <c>false</c>.</returns>
/// <param name="args">Arguments for finding the left recursion</param>
public virtual bool IsLeftRecursive(ParserContainsArgs args)
{
return object.ReferenceEquals(args.Parser, this);
}
public IEnumerable<Parser> Find(string parserId)
{
return Find(new ParserFindArgs(parserId));
}
public virtual IEnumerable<Parser> Find(ParserFindArgs args)
{
if (string.Equals(Name, args.ParserId, StringComparison.Ordinal))
yield return this;
}
public Parser this [string parserId]
{
get { return Find(parserId).FirstOrDefault(); }
}
public Parser Clone()
{
return Clone(new ParserCloneArgs());
}
public abstract Parser Clone(ParserCloneArgs args);
object ICloneable.Clone()
{
return Clone();
}
public void Replace(ParserReplaceArgs args)
{
if (args.Push(this))
{
InnerReplace(args);
//args.Pop();
}
}
protected virtual void InnerReplace(ParserReplaceArgs args)
{
}
/// <summary>
/// Sets the <see cref="AddError"/> flag on all children of this parser
/// </summary>
/// <param name="addError">Value to set the AddError flag to</param>
/// <param name="name">Name of the parser(s) to match, or null to set all children</param>
public void SetError(bool addError, string name = null)
{
var children = Children;
if (name != null)
children = children.Where(r => r.Name == name);
foreach (var item in children)
item.AddError = addError;
}
/// <summary>
/// Sets the <see cref="AddError"/> flag on all children of this parser
/// </summary>
/// <param name="addError">Value to set the AddError flag to</param>
/// <param name="name">Name of the parser(s) to match, or null to set all children</param>
/// <typeparam name="T">The type of parser to update</typeparam>
public void SetError<T>(bool addError, string name = null)
where T: Parser
{
var children = Children.OfType<T>();
if (name != null)
children = children.Where(r => r.Name == name);
foreach (var item in children)
item.AddError = addError;
}
/// <summary>
/// Gets the object value of the parser for the specified match
/// </summary>
/// <remarks>
/// Specialized parsers such as <see cref="Parsers.NumberParser"/>, <see cref="Parsers.StringParser"/>, etc
/// can return a type-specific value from its string representation using this method.
///
/// For example, the NumberParser can return an int, decimal, double, etc. and the StringParser
/// can process escape sequences or double quoted values.
///
/// To get the value from a specified text fragment, use <see cref="GetValue(string)"/>.
///
/// Implementors of parsers can override this (or preferrably <see cref="GetValue(string)"/>) to
/// provide special logic to get the translated object value.
/// </remarks>
/// <returns>The translated object value from the range specified in the <paramref name="match"/></returns>
/// <param name="match">Match to get the object value for</param>
public virtual object GetValue(Match match)
{
return GetValue(match.Text);
}
/// <summary>
/// Gets the object value of the parser for the specified text representation
/// </summary>
/// <remarks>
/// Specialized parsers such as <see cref="Parsers.NumberParser"/>, <see cref="Parsers.StringParser"/>, etc
/// can return a type-specific value from its string representation using this method.
///
/// For example, the NumberParser can return an int, decimal, double, etc. and the StringParser
/// can process escape sequences or double quoted values.
///
/// To get the value from a specified <see cref="Match"/>, use <see cref="GetValue(Match)"/> instead.
///
/// Implementors of parsers can override this to provide special logic to get the translated object value.
/// </remarks>
/// <returns>The translated object value from the specified <paramref name="text"/></returns>
/// <param name="text">Text representation to translate to an object value</param>
public virtual object GetValue(string text)
{
return text;
}
}
}
| |
/*
* Copyright 2013 ThirdMotion, 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.
*/
/**
* @class strange.extensions.dispatcher.eventdispatcher.impl.EventDispatcher
*
* A Dispatcher that uses IEvent to send messages.
*
* Whenever the Dispatcher executes a `Dispatch()`, observers will be
* notified of any event (Key) for which they have registered.
*
* EventDispatcher dispatches TmEvent : IEvent.
*
* The EventDispatcher is the only Dispatcher currently released with Strange
* (though by separating EventDispatcher from Dispatcher I'm obviously
* signalling that I don't think it's the only possible one).
*
* EventDispatcher is both an ITriggerProvider and an ITriggerable.
*
* @see strange.extensions.dispatcher.eventdispatcher.api.IEvent
* @see strange.extensions.dispatcher.api.ITriggerProvider
* @see strange.extensions.dispatcher.api.ITriggerable
*/
using System;
using System.Collections.Generic;
using strange.framework.api;
using strange.framework.impl;
using strange.extensions.dispatcher.api;
using strange.extensions.dispatcher.eventdispatcher.api;
using strange.extensions.pool.api;
using strange.extensions.pool.impl;
namespace strange.extensions.dispatcher.eventdispatcher.impl
{
public class EventDispatcher : Binder, IEventDispatcher, ITriggerProvider, ITriggerable
{
/// The list of clients that will be triggered as a consequence of an Event firing.
protected HashSet<ITriggerable> triggerClients;
protected HashSet<ITriggerable> triggerClientRemovals;
protected bool isTriggeringClients;
/// The eventPool is shared across all EventDispatchers for efficiency
public static IPool<TmEvent> eventPool;
public EventDispatcher ()
{
if (eventPool == null)
{
eventPool = new Pool<TmEvent> ();
eventPool.instanceProvider = new EventInstanceProvider ();
}
}
override public IBinding GetRawBinding()
{
return new EventBinding (resolver);
}
new public IEventBinding Bind(object key)
{
return base.Bind (key) as IEventBinding;
}
public void Dispatch (object eventType)
{
Dispatch (eventType, null);
}
public void Dispatch (object eventType, object data)
{
//Scrub the data to make eventType and data conform if possible
IEvent evt = conformDataToEvent (eventType, data);
if (evt is IPoolable)
{
(evt as IPoolable).Retain ();
}
bool continueDispatch = true;
if (triggerClients != null)
{
isTriggeringClients = true;
foreach (ITriggerable trigger in triggerClients)
{
if (!trigger.Trigger(evt.type, evt))
{
continueDispatch = false;
break;
}
}
if (triggerClientRemovals != null)
{
flushRemovals();
}
isTriggeringClients = false;
}
if (!continueDispatch)
{
internalReleaseEvent (evt);
return;
}
IEventBinding binding = GetBinding (evt.type) as IEventBinding;
if (binding == null)
{
internalReleaseEvent (evt);
return;
}
object[] callbacks = (binding.value as object[]).Clone() as object[];
if (callbacks == null)
{
internalReleaseEvent (evt);
return;
}
for(int a = 0; a < callbacks.Length; a++)
{
object callback = callbacks[a];
if(callback == null)
continue;
callbacks[a] = null;
object[] currentCallbacks = binding.value as object[];
if(Array.IndexOf(currentCallbacks, callback) == -1)
continue;
if (callback is EventCallback)
{
invokeEventCallback (evt, callback as EventCallback);
}
else if (callback is EmptyCallback)
{
(callback as EmptyCallback)();
}
}
internalReleaseEvent (evt);
}
virtual protected IEvent conformDataToEvent(object eventType, object data)
{
IEvent retv = null;
if (eventType == null)
{
throw new EventDispatcherException("Attempt to Dispatch to null.\ndata: " + data, EventDispatcherExceptionType.EVENT_KEY_NULL);
}
else if (eventType is IEvent)
{
//Client provided a full-formed event
retv = (IEvent)eventType;
}
else if (data == null)
{
//Client provided just an event ID. Create an event for injection
retv = createEvent (eventType, null);
}
else if (data is IEvent)
{
//Client provided both an evertType and a full-formed IEvent
retv = (IEvent)data;
}
else
{
//Client provided an eventType and some data which is not a IEvent.
retv = createEvent (eventType, data);
}
return retv;
}
virtual protected IEvent createEvent(object eventType, object data)
{
IEvent retv = eventPool.GetInstance();
retv.type = eventType;
retv.target = this;
retv.data = data;
return retv;
}
virtual protected void invokeEventCallback(object data, EventCallback callback)
{
try
{
callback (data as IEvent);
}
catch(InvalidCastException)
{
object tgt = callback.Target;
string methodName = (callback as Delegate).Method.Name;
string message = "An EventCallback is attempting an illegal cast. One possible reason is not typing the payload to IEvent in your callback. Another is illegal casting of the data.\nTarget class: " + tgt + " method: " + methodName;
throw new EventDispatcherException (message, EventDispatcherExceptionType.TARGET_INVOCATION);
}
}
public void AddListener(object evt, EventCallback callback)
{
IBinding binding = GetBinding (evt);
if (binding == null)
{
Bind (evt).To (callback);
}
else
{
binding.To (callback);
}
}
public void AddListener(object evt, EmptyCallback callback)
{
IBinding binding = GetBinding (evt);
if (binding == null)
{
Bind (evt).To (callback);
}
else
{
binding.To (callback);
}
}
public void RemoveListener(object evt, EventCallback callback)
{
IBinding binding = GetBinding (evt);
RemoveValue (binding, callback);
}
public void RemoveListener(object evt, EmptyCallback callback)
{
IBinding binding = GetBinding (evt);
RemoveValue (binding, callback);
}
public bool HasListener(object evt, EventCallback callback)
{
IEventBinding binding = GetBinding (evt) as IEventBinding;
if (binding == null)
{
return false;
}
return binding.TypeForCallback (callback) != EventCallbackType.NOT_FOUND;
}
public bool HasListener(object evt, EmptyCallback callback)
{
IEventBinding binding = GetBinding (evt) as IEventBinding;
if (binding == null)
{
return false;
}
return binding.TypeForCallback (callback) != EventCallbackType.NOT_FOUND;
}
public void UpdateListener(bool toAdd, object evt, EventCallback callback)
{
if (toAdd)
{
AddListener (evt, callback);
}
else
{
RemoveListener (evt, callback);
}
}
public void UpdateListener(bool toAdd, object evt, EmptyCallback callback)
{
if (toAdd)
{
AddListener (evt, callback);
}
else
{
RemoveListener (evt, callback);
}
}
public void AddTriggerable(ITriggerable target)
{
if (triggerClients == null)
{
triggerClients = new HashSet<ITriggerable>();
}
triggerClients.Add(target);
}
public void RemoveTriggerable(ITriggerable target)
{
if (triggerClients.Contains(target))
{
if (triggerClientRemovals == null)
{
triggerClientRemovals = new HashSet<ITriggerable>();
}
triggerClientRemovals.Add (target);
if (!isTriggeringClients)
{
flushRemovals();
}
}
}
public int Triggerables
{
get
{
if (triggerClients == null)
return 0;
return triggerClients.Count;
}
}
protected void flushRemovals()
{
if (triggerClientRemovals == null)
{
return;
}
foreach(ITriggerable target in triggerClientRemovals)
{
if (triggerClients.Contains(target))
{
triggerClients.Remove(target);
}
}
triggerClientRemovals = null;
}
public bool Trigger<T>(object data)
{
return Trigger (typeof(T), data);
}
public bool Trigger(object key, object data)
{
bool allow = ((data is IEvent && System.Object.ReferenceEquals((data as IEvent).target, this) == false) ||
(key is IEvent && System.Object.ReferenceEquals((data as IEvent).target, this) == false));
if (allow)
Dispatch(key, data);
return true;
}
protected void internalReleaseEvent(IEvent evt)
{
if (evt is IPoolable)
{
(evt as IPoolable).Release ();
}
}
public void ReleaseEvent(IEvent evt)
{
if ((evt as IPoolable).retain == false)
{
cleanEvent (evt);
eventPool.ReturnInstance (evt);
}
}
protected void cleanEvent(IEvent evt)
{
evt.target = null;
evt.data = null;
evt.type = null;
}
}
class EventInstanceProvider : IInstanceProvider
{
public T GetInstance<T>()
{
object instance = new TmEvent ();
T retv = (T) instance;
return retv;
}
public object GetInstance(Type key)
{
return new TmEvent ();
}
}
}
| |
// Copyright (c) ppy Pty Ltd <[email protected]>. Licensed under the MIT Licence.
// See the LICENCE file in the repository root for full licence text.
using System;
using System.Collections.Specialized;
using Humanizer;
using osu.Framework.Allocation;
using osu.Framework.Graphics;
using osu.Framework.Graphics.Containers;
using osu.Framework.Graphics.Shapes;
using osu.Framework.Localisation;
using osu.Game.Graphics;
using osu.Game.Graphics.Containers;
using osu.Game.Graphics.Sprites;
using osu.Game.Graphics.UserInterface;
using osu.Game.Online.Rooms;
using osu.Game.Overlays;
using osu.Game.Screens.OnlinePlay.Match.Components;
using osuTK;
namespace osu.Game.Screens.OnlinePlay.Playlists
{
public class PlaylistsRoomSettingsOverlay : RoomSettingsOverlay
{
public Action EditPlaylist;
private MatchSettings settings;
protected override OsuButton SubmitButton => settings.ApplyButton;
protected override bool IsLoading => settings.IsLoading; // should probably be replaced with an OngoingOperationTracker.
public PlaylistsRoomSettingsOverlay(Room room)
: base(room)
{
}
protected override void SelectBeatmap() => settings.SelectBeatmap();
protected override OnlinePlayComposite CreateSettings(Room room) => settings = new MatchSettings(room)
{
RelativeSizeAxes = Axes.Both,
RelativePositionAxes = Axes.Y,
EditPlaylist = () => EditPlaylist?.Invoke()
};
protected class MatchSettings : OnlinePlayComposite
{
private const float disabled_alpha = 0.2f;
public Action EditPlaylist;
public OsuTextBox NameField, MaxParticipantsField, MaxAttemptsField;
public OsuDropdown<TimeSpan> DurationField;
public RoomAvailabilityPicker AvailabilityPicker;
public TriangleButton ApplyButton;
public bool IsLoading => loadingLayer.State.Value == Visibility.Visible;
public OsuSpriteText ErrorText;
private LoadingLayer loadingLayer;
private DrawableRoomPlaylist playlist;
private OsuSpriteText playlistLength;
private PurpleTriangleButton editPlaylistButton;
[Resolved(CanBeNull = true)]
private IRoomManager manager { get; set; }
private readonly Room room;
public MatchSettings(Room room)
{
this.room = room;
}
[BackgroundDependencyLoader]
private void load(OverlayColourProvider colourProvider, OsuColour colours)
{
InternalChildren = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background4
},
new GridContainer
{
RelativeSizeAxes = Axes.Both,
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
},
Content = new[]
{
new Drawable[]
{
new OsuScrollContainer
{
Padding = new MarginPadding
{
Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING,
Vertical = 10
},
RelativeSizeAxes = Axes.Both,
Children = new[]
{
new Container
{
Padding = new MarginPadding { Horizontal = WaveOverlayContainer.WIDTH_PADDING },
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new SectionContainer
{
Padding = new MarginPadding { Right = FIELD_PADDING / 2 },
Children = new[]
{
new Section("Room name")
{
Child = NameField = new OsuTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
LengthLimit = 100
},
},
new Section("Duration")
{
Child = DurationField = new DurationDropdown
{
RelativeSizeAxes = Axes.X,
Items = new[]
{
TimeSpan.FromMinutes(30),
TimeSpan.FromHours(1),
TimeSpan.FromHours(2),
TimeSpan.FromHours(4),
TimeSpan.FromHours(8),
TimeSpan.FromHours(12),
//TimeSpan.FromHours(16),
TimeSpan.FromHours(24),
TimeSpan.FromDays(3),
TimeSpan.FromDays(7)
}
}
},
new Section("Allowed attempts (across all playlist items)")
{
Child = MaxAttemptsField = new OsuNumberBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
PlaceholderText = "Unlimited",
},
},
new Section("Room visibility")
{
Alpha = disabled_alpha,
Child = AvailabilityPicker = new RoomAvailabilityPicker
{
Enabled = { Value = false }
},
},
new Section("Max participants")
{
Alpha = disabled_alpha,
Child = MaxParticipantsField = new OsuNumberBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
ReadOnly = true,
},
},
new Section("Password (optional)")
{
Alpha = disabled_alpha,
Child = new OsuPasswordTextBox
{
RelativeSizeAxes = Axes.X,
TabbableContentContainer = this,
ReadOnly = true,
},
},
},
},
new SectionContainer
{
Anchor = Anchor.TopRight,
Origin = Anchor.TopRight,
Padding = new MarginPadding { Left = FIELD_PADDING / 2 },
Children = new[]
{
new Section("Playlist")
{
Child = new GridContainer
{
RelativeSizeAxes = Axes.X,
Height = 448,
Content = new[]
{
new Drawable[]
{
playlist = new DrawableRoomPlaylist(true, true) { RelativeSizeAxes = Axes.Both }
},
new Drawable[]
{
playlistLength = new OsuSpriteText
{
Margin = new MarginPadding { Vertical = 5 },
Colour = colours.Yellow,
Font = OsuFont.GetFont(size: 12),
}
},
new Drawable[]
{
editPlaylistButton = new PurpleTriangleButton
{
RelativeSizeAxes = Axes.X,
Height = 40,
Text = "Edit playlist",
Action = () => EditPlaylist?.Invoke()
}
}
},
RowDimensions = new[]
{
new Dimension(),
new Dimension(GridSizeMode.AutoSize),
new Dimension(GridSizeMode.AutoSize),
}
}
},
},
},
},
}
},
},
},
new Drawable[]
{
new Container
{
Anchor = Anchor.BottomLeft,
Origin = Anchor.BottomLeft,
Y = 2,
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Children = new Drawable[]
{
new Box
{
RelativeSizeAxes = Axes.Both,
Colour = colourProvider.Background5
},
new FillFlowContainer
{
RelativeSizeAxes = Axes.X,
AutoSizeAxes = Axes.Y,
Direction = FillDirection.Vertical,
Spacing = new Vector2(0, 20),
Margin = new MarginPadding { Vertical = 20 },
Padding = new MarginPadding { Horizontal = OsuScreen.HORIZONTAL_OVERFLOW_PADDING },
Children = new Drawable[]
{
ApplyButton = new CreateRoomButton
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Size = new Vector2(230, 55),
Enabled = { Value = false },
Action = apply,
},
ErrorText = new OsuSpriteText
{
Anchor = Anchor.BottomCentre,
Origin = Anchor.BottomCentre,
Alpha = 0,
Depth = 1,
Colour = colours.RedDark
}
}
}
}
}
}
}
},
loadingLayer = new LoadingLayer(true)
};
RoomName.BindValueChanged(name => NameField.Text = name.NewValue, true);
Availability.BindValueChanged(availability => AvailabilityPicker.Current.Value = availability.NewValue, true);
MaxParticipants.BindValueChanged(count => MaxParticipantsField.Text = count.NewValue?.ToString(), true);
MaxAttempts.BindValueChanged(count => MaxAttemptsField.Text = count.NewValue?.ToString(), true);
Duration.BindValueChanged(duration => DurationField.Current.Value = duration.NewValue ?? TimeSpan.FromMinutes(30), true);
playlist.Items.BindTo(Playlist);
Playlist.BindCollectionChanged(onPlaylistChanged, true);
}
protected override void Update()
{
base.Update();
ApplyButton.Enabled.Value = hasValidSettings;
}
public void SelectBeatmap() => editPlaylistButton.TriggerClick();
private void onPlaylistChanged(object sender, NotifyCollectionChangedEventArgs e) =>
playlistLength.Text = $"Length: {Playlist.GetTotalDuration()}";
private bool hasValidSettings => RoomID.Value == null && NameField.Text.Length > 0 && Playlist.Count > 0;
private void apply()
{
if (!ApplyButton.Enabled.Value)
return;
hideError();
RoomName.Value = NameField.Text;
Availability.Value = AvailabilityPicker.Current.Value;
if (int.TryParse(MaxParticipantsField.Text, out int max))
MaxParticipants.Value = max;
else
MaxParticipants.Value = null;
if (int.TryParse(MaxAttemptsField.Text, out max))
MaxAttempts.Value = max;
else
MaxAttempts.Value = null;
Duration.Value = DurationField.Current.Value;
manager?.CreateRoom(room, onSuccess, onError);
loadingLayer.Show();
}
private void hideError() => ErrorText.FadeOut(50);
private void onSuccess(Room room) => loadingLayer.Hide();
private void onError(string text)
{
ErrorText.Text = text;
ErrorText.FadeIn(50);
loadingLayer.Hide();
}
}
public class CreateRoomButton : TriangleButton
{
public CreateRoomButton()
{
Text = "Create";
}
[BackgroundDependencyLoader]
private void load(OsuColour colours)
{
BackgroundColour = colours.Yellow;
Triangles.ColourLight = colours.YellowLight;
Triangles.ColourDark = colours.YellowDark;
}
}
private class DurationDropdown : OsuDropdown<TimeSpan>
{
public DurationDropdown()
{
Menu.MaxHeight = 100;
}
protected override LocalisableString GenerateItemText(TimeSpan item) => item.Humanize();
}
}
}
| |
// 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: For writing text to streams in a particular
** encoding.
**
**
===========================================================*/
using System;
using System.Text;
using System.Threading;
using System.Globalization;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Security.Permissions;
using System.Runtime.Serialization;
using System.Diagnostics.Contracts;
using System.Runtime.InteropServices;
using System.Threading.Tasks;
namespace System.IO
{
// This class implements a TextWriter for writing characters to a Stream.
// This is designed for character output in a particular Encoding,
// whereas the Stream class is designed for byte input and output.
//
[Serializable]
[ComVisible(true)]
public class StreamWriter : TextWriter
{
// For UTF-8, the values of 1K for the default buffer size and 4K for the
// file stream buffer size are reasonable & give very reasonable
// performance for in terms of construction time for the StreamWriter and
// write perf. Note that for UTF-8, we end up allocating a 4K byte buffer,
// which means we take advantage of adaptive buffering code.
// The performance using UnicodeEncoding is acceptable.
internal const int DefaultBufferSize = 1024; // char[]
private const int DefaultFileStreamBufferSize = 4096;
private const int MinBufferSize = 128;
private const Int32 DontCopyOnWriteLineThreshold = 512;
// Bit bucket - Null has no backing store. Non closable.
public new static readonly StreamWriter Null = new StreamWriter(Stream.Null, new UTF8Encoding(false, true), MinBufferSize, true);
private Stream stream;
private Encoding encoding;
private Encoder encoder;
private byte[] byteBuffer;
private char[] charBuffer;
private int charPos;
private int charLen;
private bool autoFlush;
private bool haveWrittenPreamble;
private bool closable;
#if MDA_SUPPORTED
[NonSerialized]
// For StreamWriterBufferedDataLost MDA
private MdaHelper mdaHelper;
#endif
// We don't guarantee thread safety on StreamWriter, but we should at
// least prevent users from trying to write anything while an Async
// write from the same thread is in progress.
[NonSerialized]
private volatile Task _asyncWriteTask;
private void CheckAsyncTaskInProgress()
{
// We are not locking the access to _asyncWriteTask because this is not meant to guarantee thread safety.
// We are simply trying to deter calling any Write APIs while an async Write from the same thread is in progress.
Task t = _asyncWriteTask;
if (t != null && !t.IsCompleted)
throw new InvalidOperationException(Environment.GetResourceString("InvalidOperation_AsyncIOInProgress"));
}
// The high level goal is to be tolerant of encoding errors when we read and very strict
// when we write. Hence, default StreamWriter encoding will throw on encoding error.
// Note: when StreamWriter throws on invalid encoding chars (for ex, high surrogate character
// D800-DBFF without a following low surrogate character DC00-DFFF), it will cause the
// internal StreamWriter's state to be irrecoverable as it would have buffered the
// illegal chars and any subsequent call to Flush() would hit the encoding error again.
// Even Close() will hit the exception as it would try to flush the unwritten data.
// Maybe we can add a DiscardBufferedData() method to get out of such situation (like
// StreamReader though for different reason). Either way, the buffered data will be lost!
private static volatile Encoding _UTF8NoBOM;
internal static Encoding UTF8NoBOM {
[FriendAccessAllowed]
get {
if (_UTF8NoBOM == null) {
// No need for double lock - we just want to avoid extra
// allocations in the common case.
UTF8Encoding noBOM = new UTF8Encoding(false, true);
Thread.MemoryBarrier();
_UTF8NoBOM = noBOM;
}
return _UTF8NoBOM;
}
}
internal StreamWriter(): base(null) { // Ask for CurrentCulture all the time
}
public StreamWriter(Stream stream)
: this(stream, UTF8NoBOM, DefaultBufferSize, false) {
}
public StreamWriter(Stream stream, Encoding encoding)
: this(stream, encoding, DefaultBufferSize, false) {
}
// Creates a new StreamWriter for the given stream. The
// character encoding is set by encoding and the buffer size,
// in number of 16-bit characters, is set by bufferSize.
//
public StreamWriter(Stream stream, Encoding encoding, int bufferSize)
: this(stream, encoding, bufferSize, false) {
}
public StreamWriter(Stream stream, Encoding encoding, int bufferSize, bool leaveOpen)
: base(null) // Ask for CurrentCulture all the time
{
if (stream == null || encoding == null)
throw new ArgumentNullException((stream == null ? "stream" : "encoding"));
if (!stream.CanWrite)
throw new ArgumentException(Environment.GetResourceString("Argument_StreamNotWritable"));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Init(stream, encoding, bufferSize, leaveOpen);
}
public StreamWriter(String path)
: this(path, false, UTF8NoBOM, DefaultBufferSize) {
}
public StreamWriter(String path, bool append)
: this(path, append, UTF8NoBOM, DefaultBufferSize) {
}
public StreamWriter(String path, bool append, Encoding encoding)
: this(path, append, encoding, DefaultBufferSize) {
}
[System.Security.SecuritySafeCritical]
public StreamWriter(String path, bool append, Encoding encoding, int bufferSize): this(path, append, encoding, bufferSize, true) {
}
[System.Security.SecurityCritical]
internal StreamWriter(String path, bool append, Encoding encoding, int bufferSize, bool checkHost)
: base(null)
{ // Ask for CurrentCulture all the time
if (path == null)
throw new ArgumentNullException("path");
if (encoding == null)
throw new ArgumentNullException("encoding");
if (path.Length == 0)
throw new ArgumentException(Environment.GetResourceString("Argument_EmptyPath"));
if (bufferSize <= 0) throw new ArgumentOutOfRangeException("bufferSize", Environment.GetResourceString("ArgumentOutOfRange_NeedPosNum"));
Contract.EndContractBlock();
Stream stream = CreateFile(path, append, checkHost);
Init(stream, encoding, bufferSize, false);
}
[System.Security.SecuritySafeCritical]
private void Init(Stream streamArg, Encoding encodingArg, int bufferSize, bool shouldLeaveOpen)
{
this.stream = streamArg;
this.encoding = encodingArg;
this.encoder = encoding.GetEncoder();
if (bufferSize < MinBufferSize) bufferSize = MinBufferSize;
charBuffer = new char[bufferSize];
byteBuffer = new byte[encoding.GetMaxByteCount(bufferSize)];
charLen = bufferSize;
// If we're appending to a Stream that already has data, don't write
// the preamble.
if (stream.CanSeek && stream.Position > 0)
haveWrittenPreamble = true;
closable = !shouldLeaveOpen;
#if MDA_SUPPORTED
if (Mda.StreamWriterBufferedDataLost.Enabled) {
String callstack = null;
if (Mda.StreamWriterBufferedDataLost.CaptureAllocatedCallStack)
callstack = Environment.GetStackTrace(null, false);
mdaHelper = new MdaHelper(this, callstack);
}
#endif
}
[System.Security.SecurityCritical]
private static Stream CreateFile(String path, bool append, bool checkHost) {
FileMode mode = append? FileMode.Append: FileMode.Create;
FileStream f = new FileStream(path, mode, FileAccess.Write, FileShare.Read,
DefaultFileStreamBufferSize, FileOptions.SequentialScan, Path.GetFileName(path), false, false, checkHost);
return f;
}
public override void Close() {
Dispose(true);
GC.SuppressFinalize(this);
}
protected override void Dispose(bool disposing) {
try {
// We need to flush any buffered data if we are being closed/disposed.
// Also, we never close the handles for stdout & friends. So we can safely
// write any buffered data to those streams even during finalization, which
// is generally the right thing to do.
if (stream != null) {
// Note: flush on the underlying stream can throw (ex., low disk space)
if (disposing || (LeaveOpen && stream is __ConsoleStream))
{
CheckAsyncTaskInProgress();
Flush(true, true);
#if MDA_SUPPORTED
// Disable buffered data loss mda
if (mdaHelper != null)
GC.SuppressFinalize(mdaHelper);
#endif
}
}
}
finally {
// Dispose of our resources if this StreamWriter is closable.
// Note: Console.Out and other such non closable streamwriters should be left alone
if (!LeaveOpen && stream != null) {
try {
// Attempt to close the stream even if there was an IO error from Flushing.
// Note that Stream.Close() can potentially throw here (may or may not be
// due to the same Flush error). In this case, we still need to ensure
// cleaning up internal resources, hence the finally block.
if (disposing)
stream.Close();
}
finally {
stream = null;
byteBuffer = null;
charBuffer = null;
encoding = null;
encoder = null;
charLen = 0;
base.Dispose(disposing);
}
}
}
}
public override void Flush()
{
CheckAsyncTaskInProgress();
Flush(true, true);
}
private void Flush(bool flushStream, bool flushEncoder)
{
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (stream == null)
__Error.WriterClosed();
// Perf boost for Flush on non-dirty writers.
if (charPos==0 && ((!flushStream && !flushEncoder) || CompatibilitySwitches.IsAppEarlierThanWindowsPhone8))
return;
if (!haveWrittenPreamble) {
haveWrittenPreamble = true;
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
stream.Write(preamble, 0, preamble.Length);
}
int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
charPos = 0;
if (count > 0)
stream.Write(byteBuffer, 0, count);
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
stream.Flush();
}
public virtual bool AutoFlush {
get { return autoFlush; }
set
{
CheckAsyncTaskInProgress();
autoFlush = value;
if (value) Flush(true, false);
}
}
public virtual Stream BaseStream {
get { return stream; }
}
internal bool LeaveOpen {
get { return !closable; }
}
internal bool HaveWrittenPreamble {
set { haveWrittenPreamble= value; }
}
public override Encoding Encoding {
get { return encoding; }
}
public override void Write(char value)
{
CheckAsyncTaskInProgress();
if (charPos == charLen) Flush(false, false);
charBuffer[charPos] = value;
charPos++;
if (autoFlush) Flush(true, false);
}
public override void Write(char[] buffer)
{
// This may be faster than the one with the index & count since it
// has to do less argument checking.
if (buffer==null)
return;
CheckAsyncTaskInProgress();
int index = 0;
int count = buffer.Length;
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[]) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
public override void Write(char[] buffer, int index, int count) {
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
CheckAsyncTaskInProgress();
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
public override void Write(String value)
{
if (value != null)
{
CheckAsyncTaskInProgress();
int count = value.Length;
int index = 0;
while (count > 0) {
if (charPos == charLen) Flush(false, false);
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
count -= n;
}
if (autoFlush) Flush(true, false);
}
}
#region Task based Async APIs
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, Char value,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = value;
charPos++;
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(String value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(value);
if (value != null)
{
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
else
{
return Task.CompletedTask;
}
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, String value,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Contract.Requires(value != null);
int count = value.Length;
int index = 0;
while (count > 0)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count)
n = count;
Contract.Assert(n > 0, "StreamWriter::Write(String) isn't making progress! This is most likely a race condition in user code.");
value.CopyTo(index, charBuffer, charPos, n);
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteAsync(buffer, index, count);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: false);
_asyncWriteTask = task;
return task;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
// Fields that are written to must be assigned at the end of the method *and* before instance invocations.
private static async Task WriteAsyncInternal(StreamWriter _this, Char[] buffer, Int32 index, Int32 count,
Char[] charBuffer, Int32 charPos, Int32 charLen, Char[] coreNewLine,
bool autoFlush, bool appendNewLine)
{
Contract.Requires(count == 0 || (count > 0 && buffer != null));
Contract.Requires(index >= 0);
Contract.Requires(count >= 0);
Contract.Requires(buffer == null || (buffer != null && buffer.Length - index >= count));
while (count > 0)
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
int n = charLen - charPos;
if (n > count) n = count;
Contract.Assert(n > 0, "StreamWriter::Write(char[], int, int) isn't making progress! This is most likely a race condition in user code.");
Buffer.InternalBlockCopy(buffer, index * sizeof(char), charBuffer, charPos * sizeof(char), n * sizeof(char));
charPos += n;
index += n;
count -= n;
}
if (appendNewLine)
{
for (Int32 i = 0; i < coreNewLine.Length; i++) // Expect 2 iterations, no point calling BlockCopy
{
if (charPos == charLen) {
await _this.FlushAsyncInternal(false, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
charBuffer[charPos] = coreNewLine[i];
charPos++;
}
}
if (autoFlush) {
await _this.FlushAsyncInternal(true, false, charBuffer, charPos).ConfigureAwait(false);
Contract.Assert(_this.charPos == 0);
charPos = 0;
}
_this.CharPos_Prop = charPos;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync();
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, null, 0, 0, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(String value)
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(value);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, value, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task WriteLineAsync(char[] buffer, int index, int count)
{
if (buffer==null)
throw new ArgumentNullException("buffer", Environment.GetResourceString("ArgumentNull_Buffer"));
if (index < 0)
throw new ArgumentOutOfRangeException("index", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (count < 0)
throw new ArgumentOutOfRangeException("count", Environment.GetResourceString("ArgumentOutOfRange_NeedNonNegNum"));
if (buffer.Length - index < count)
throw new ArgumentException(Environment.GetResourceString("Argument_InvalidOffLen"));
Contract.EndContractBlock();
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Write() which a subclass might have overriden.
// To be safe we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Write) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.WriteLineAsync(buffer, index, count);
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = WriteAsyncInternal(this, buffer, index, count, charBuffer, charPos, charLen, CoreNewLine, autoFlush, appendNewLine: true);
_asyncWriteTask = task;
return task;
}
[HostProtection(ExternalThreading = true)]
[ComVisible(false)]
public override Task FlushAsync()
{
// If we have been inherited into a subclass, the following implementation could be incorrect
// since it does not call through to Flush() which a subclass might have overriden. To be safe
// we will only use this implementation in cases where we know it is safe to do so,
// and delegate to our base class (which will call into Flush) when we are not sure.
if (this.GetType() != typeof(StreamWriter))
return base.FlushAsync();
// flushEncoder should be true at the end of the file and if
// the user explicitly calls Flush (though not if AutoFlush is true).
// This is required to flush any dangling characters from our UTF-7
// and UTF-8 encoders.
if (stream == null)
__Error.WriterClosed();
CheckAsyncTaskInProgress();
Task task = FlushAsyncInternal(true, true, charBuffer, charPos);
_asyncWriteTask = task;
return task;
}
private Int32 CharPos_Prop {
set { this.charPos = value; }
}
private bool HaveWrittenPreamble_Prop {
set { this.haveWrittenPreamble = value; }
}
private Task FlushAsyncInternal(bool flushStream, bool flushEncoder,
Char[] sCharBuffer, Int32 sCharPos) {
// Perf boost for Flush on non-dirty writers.
if (sCharPos == 0 && !flushStream && !flushEncoder)
return Task.CompletedTask;
Task flushTask = FlushAsyncInternal(this, flushStream, flushEncoder, sCharBuffer, sCharPos, this.haveWrittenPreamble,
this.encoding, this.encoder, this.byteBuffer, this.stream);
this.charPos = 0;
return flushTask;
}
// We pass in private instance fields of this MarshalByRefObject-derived type as local params
// to ensure performant access inside the state machine that corresponds this async method.
private static async Task FlushAsyncInternal(StreamWriter _this, bool flushStream, bool flushEncoder,
Char[] charBuffer, Int32 charPos, bool haveWrittenPreamble,
Encoding encoding, Encoder encoder, Byte[] byteBuffer, Stream stream)
{
if (!haveWrittenPreamble)
{
_this.HaveWrittenPreamble_Prop = true;
byte[] preamble = encoding.GetPreamble();
if (preamble.Length > 0)
await stream.WriteAsync(preamble, 0, preamble.Length).ConfigureAwait(false);
}
int count = encoder.GetBytes(charBuffer, 0, charPos, byteBuffer, 0, flushEncoder);
if (count > 0)
await stream.WriteAsync(byteBuffer, 0, count).ConfigureAwait(false);
// By definition, calling Flush should flush the stream, but this is
// only necessary if we passed in true for flushStream. The Web
// Services guys have some perf tests where flushing needlessly hurts.
if (flushStream)
await stream.FlushAsync().ConfigureAwait(false);
}
#endregion
#if MDA_SUPPORTED
// StreamWriterBufferedDataLost MDA
// Instead of adding a finalizer to StreamWriter for detecting buffered data loss
// (ie, when the user forgets to call Close/Flush on the StreamWriter), we will
// have a separate object with normal finalization semantics that maintains a
// back pointer to this StreamWriter and alerts about any data loss
private sealed class MdaHelper
{
private StreamWriter streamWriter;
private String allocatedCallstack; // captures the callstack when this streamwriter was allocated
internal MdaHelper(StreamWriter sw, String cs)
{
streamWriter = sw;
allocatedCallstack = cs;
}
// Finalizer
~MdaHelper()
{
// Make sure people closed this StreamWriter, exclude StreamWriter::Null.
if (streamWriter.charPos != 0 && streamWriter.stream != null && streamWriter.stream != Stream.Null) {
String fileName = (streamWriter.stream is FileStream) ? ((FileStream)streamWriter.stream).NameInternal : "<unknown>";
String callStack = allocatedCallstack;
if (callStack == null)
callStack = Environment.GetResourceString("IO_StreamWriterBufferedDataLostCaptureAllocatedFromCallstackNotEnabled");
String message = Environment.GetResourceString("IO_StreamWriterBufferedDataLost", streamWriter.stream.GetType().FullName, fileName, callStack);
Mda.StreamWriterBufferedDataLost.ReportError(message);
}
}
} // class MdaHelper
#endif // MDA_SUPPORTED
} // class StreamWriter
} // namespace
| |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
using System;
using System.Collections.Generic;
using System.Security;
using System.Security.Permissions;
using System.Diagnostics;
namespace System.Threading.Tasks
{
/// <summary>
/// Represents an abstract scheduler for tasks.
/// </summary>
/// <remarks>
/// <para>
/// <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> acts as the extension point for all
/// pluggable scheduling logic. This includes mechanisms such as how to schedule a task for execution, and
/// how scheduled tasks should be exposed to debuggers.
/// </para>
/// <para>
/// All members of the abstract <see cref="TaskScheduler"/> type are thread-safe
/// and may be used from multiple threads concurrently.
/// </para>
/// </remarks>
[DebuggerDisplay("Id={Id}")]
[HostProtection(Synchronization = true, ExternalThreading = true)]
////[PermissionSet(SecurityAction.InheritanceDemand, Unrestricted = true)]
public abstract class TaskScheduler
{
////////////////////////////////////////////////////////////
//
// User Provided Methods and Properties
//
/// <summary>
/// Queues a <see cref="T:System.Threading.Tasks.Task">Task</see> to the scheduler.
/// </summary>
/// <remarks>
/// <para>
/// A class derived from <see cref="T:System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
/// implements this method to accept tasks being scheduled on the scheduler.
/// A typical implementation would store the task in an internal data structure, which would
/// be serviced by threads that would execute those tasks at some time in the future.
/// </para>
/// <para>
/// This method is only meant to be called by the .NET Framework and
/// should not be called directly by the derived class. This is necessary
/// for maintaining the consistency of the system.
/// </para>
/// </remarks>
/// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be queued.</param>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is null.</exception>
[SecurityCritical]
protected internal abstract void QueueTask(Task task);
/// <summary>
/// Determines whether the provided <see cref="T:System.Threading.Tasks.Task">Task</see>
/// can be executed synchronously in this call, and if it can, executes it.
/// </summary>
/// <remarks>
/// <para>
/// A class derived from <see cref="TaskScheduler">TaskScheduler</see> implements this function to
/// support inline execution of a task on a thread that initiates a wait on that task object. Inline
/// execution is optional, and the request may be rejected by returning false. However, better
/// scalability typically results the more tasks that can be inlined, and in fact a scheduler that
/// inlines too little may be prone to deadlocks. A proper implementation should ensure that a
/// request executing under the policies guaranteed by the scheduler can successfully inline. For
/// example, if a scheduler uses a dedicated thread to execute tasks, any inlining requests from that
/// thread should succeed.
/// </para>
/// <para>
/// If a scheduler decides to perform the inline execution, it should do so by calling to the base
/// TaskScheduler's
/// <see cref="TryExecuteTask">TryExecuteTask</see> method with the provided task object, propagating
/// the return value. It may also be appropriate for the scheduler to remove an inlined task from its
/// internal data structures if it decides to honor the inlining request. Note, however, that under
/// some circumstances a scheduler may be asked to inline a task that was not previously provided to
/// it with the <see cref="QueueTask"/> method.
/// </para>
/// <para>
/// The derived scheduler is responsible for making sure that the calling thread is suitable for
/// executing the given task as far as its own scheduling and execution policies are concerned.
/// </para>
/// </remarks>
/// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be
/// executed.</param>
/// <param name="taskWasPreviouslyQueued">A Boolean denoting whether or not task has previously been
/// queued. If this parameter is True, then the task may have been previously queued (scheduled); if
/// False, then the task is known not to have been queued, and this call is being made in order to
/// execute the task inline without queueing it.</param>
/// <returns>A Boolean value indicating whether the task was executed inline.</returns>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is
/// null.</exception>
/// <exception cref="T:System.InvalidOperationException">The <paramref name="task"/> was already
/// executed.</exception>
[SecurityCritical]
protected abstract bool TryExecuteTaskInline(Task task, bool taskWasPreviouslyQueued);
/// <summary>
/// Generates an enumerable of <see cref="T:System.Threading.Tasks.Task">Task</see> instances
/// currently queued to the scheduler waiting to be executed.
/// </summary>
/// <remarks>
/// <para>
/// A class derived from <see cref="TaskScheduler"/> implements this method in order to support
/// integration with debuggers. This method will only be invoked by the .NET Framework when the
/// debugger requests access to the data. The enumerable returned will be traversed by debugging
/// utilities to access the tasks currently queued to this scheduler, enabling the debugger to
/// provide a representation of this information in the user interface.
/// </para>
/// <para>
/// It is important to note that, when this method is called, all other threads in the process will
/// be frozen. Therefore, it's important to avoid synchronization with other threads that may lead to
/// blocking. If synchronization is necessary, the method should prefer to throw a <see
/// cref="System.NotSupportedException"/>
/// than to block, which could cause a debugger to experience delays. Additionally, this method and
/// the enumerable returned must not modify any globally visible state.
/// </para>
/// <para>
/// The returned enumerable should never be null. If there are currently no queued tasks, an empty
/// enumerable should be returned instead.
/// </para>
/// <para>
/// For developers implementing a custom debugger, this method shouldn't be called directly, but
/// rather this functionality should be accessed through the internal wrapper method
/// GetScheduledTasksForDebugger:
/// <c>internal Task[] GetScheduledTasksForDebugger()</c>. This method returns an array of tasks,
/// rather than an enumerable. In order to retrieve a list of active schedulers, a debugger may use
/// another internal method: <c>internal static TaskScheduler[] GetTaskSchedulersForDebugger()</c>.
/// This static method returns an array of all active TaskScheduler instances.
/// GetScheduledTasksForDebugger then may be used on each of these scheduler instances to retrieve
/// the list of scheduled tasks for each.
/// </para>
/// </remarks>
/// <returns>An enumerable that allows traversal of tasks currently queued to this scheduler.
/// </returns>
/// <exception cref="T:System.NotSupportedException">
/// This scheduler is unable to generate a list of queued tasks at this time.
/// </exception>
[SecurityCritical]
protected abstract IEnumerable<Task> GetScheduledTasks();
/// <summary>
/// Indicates the maximum concurrency level this
/// <see cref="TaskScheduler"/> is able to support.
/// </summary>
public virtual Int32 MaximumConcurrencyLevel
{
get
{
return Int32.MaxValue;
}
}
/// <summary>
/// Attempts to dequeue a <see cref="T:System.Threading.Tasks.Task">Task</see> that was previously queued to
/// this scheduler.
/// </summary>
/// <param name="task">The <see cref="T:System.Threading.Tasks.Task">Task</see> to be dequeued.</param>
/// <returns>A Boolean denoting whether the <paramref name="task"/> argument was successfully dequeued.</returns>
/// <exception cref="T:System.ArgumentNullException">The <paramref name="task"/> argument is null.</exception>
[SecurityCritical]
protected internal virtual bool TryDequeue(Task task)
{
return false;
}
/// <summary>
/// Notifies the scheduler that a work item has made progress.
/// </summary>
internal virtual void NotifyWorkItemProgress()
{
}
/// <summary>
/// Indicates whether this is a custom scheduler, in which case the safe code paths will be taken upon task entry
/// using a CAS to transition from queued state to executing.
/// </summary>
internal virtual bool RequiresAtomicStartTransition
{
get { return true; }
}
////////////////////////////////////////////////////////////
//
// Constructors and public properties
//
/// <summary>
/// Initializes the <see cref="System.Threading.Tasks.TaskScheduler"/>.
/// </summary>
protected TaskScheduler()
{
}
/// <summary>
/// Gets the default <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see> instance.
/// </summary>
public static TaskScheduler Default
{
get
{
#if DISABLED_FOR_LLILUM
return s_defaultTaskScheduler;
#else // DISABLED_FOR_LLILUM
return null;
#endif // DISABLED_FOR_LLILUM
}
}
/// <summary>
/// Gets the <see cref="System.Threading.Tasks.TaskScheduler">TaskScheduler</see>
/// associated with the currently executing task.
/// </summary>
/// <remarks>
/// When not called from within a task, <see cref="Current"/> will return the <see cref="Default"/> scheduler.
/// </remarks>
public static TaskScheduler Current
{
get
{
#if DISABLED_FOR_LLILUM
TaskScheduler current = InternalCurrent;
return current ?? TaskScheduler.Default;
#else // DISABLED_FOR_LLILUM
return null;
#endif // DISABLED_FOR_LLILUM
}
}
/// <summary>
/// Creates a <see cref="TaskScheduler"/>
/// associated with the current <see cref="T:System.Threading.SynchronizationContext"/>.
/// </summary>
/// <remarks>
/// All <see cref="System.Threading.Tasks.Task">Task</see> instances queued to
/// the returned scheduler will be executed through a call to the
/// <see cref="System.Threading.SynchronizationContext.Post">Post</see> method
/// on that context.
/// </remarks>
/// <returns>
/// A <see cref="TaskScheduler"/> associated with
/// the current <see cref="T:System.Threading.SynchronizationContext">SynchronizationContext</see>, as
/// determined by <see cref="System.Threading.SynchronizationContext.Current">SynchronizationContext.Current</see>.
/// </returns>
/// <exception cref="T:System.InvalidOperationException">
/// The current SynchronizationContext may not be used as a TaskScheduler.
/// </exception>
public static TaskScheduler FromCurrentSynchronizationContext()
{
#if DISABLED_FOR_LLILUM
return new SynchronizationContextTaskScheduler();
#else // DISABLED_FOR_LLILUM
throw new NotImplementedException();
#endif // DISABLED_FOR_LLILUM
}
/// <summary>
/// Gets the unique ID for this <see cref="TaskScheduler"/>.
/// </summary>
public Int32 Id
{
get
{
#if DISABLED_FOR_LLILUM
if (m_taskSchedulerId == 0)
{
int newId = 0;
// We need to repeat if Interlocked.Increment wraps around and returns 0.
// Otherwise next time this scheduler's Id is queried it will get a new value
do
{
newId = Interlocked.Increment(ref s_taskSchedulerIdCounter);
} while (newId == 0);
Interlocked.CompareExchange(ref m_taskSchedulerId, newId, 0);
}
return m_taskSchedulerId;
#else // DISABLED_FOR_LLILUM
throw new NotImplementedException();
#endif // DISABLED_FOR_LLILUM
}
}
/// <summary>
/// Attempts to execute the provided <see cref="T:System.Threading.Tasks.Task">Task</see>
/// on this scheduler.
/// </summary>
/// <remarks>
/// <para>
/// Scheduler implementations are provided with <see cref="T:System.Threading.Tasks.Task">Task</see>
/// instances to be executed through either the <see cref="QueueTask"/> method or the
/// <see cref="TryExecuteTaskInline"/> method. When the scheduler deems it appropriate to run the
/// provided task, <see cref="TryExecuteTask"/> should be used to do so. TryExecuteTask handles all
/// aspects of executing a task, including action invocation, exception handling, state management,
/// and lifecycle control.
/// </para>
/// <para>
/// <see cref="TryExecuteTask"/> must only be used for tasks provided to this scheduler by the .NET
/// Framework infrastructure. It should not be used to execute arbitrary tasks obtained through
/// custom mechanisms.
/// </para>
/// </remarks>
/// <param name="task">
/// A <see cref="T:System.Threading.Tasks.Task">Task</see> object to be executed.</param>
/// <exception cref="T:System.InvalidOperationException">
/// The <paramref name="task"/> is not associated with this scheduler.
/// </exception>
/// <returns>A Boolean that is true if <paramref name="task"/> was successfully executed, false if it
/// was not. A common reason for execution failure is that the task had previously been executed or
/// is in the process of being executed by another thread.</returns>
[SecurityCritical]
protected bool TryExecuteTask(Task task)
{
#if DISABLED_FOR_LLILUM
if (task.ExecutingTaskScheduler != this)
{
throw new InvalidOperationException(Environment.GetResourceString("TaskScheduler_ExecuteTask_WrongTaskScheduler"));
}
return task.ExecuteEntry(true);
#else // DISABLED_FOR_LLILUM
throw new NotImplementedException();
#endif // DISABLED_FOR_LLILUM
}
////////////////////////////////////////////////////////////
//
// Events
//
private static EventHandler<UnobservedTaskExceptionEventArgs> _unobservedTaskException;
private static readonly object _unobservedTaskExceptionLockObject = new object();
/// <summary>
/// Occurs when a faulted <see cref="System.Threading.Tasks.Task"/>'s unobserved exception is about to trigger exception escalation
/// policy, which, by default, would terminate the process.
/// </summary>
/// <remarks>
/// This AppDomain-wide event provides a mechanism to prevent exception
/// escalation policy (which, by default, terminates the process) from triggering.
/// Each handler is passed a <see cref="T:System.Threading.Tasks.UnobservedTaskExceptionEventArgs"/>
/// instance, which may be used to examine the exception and to mark it as observed.
/// </remarks>
public static event EventHandler<UnobservedTaskExceptionEventArgs> UnobservedTaskException
{
[System.Security.SecurityCritical]
add
{
if (value != null)
{
#if DISABLED_FOR_LLILUM
RuntimeHelpers.PrepareContractedDelegate(value);
#endif // DISABLED_FOR_LLILUM
lock (_unobservedTaskExceptionLockObject) _unobservedTaskException += value;
}
}
[System.Security.SecurityCritical]
remove
{
lock (_unobservedTaskExceptionLockObject) _unobservedTaskException -= value;
}
}
////////////////////////////////////////////////////////////
//
// Internal methods
//
// This is called by the TaskExceptionHolder finalizer.
internal static void PublishUnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs ueea)
{
// Lock this logic to prevent just-unregistered handlers from being called.
lock (_unobservedTaskExceptionLockObject)
{
// Since we are under lock, it is technically no longer necessary
// to make a copy. It is done here for convenience.
EventHandler<UnobservedTaskExceptionEventArgs> handler = _unobservedTaskException;
if (handler != null)
{
handler(sender, ueea);
}
}
}
/// <summary>
/// Provides an array of all queued <see cref="System.Threading.Tasks.Task">Task</see> instances
/// for the debugger.
/// </summary>
/// <remarks>
/// The returned array is populated through a call to <see cref="GetScheduledTasks"/>.
/// Note that this function is only meant to be invoked by a debugger remotely.
/// It should not be called by any other codepaths.
/// </remarks>
/// <returns>An array of <see cref="System.Threading.Tasks.Task">Task</see> instances.</returns>
/// <exception cref="T:System.NotSupportedException">
/// This scheduler is unable to generate a list of queued tasks at this time.
/// </exception>
[SecurityCritical]
internal Task[] GetScheduledTasksForDebugger()
{
// this can throw InvalidOperationException indicating that they are unable to provide the info
// at the moment. We should let the debugger receive that exception so that it can indicate it in the UI
IEnumerable<Task> activeTasksSource = GetScheduledTasks();
if (activeTasksSource == null)
return null;
// If it can be cast to an array, use it directly
Task[] activeTasksArray = activeTasksSource as Task[];
if (activeTasksArray == null)
{
activeTasksArray = (new List<Task>(activeTasksSource)).ToArray();
}
// touch all Task.Id fields so that the debugger doesn't need to do a lot of cross-proc calls to generate them
foreach (Task t in activeTasksArray)
{
int tmp = t.Id;
}
return activeTasksArray;
}
}
/// <summary>
/// Provides data for the event that is raised when a faulted <see cref="System.Threading.Tasks.Task"/>'s
/// exception goes unobserved.
/// </summary>
/// <remarks>
/// The Exception property is used to examine the exception without marking it
/// as observed, whereas the <see cref="SetObserved"/> method is used to mark the exception
/// as observed. Marking the exception as observed prevents it from triggering exception escalation policy
/// which, by default, terminates the process.
/// </remarks>
public class UnobservedTaskExceptionEventArgs : EventArgs
{
private AggregateException m_exception;
internal bool m_observed = false;
/// <summary>
/// Initializes a new instance of the <see cref="UnobservedTaskExceptionEventArgs"/> class
/// with the unobserved exception.
/// </summary>
/// <param name="exception">The Exception that has gone unobserved.</param>
public UnobservedTaskExceptionEventArgs(AggregateException exception)
{ m_exception = exception; }
/// <summary>
/// Marks the <see cref="Exception"/> as "observed," thus preventing it
/// from triggering exception escalation policy which, by default, terminates the process.
/// </summary>
public void SetObserved()
{ m_observed = true; }
/// <summary>
/// Gets whether this exception has been marked as "observed."
/// </summary>
public bool Observed
{ get { return m_observed; } }
/// <summary>
/// The Exception that went unobserved.
/// </summary>
public AggregateException Exception
{ get { return m_exception; } }
}
}
| |
using System;
using System.Data;
using System.IO;
using System.Text.RegularExpressions;
using System.Web;
using System.Xml;
namespace DotNetNuke.Modules.UserDefinedTable.Components
{
public class XslTemplatingUtilities
{
public const string SpacePlaceholder = "{5A255853-D9A0-4f46-9E9D-F661DC4874CD}";
//Any Uncommon String would do
public const string HardSpace = " ";
public enum ContextValues
{
ApplicationPath,
CurrentCulture,
DisplayName,
HomePath,
IsAdministratorRole,
ModuleId,
OrderBy,
OrderDirection,
Parameter,
PortalId,
TabId,
TabName,
UserName,
UserRoles,
LocalizedSearchString,
NowInTicks,
TicksPerDay,
LocalizedDate,
Now
}
static string LoadXslScriptTemplate(string listView, string detailView, string headerView, bool pagingEnabled,
bool sortingEnabled, bool searchEnabled, bool showDetailView,
string currentListType)
{
var templateDoc = new XmlDocument();
templateDoc.Load(
HttpContext.Current.Request.MapPath("~/DesktopModules/UserDefinedTable/xslStyleSheets/xslScripts.xml"));
var xslTemplate =
// ReSharper disable PossibleNullReferenceException
HttpUtility.HtmlDecode(templateDoc.SelectSingleNode("/root/data[@name=\"XSLT\"]/value").InnerText);
// ReSharper restore PossibleNullReferenceException
xslTemplate = LoadXslScriptOption(templateDoc, xslTemplate, "paging", pagingEnabled);
xslTemplate = LoadXslScriptOption(templateDoc, xslTemplate, "sorting", sortingEnabled);
xslTemplate = LoadXslScriptOption(templateDoc, xslTemplate, "searching", searchEnabled);
xslTemplate = LoadXslScriptOption(templateDoc, xslTemplate, "detail", showDetailView);
xslTemplate =
(xslTemplate.Replace("[LISTVIEW]", listView).Replace("[DETAILVIEW]", detailView).Replace(
"[HEADERVIEW]", headerView));
string opentag;
var opentagclass = string.Empty;
switch (currentListType)
{
case "table":
opentag = currentListType;
opentagclass = @" class=""dnnFormItem""";
break;
case "ul":
case "ol":
opentag = currentListType;
break;
default:
opentag = "";
break;
}
if (opentag == "")
{
xslTemplate = (xslTemplate.Replace("[OPENTAG]", "").Replace("[/OPENTAG]", ""));
}
else
{
xslTemplate = xslTemplate
.Replace("[OPENTAG]", string.Format("<{0}{1}>", opentag, opentagclass))
.Replace("[/OPENTAG]", string.Format("</{0}>", opentag));
}
return xslTemplate;
}
static string LoadXslScriptOption(XmlDocument def, string xsl, string extension, bool isEnabled)
{
// ReSharper disable PossibleNullReferenceException
foreach (XmlElement element in def.SelectNodes(string.Format("root/data[@name=\"{0}\"]", extension)))
// ReSharper restore PossibleNullReferenceException
{
var placeholder = string.Format("{{{0}{1}}}", extension.ToUpperInvariant(),
element.Attributes["number"].InnerText);
xsl = xsl.Replace(placeholder, isEnabled ? HttpUtility.HtmlDecode(element.FirstChild.InnerText) : "");
}
return xsl;
}
public static string TransformTokenTextToXslScript(DataSet udtDataset, string tokentemplate)
{
return TransformTokenTextToXslScript(udtDataset, tokentemplate, string.Empty, string.Empty, false, false,
false, false, string.Empty);
}
public static string TransformTokenTextToXslScript(DataSet udtDataset, string listView, string detailView,
string headerView, bool pagingEnabled, bool sortingEnabled,
bool searchEnabled, bool showDetailView,
string currentListType)
{
headerView = Regex.Replace(headerView, "\\[((?:\\w|\\s)+)\\]",
sortingEnabled
? "<xsl:apply-templates select =\"udt:Fields[udt:FieldTitle=\'$1\']\"/>"
: "$1");
string template = LoadXslScriptTemplate(listView, detailView, headerView, pagingEnabled, sortingEnabled,
searchEnabled, showDetailView, currentListType);
template =
(template.Replace("[ ]", SpacePlaceholder).Replace(HardSpace, SpacePlaceholder).Replace(" ",
SpacePlaceholder));
const string attributeRegexPattern = "(?<==\\s*[\'\"][^\'\"<>]*)(\\[{0}\\])(?=[^\'\"<>]*[\"\'])";
foreach (DataColumn col in udtDataset.Tables[DataSetTableName.Data].Columns)
{
template = Regex.Replace(template, string.Format(attributeRegexPattern, col.ColumnName),
string.Format("{{udt:{0}}}", XmlConvert.EncodeName(col.ColumnName)));
template = template.Replace(string.Format("[{0}]", col.ColumnName),
string.Format(
"<xsl:value-of select=\"udt:{0}\" disable-output-escaping=\"yes\"/>",
XmlConvert.EncodeName(col.ColumnName)));
}
foreach (var contextString in Enum.GetNames(typeof (ContextValues)))
{
template = Regex.Replace(template, string.Format(attributeRegexPattern, "Context:" + contextString),
string.Format("{{/udt:UserDefinedTable/udt:Context/udt:{0}}}", contextString));
template = template.Replace(string.Format("[Context:{0}]", contextString),
string.Format(
"<xsl:value-of select=\"/udt:UserDefinedTable/udt:Context/udt:{0}\" disable-output-escaping=\"yes\"/>",
contextString));
}
template = template.Replace("[UDT:EditLink]", "<xsl:call-template name =\"EditLink\"/>");
template = template.Replace("[UDT:DetailView]", "<xsl:call-template name =\"DetailView\"/>");
template = template.Replace("[UDT:ListView]", "<xsl:call-template name =\"ListView\"/>");
return PrettyPrint(template).Replace(SpacePlaceholder, HardSpace);
}
public static string PrettyPrint(string template)
{
var doc = new XmlDocument();
doc.LoadXml(template);
return PrettyPrint(doc);
}
public static string PrettyPrint(XmlDocument doc)
{
using (var strXML = new StringWriter())
{
using (var writer = new XmlTextWriter(strXML))
{
try
{
writer.Formatting = Formatting.Indented;
doc.WriteTo(writer);
writer.Flush();
writer.Close();
return strXML.ToString().Replace(" <xsl:template", string.Format("{0} <xsl:template", "\r\n"));
}
catch (Exception)
{
return string.Empty;
}
}
}
}
public static string GenerateDetailViewTokenText(DataTable fieldstable)
{
return GenerateDetailViewTokenText(fieldstable, true);
}
public static string GenerateDetailViewTokenText(DataTable fieldstable, bool includeEditLink)
{
using (var sw = new StringWriter())
{
using (var xw = new XmlTextWriter(sw) {Formatting = Formatting.Indented})
{
xw.WriteStartElement("table");
foreach (DataRow row in fieldstable.Rows)
{
xw.WriteStartElement("tr");
xw.WriteStartElement("td");
xw.WriteAttributeString("class", "normalBold");
xw.WriteString(row[FieldsTableColumn.Title].ToString());
xw.WriteEndElement();
xw.WriteStartElement("td");
xw.WriteAttributeString("class", "Normal");
xw.WriteString(string.Format("[{0}]",
XmlConvert.DecodeName(row[FieldsTableColumn.ValueColumn].ToString())));
xw.WriteEndElement();
xw.WriteEndElement();
}
xw.WriteEndElement();
xw.Flush();
xw.Close();
}
return includeEditLink
? string.Format("[UDT:ListView][UDT:EditLink]{0}{1}", "\r\n", sw)
: sw.ToString();
}
}
}
}
| |
using UnityEngine;
using UnityEditor;
using System;
using System.Linq;
using System.Collections.Generic;
using System.IO;
using V1=AssetBundleGraph;
using Model=UnityEngine.AssetBundles.GraphTool.DataModel.Version2;
namespace UnityEngine.AssetBundles.GraphTool {
[CustomNode("Modify Assets/Modify Assets Directly", 61)]
public class Modifier : Node, Model.NodeDataImporter {
[SerializeField] private SerializableMultiTargetInstance m_instance;
public override string ActiveStyle {
get {
return "node 8 on";
}
}
public override string InactiveStyle {
get {
return "node 8";
}
}
public override string Category {
get {
return "Modify";
}
}
public override void Initialize(Model.NodeData data) {
m_instance = new SerializableMultiTargetInstance();
data.AddDefaultInputPoint();
data.AddDefaultOutputPoint();
}
public void Import(V1.NodeData v1, Model.NodeData v2) {
m_instance = new SerializableMultiTargetInstance(v1.ScriptClassName, v1.InstanceData);
}
public override Node Clone(Model.NodeData newData) {
var newNode = new Modifier();
newNode.m_instance = new SerializableMultiTargetInstance(m_instance);
newData.AddDefaultInputPoint();
newData.AddDefaultOutputPoint();
return newNode;
}
public override void OnInspectorGUI(NodeGUI node, AssetReferenceStreamManager streamManager, NodeGUIEditor editor, Action onValueChanged) {
EditorGUILayout.HelpBox("Modify Assets Directly: Modify assets.", MessageType.Info);
editor.UpdateNodeName(node);
GUILayout.Space(10f);
using (new EditorGUILayout.VerticalScope(GUI.skin.box)) {
Type incomingType = TypeUtility.FindFirstIncomingAssetType(streamManager, node.Data.InputPoints[0]);
var modifier = m_instance.Get<IModifier>(editor.CurrentEditingGroup);
if(incomingType == null) {
// if there is no asset input to determine incomingType,
// retrieve from assigned Modifier.
incomingType = ModifierUtility.GetModifierTargetType(m_instance.ClassName);
if(incomingType == null) {
EditorGUILayout.HelpBox("Modifier needs a single type from incoming assets.", MessageType.Info);
return;
}
}
Dictionary<string, string> map = null;
if(incomingType != null) {
map = ModifierUtility.GetAttributeAssemblyQualifiedNameMap(incomingType);
}
if(map != null && map.Count > 0) {
using(new GUILayout.HorizontalScope()) {
GUILayout.Label("Modifier");
var guiName = ModifierUtility.GetModifierGUIName(m_instance.ClassName);
if (GUILayout.Button(guiName, "Popup", GUILayout.MinWidth(150f))) {
var builders = map.Keys.ToList();
if(builders.Count > 0) {
NodeGUI.ShowTypeNamesMenu(guiName, builders, (string selectedGUIName) =>
{
using(new RecordUndoScope("Change Modifier class", node, true)) {
modifier = ModifierUtility.CreateModifier(selectedGUIName, incomingType);
m_instance.Set(editor.CurrentEditingGroup,modifier);
onValueChanged();
}
}
);
}
}
MonoScript s = TypeUtility.LoadMonoScript(m_instance.ClassName);
using(new EditorGUI.DisabledScope(s == null)) {
if(GUILayout.Button("Edit", GUILayout.Width(50))) {
AssetDatabase.OpenAsset(s, 0);
}
}
}
} else {
string[] menuNames = Model.Settings.GUI_TEXT_MENU_GENERATE_MODIFIER.Split('/');
if (incomingType == null) {
EditorGUILayout.HelpBox(
string.Format(
"You need to create at least one Modifier script to select script for Modifier. " +
"To start, select {0}>{1}>{2} menu and create a new script.",
menuNames[1],menuNames[2], menuNames[3]
), MessageType.Info);
} else {
EditorGUILayout.HelpBox(
string.Format(
"No CustomModifier found for {3} type. \n" +
"You need to create at least one Modifier script to select script for Modifier. " +
"To start, select {0}>{1}>{2} menu and create a new script.",
menuNames[1],menuNames[2], menuNames[3], incomingType.FullName
), MessageType.Info);
}
}
GUILayout.Space(10f);
editor.DrawPlatformSelector(node);
using (new EditorGUILayout.VerticalScope()) {
var disabledScope = editor.DrawOverrideTargetToggle(node, m_instance.ContainsValueOf(editor.CurrentEditingGroup), (bool enabled) => {
if(enabled) {
m_instance.CopyDefaultValueTo(editor.CurrentEditingGroup);
} else {
m_instance.Remove(editor.CurrentEditingGroup);
}
onValueChanged();
});
using (disabledScope) {
if (modifier != null) {
Action onChangedAction = () => {
using(new RecordUndoScope("Change Modifier Setting", node)) {
m_instance.Set(editor.CurrentEditingGroup, modifier);
onValueChanged();
}
};
modifier.OnInspectorGUI(onChangedAction);
}
}
}
}
}
public override void OnContextMenuGUI(GenericMenu menu) {
MonoScript s = TypeUtility.LoadMonoScript(m_instance.ClassName);
if(s != null) {
menu.AddItem(
new GUIContent("Edit Script"),
false,
() => {
AssetDatabase.OpenAsset(s, 0);
}
);
}
}
public override void Prepare (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output)
{
ValidateModifier(node, target, incoming,
(Type expectedType, Type foundType, AssetReference foundAsset) => {
throw new NodeException(string.Format("{3} :Modifier expect {0}, but different type of incoming asset is found({1} {2})",
expectedType.FullName, foundType.FullName, foundAsset.fileNameAndExtension, node.Name), node.Id);
},
() => {
throw new NodeException(node.Name + " :Modifier is not configured. Please configure from Inspector.", node.Id);
},
() => {
throw new NodeException(node.Name + " :Failed to create Modifier from settings. Please fix settings from Inspector.", node.Id);
},
(Type expectedType, Type incomingType) => {
throw new NodeException(string.Format("{0} :Incoming asset type is does not match with this Modifier (Expected type:{1}, Incoming type:{2}).",
node.Name, (expectedType != null)?expectedType.FullName:"null", (incomingType != null)?incomingType.FullName:"null"), node.Id);
}
);
if(incoming != null && Output != null) {
// Modifier does not add, filter or change structure of group, so just pass given group of assets
var dst = (connectionsToOutput == null || !connectionsToOutput.Any())?
null : connectionsToOutput.First();
foreach(var ag in incoming) {
Output(dst, ag.assetGroups);
}
}
}
public override void Build (BuildTarget target,
Model.NodeData node,
IEnumerable<PerformGraph.AssetGroups> incoming,
IEnumerable<Model.ConnectionData> connectionsToOutput,
PerformGraph.Output Output,
Action<Model.NodeData, string, float> progressFunc)
{
if(incoming == null) {
return;
}
var modifier = m_instance.Get<IModifier>(target);
UnityEngine.Assertions.Assert.IsNotNull(modifier);
bool isAnyAssetModified = false;
foreach(var ag in incoming) {
foreach(var assets in ag.assetGroups.Values) {
foreach(var asset in assets) {
if(modifier.IsModified(asset.allData)) {
modifier.Modify(asset.allData);
asset.SetDirty();
isAnyAssetModified = true;
}
}
}
}
if(isAnyAssetModified) {
// apply asset setting changes to AssetDatabase.
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
foreach(var ag in incoming) {
foreach(var assets in ag.assetGroups.Values) {
foreach(var asset in assets) {
asset.ReleaseData();
}
}
}
if(incoming != null && Output != null) {
// Modifier does not add, filter or change structure of group, so just pass given group of assets
var dst = (connectionsToOutput == null || !connectionsToOutput.Any())?
null : connectionsToOutput.First();
foreach(var ag in incoming) {
Output(dst, ag.assetGroups);
}
}
}
public void ValidateModifier (
Model.NodeData node,
BuildTarget target,
IEnumerable<PerformGraph.AssetGroups> incoming,
Action<Type, Type, AssetReference> multipleAssetTypeFound,
Action noModiferData,
Action failedToCreateModifier,
Action<Type, Type> incomingTypeMismatch
) {
Type expectedType = null;
if(incoming != null) {
expectedType = TypeUtility.FindFirstIncomingAssetType(incoming);
if(expectedType != null) {
foreach(var ag in incoming) {
foreach(var assets in ag.assetGroups.Values) {
foreach(var a in assets) {
Type assetType = a.filterType;
if(assetType != expectedType) {
multipleAssetTypeFound(expectedType, assetType, a);
}
}
}
}
}
}
// var modifier = ModifierUtility.CreateModifier(node, target);
//
if(m_instance.Get<IModifier>(target) == null) {
failedToCreateModifier();
}
// if there is no incoming assets, there is no way to check if
// right type of asset is coming in - so we'll just skip the test
// expectedType is not null when there is at least one incoming asset
if(incoming != null && expectedType != null) {
var targetType = ModifierUtility.GetModifierTargetType(m_instance.Get<IModifier>(target));
if( targetType != expectedType ) {
incomingTypeMismatch(targetType, expectedType);
}
}
}
}
}
| |
// 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.Sockets;
using System.Runtime.ExceptionServices;
namespace System.Net
{
/// <summary>
/// <para>
/// The FtpDataStream class implements the FTP data connection.
/// </para>
/// </summary>
internal class FtpDataStream : Stream, ICloseEx
{
private FtpWebRequest _request;
private NetworkStream _networkStream;
private bool _writeable;
private bool _readable;
private bool _isFullyRead = false;
private bool _closing = false;
private const int DefaultCloseTimeout = -1;
internal FtpDataStream(NetworkStream networkStream, FtpWebRequest request, TriState writeOnly)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this);
_readable = true;
_writeable = true;
if (writeOnly == TriState.True)
{
_readable = false;
}
else if (writeOnly == TriState.False)
{
_writeable = false;
}
_networkStream = networkStream;
_request = request;
}
protected override void Dispose(bool disposing)
{
try
{
if (disposing)
((ICloseEx)this).CloseEx(CloseExState.Normal);
else
((ICloseEx)this).CloseEx(CloseExState.Abort | CloseExState.Silent);
}
finally
{
base.Dispose(disposing);
}
}
//TODO: Add this to FxCopBaseline.cs once https://github.com/dotnet/roslyn/issues/15728 is fixed
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Reliability", "CA2002:DoNotLockOnObjectsWithWeakIdentity")]
void ICloseEx.CloseEx(CloseExState closeState)
{
if (NetEventSource.IsEnabled) NetEventSource.Info(this, $"state = {closeState}");
lock (this)
{
if (_closing == true)
return;
_closing = true;
_writeable = false;
_readable = false;
}
try
{
try
{
if ((closeState & CloseExState.Abort) == 0)
_networkStream.Close(DefaultCloseTimeout);
else
_networkStream.Close(0);
}
finally
{
_request.DataStreamClosed(closeState);
}
}
catch (Exception exception)
{
bool doThrow = true;
WebException webException = exception as WebException;
if (webException != null)
{
FtpWebResponse response = webException.Response as FtpWebResponse;
if (response != null)
{
if (!_isFullyRead
&& response.StatusCode == FtpStatusCode.ConnectionClosed)
doThrow = false;
}
}
if (doThrow)
if ((closeState & CloseExState.Silent) == 0)
throw;
}
}
private void CheckError()
{
if (_request.Aborted)
{
throw ExceptionHelper.RequestAbortedException;
}
}
public override bool CanRead
{
get
{
return _readable;
}
}
public override bool CanSeek
{
get
{
return _networkStream.CanSeek;
}
}
public override bool CanWrite
{
get
{
return _writeable;
}
}
public override long Length
{
get
{
return _networkStream.Length;
}
}
public override long Position
{
get
{
return _networkStream.Position;
}
set
{
_networkStream.Position = value;
}
}
public override long Seek(long offset, SeekOrigin origin)
{
CheckError();
try
{
return _networkStream.Seek(offset, origin);
}
catch
{
CheckError();
throw;
}
}
public override int Read(byte[] buffer, int offset, int size)
{
CheckError();
int readBytes;
try
{
readBytes = _networkStream.Read(buffer, offset, size);
}
catch
{
CheckError();
throw;
}
if (readBytes == 0)
{
_isFullyRead = true;
Close();
}
return readBytes;
}
public override void Write(byte[] buffer, int offset, int size)
{
CheckError();
try
{
_networkStream.Write(buffer, offset, size);
}
catch
{
CheckError();
throw;
}
}
private void AsyncReadCallback(IAsyncResult ar)
{
LazyAsyncResult userResult = (LazyAsyncResult)ar.AsyncState;
try
{
try
{
int readBytes = _networkStream.EndRead(ar);
if (readBytes == 0)
{
_isFullyRead = true;
Close(); // This should block for pipeline completion
}
userResult.InvokeCallback(readBytes);
}
catch (Exception exception)
{
// Complete with error. If already completed rethrow on the worker thread
if (!userResult.IsCompleted)
userResult.InvokeCallback(exception);
}
}
catch { }
}
public override IAsyncResult BeginRead(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
CheckError();
LazyAsyncResult userResult = new LazyAsyncResult(this, state, callback);
try
{
_networkStream.BeginRead(buffer, offset, size, new AsyncCallback(AsyncReadCallback), userResult);
}
catch
{
CheckError();
throw;
}
return userResult;
}
public override int EndRead(IAsyncResult ar)
{
try
{
object result = ((LazyAsyncResult)ar).InternalWaitForCompletion();
if (result is Exception e)
{
ExceptionDispatchInfo.Throw(e);
}
return (int)result;
}
finally
{
CheckError();
}
}
public override IAsyncResult BeginWrite(byte[] buffer, int offset, int size, AsyncCallback callback, object state)
{
CheckError();
try
{
return _networkStream.BeginWrite(buffer, offset, size, callback, state);
}
catch
{
CheckError();
throw;
}
}
public override void EndWrite(IAsyncResult asyncResult)
{
try
{
_networkStream.EndWrite(asyncResult);
}
finally
{
CheckError();
}
}
public override void Flush()
{
_networkStream.Flush();
}
public override void SetLength(long value)
{
_networkStream.SetLength(value);
}
public override bool CanTimeout
{
get
{
return _networkStream.CanTimeout;
}
}
public override int ReadTimeout
{
get
{
return _networkStream.ReadTimeout;
}
set
{
_networkStream.ReadTimeout = value;
}
}
public override int WriteTimeout
{
get
{
return _networkStream.WriteTimeout;
}
set
{
_networkStream.WriteTimeout = value;
}
}
internal void SetSocketTimeoutOption(int timeout)
{
_networkStream.ReadTimeout = timeout;
_networkStream.WriteTimeout = timeout;
}
}
}
| |
namespace PokerTell.PokerHand.Services
{
using System;
using System.Reflection;
using log4net;
using PokerTell.Infrastructure.Enumerations.PokerHand;
using PokerTell.Infrastructure.Interfaces;
using PokerTell.Infrastructure.Interfaces.PokerHand;
using PokerTell.PokerHand.Interfaces;
public class PokerRoundsConverter : IPokerRoundsConverter
{
protected int ActionCount;
protected bool FoundAction;
protected double Pot;
protected IConvertedPokerRound SequenceForCurrentRound;
protected string SequenceSoFar;
protected double ToCall;
static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
readonly IPokerActionConverter _actionConverter;
readonly IConstructor<IConvertedPokerActionWithId> _convertedActionWithId;
readonly IConstructor<IConvertedPokerRound> _convertedRound;
IAquiredPokerHand _aquiredHand;
IConvertedPokerHand _convertedHand;
public PokerRoundsConverter(
IConstructor<IConvertedPokerActionWithId> convertedActionWithId,
IConstructor<IConvertedPokerRound> convertedRound,
IPokerActionConverter actionConverter)
{
_convertedActionWithId = convertedActionWithId;
_convertedRound = convertedRound;
_actionConverter = actionConverter;
}
bool HeadsUp
{
get { return _aquiredHand.TotalPlayers == 2; }
}
bool ThreeOrMore
{
get { return _aquiredHand.TotalPlayers >= 3; }
}
public virtual IConvertedPokerHand ConvertFlopTurnAndRiver()
{
for (Streets street = Streets.Flop; street <= Streets.River; street++)
{
ActionCount = 0;
SequenceSoFar = string.Empty;
SequenceForCurrentRound = _convertedRound.New;
// Do as long as we still find an action of ANY Player
do
{
FoundAction = false;
int fromPlayer;
int toPlayer;
if (HeadsUp)
{
// BigBlind acts before button (small Blind)
fromPlayer = 1;
toPlayer = 0;
ProcessPlayersForRound(street, fromPlayer, toPlayer);
}
else if (ThreeOrMore)
{
fromPlayer = 0;
toPlayer = _aquiredHand.Players.Count - 1;
ProcessPlayersForRound(street, fromPlayer, toPlayer);
}
ActionCount++;
}
while (FoundAction);
_convertedHand.Sequences[(int)street] = SequenceForCurrentRound;
}
return _convertedHand;
}
public virtual IPokerRoundsConverter ConvertPreflop()
{
// At this point all posting has been removed
SequenceForCurrentRound = _convertedRound.New;
ActionCount = 0;
// Do as long as we still find an action of ANY Player
do
{
FoundAction = false;
SequenceSoFar = string.Empty;
int fromPlayer;
int toPlayer;
if (HeadsUp)
{
fromPlayer = 0;
toPlayer = 1;
ProcessPlayersForRound(Streets.PreFlop, fromPlayer, toPlayer);
}
else if (ThreeOrMore)
{
// Preflop Blinds are last
// Everyone but blinds
fromPlayer = 2;
toPlayer = _aquiredHand.Players.Count - 1;
ProcessPlayersForRound(Streets.PreFlop, fromPlayer, toPlayer);
// Blinds
fromPlayer = 0;
toPlayer = 1;
ProcessPlayersForRound(Streets.PreFlop, fromPlayer, toPlayer);
}
ActionCount++;
}
while (FoundAction);
_convertedHand.Sequences[(int)Streets.PreFlop] = SequenceForCurrentRound;
return this;
}
public IPokerRoundsConverter InitializeWith(
IAquiredPokerHand aquiredHand, IConvertedPokerHand convertedHand, double pot, double toCall)
{
ToCall = toCall;
Pot = pot;
_convertedHand = convertedHand;
_aquiredHand = aquiredHand;
return this;
}
protected virtual void ProcessPlayersForRound(Streets street, int fromPlayer, int toPlayer)
{
if (fromPlayer <= toPlayer)
{
for (int playerIndex = fromPlayer; playerIndex <= toPlayer; playerIndex++)
{
// Check if non empty bettinground for that player exists in the current round
IAquiredPokerPlayer aquiredPlayer = _aquiredHand[playerIndex];
if (aquiredPlayer.Count > (int)street && aquiredPlayer[street].Actions.Count > ActionCount)
ProcessRound(street, aquiredPlayer[street], _convertedHand[playerIndex]);
}
}
else
{
// Headsup Postflop
for (int playerIndex = fromPlayer; playerIndex >= toPlayer; playerIndex--)
{
// Check if non empty bettinground for that player exists in the current round
IAquiredPokerPlayer aquiredPlayer = _aquiredHand[playerIndex];
if (aquiredPlayer.Count > (int)street && aquiredPlayer[street].Actions.Count > ActionCount)
ProcessRound(street, aquiredPlayer[street], _convertedHand[playerIndex]);
}
}
}
protected virtual void ProcessRound(Streets street, IAquiredPokerRound aquiredPokerRound, IConvertedPokerPlayer convertedPlayer)
{
try
{
FoundAction = true;
// Ignore returned chips (they didn't add or substract from the pot
// and this action was not "done" by the player
if (aquiredPokerRound[ActionCount].What != ActionTypes.U)
{
IConvertedPokerAction convertedAction =
_actionConverter.Convert(
aquiredPokerRound[ActionCount], ref Pot, ref ToCall, _aquiredHand.TotalPot);
SequenceForCurrentRound.Add(
_convertedActionWithId.New.InitializeWith(convertedAction, convertedPlayer.Position));
SetActionSequenceAndAddActionTo(convertedPlayer, convertedAction, street);
}
}
catch (Exception excep)
{
Log.Error("Unhandled", excep);
}
}
void SetActionSequenceAndAddActionTo(IConvertedPokerPlayer convertedPlayer, IConvertedPokerAction convertedAction, Streets street)
{
convertedPlayer.SetActionSequenceString(ref SequenceSoFar, convertedAction, street);
if (convertedPlayer.Rounds != null && convertedPlayer.Rounds.Count < (int)street + 1)
{
convertedPlayer.Add();
}
convertedPlayer[street].Add(convertedAction);
}
}
}
| |
using System;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading.Tasks;
using MockServerClientNet.Model;
using MockServerClientNet.Model.Body;
using Xunit;
using static MockServerClientNet.Model.Body.Matchers;
using static MockServerClientNet.Model.HttpResponse;
using static MockServerClientNet.Model.HttpRequest;
namespace MockServerClientNet.Tests
{
public class BodyMatcherTest : MockServerClientTest
{
[Fact]
public async Task ShouldMatchExactString()
{
await SetupRequestBodyExpectation(MatchingExactString("some"));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", "some")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", "some_string")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchSubString()
{
await SetupRequestBodyExpectation(MatchingSubString("some"));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", "some_string")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", "other_string")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchNotExactString()
{
await SetupRequestBodyExpectation(Not(MatchingExactString("some")));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", "other")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", "some")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchBinary()
{
await SetupRequestBodyExpectation(MatchingBinary(new byte[] {1, 2, 3}));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", new byte[] {1, 2, 3})
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", new byte[] {1, 2})
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchBinaryFromMemoryStream()
{
byte[] bytes;
using (var byteStream = new MemoryStream())
{
using (var writer = new StreamWriter(byteStream))
{
await writer.WriteLineAsync("This is a test line");
}
bytes = byteStream.GetBuffer();
await SetupRequestBodyExpectation(MatchingBinary(byteStream));
}
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", bytes)
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", new byte[] {1, 2, 3})
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchBinaryFromFile()
{
byte[] bytes;
using (var fileStream = File.OpenRead(Path.Combine("TestFiles", "SampleText.txt")))
{
using (var byteStream = new MemoryStream())
{
await fileStream.CopyToAsync(byteStream);
bytes = byteStream.GetBuffer();
}
fileStream.Position = 0;
await SetupRequestBodyExpectation(MatchingBinary(fileStream));
}
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", bytes)
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", new byte[] {1, 2, 3})
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchStrictXml()
{
await SetupRequestBodyExpectation(MatchingXml(
@"<department>
<employee>
<name>John Doe</name>
<age>45</age>
</employee>
<employee>
<name>Jane Doe</name>
<age>38</age>
</employee>
</department>"));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"<department>
<employee>
<name>John Doe</name>
<age>45</age>
</employee>
<employee>
<name>Jane Doe</name>
<age>38</age>
</employee>
</department>")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"<department>
<employee>
<name>John Doe</name>
<age>40</age>
</employee>
</department>")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchPartialJson()
{
await SetupRequestBodyExpectation(MatchingJson(
@"{ ""department"": {
""employee"": [
{ ""name"": ""John Doe"", ""age"": 45 }
]
}
}"));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"{ ""department"": {
""employee"": [
{ ""name"": ""John Doe"", ""age"": 45, ""address"": ""World"" },
{ ""name"": ""Jane Doe"", ""age"": 38, ""address"": ""World"" }
]
}
}")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"{ ""department"": {
""employee"": [
{ ""name"": ""John Doe"", ""age"": 40 },
{ ""name"": ""Jane Doe"", ""age"": 30 }
]
}
}")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchStrictJson()
{
await SetupRequestBodyExpectation(MatchingStrictJson(
@"{ ""department"": {
""employee"": [
{ ""name"": ""John Doe"", ""age"": 45 },
{ ""name"": ""Jane Doe"", ""age"": 38 }
]
}
}"));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"{ ""department"": {
""employee"": [
{ ""name"": ""John Doe"", ""age"": 45 },
{ ""name"": ""Jane Doe"", ""age"": 38 }
]
}
}")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"{ ""department"": {
""employee"": [
{ ""name"": ""John Doe"", ""age"": 45, ""address"": ""World"" },
{ ""name"": ""Jane Doe"", ""age"": 38, ""address"": ""World"" }
]
}
}")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchXPath()
{
await SetupRequestBodyExpectation(MatchingXPath("/department/employee[age>40]/name"));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"<department>
<employee>
<name>John Doe</name>
<age>45</age>
</employee>
<employee>
<name>Jane Doe</name>
<age>38</age>
</employee>
</department>")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"<department>
<employee>
<name>John Doe</name>
<age>40</age>
</employee>
<employee>
<name>Jane Doe</name>
<age>38</age>
</employee>
</department>")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchJsonPath()
{
await SetupRequestBodyExpectation(MatchingJsonPath("$.department.employee[?(@.age > 40)]"));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"{ ""department"": {
""employee"": [
{ ""name"": ""John Doe"", ""age"": 45 },
{ ""name"": ""Jane Doe"", ""age"": 38 }
]
}
}")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"{ ""department"": {
""employee"": [
{ ""name"": ""John Doe"", ""age"": 40 },
{ ""name"": ""Jane Doe"", ""age"": 38 }
]
}
}")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchXmlSchema()
{
await SetupRequestBodyExpectation(MatchingXmlSchema(
@"<xs:schema xmlns:xs=""http://www.w3.org/2001/XMLSchema"">
<xs:element name=""department"">
<xs:complexType>
<xs:sequence>
<xs:element name=""employee"" maxOccurs=""unbounded"" minOccurs=""0"">
<xs:complexType>
<xs:sequence>
<xs:element type=""xs:string"" name=""name""/>
<xs:element type=""xs:byte"" name=""age""/>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:sequence>
</xs:complexType>
</xs:element>
</xs:schema>"));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"<department>
<employee>
<name>John Doe</name>
<age>45</age>
</employee>
<employee>
<name>Jane Doe</name>
<age>38</age>
</employee>
</department>")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"<department>
<employee>
<name>John Doe</name>
</employee>
<employee>
<name>Jane Doe</name>
</employee>
</department>")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchJsonSchema()
{
await SetupRequestBodyExpectation(MatchingJsonSchema(
@"{ ""$schema"": ""http://json-schema.org/draft-04/schema#"",
""type"": ""object"",
""properties"": {
""department"": {
""type"": ""object"",
""properties"": {
""employee"": {
""type"": ""array"",
""items"": [
{
""type"": ""object"",
""properties"": {
""name"": { ""type"": ""string"" },
""age"": { ""type"": ""integer"" }
},
""required"": [ ""name"", ""age"" ]
}
]
}
},
""required"": [ ""employee"" ]
}
},
""required"": [ ""department"" ]
}"));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"{ ""department"": {
""employee"": [
{ ""name"": ""John Doe"", ""age"": 45 },
{ ""name"": ""Jane Doe"", ""age"": 38 }
]
}
}")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/",
@"{ ""department"": {
""employee"": [
{ ""name"": ""John Doe"" },
{ ""name"": ""Jane Doe"" }
]
}
}")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public async Task ShouldMatchRegex()
{
await SetupRequestBodyExpectation(MatchingRegex("some_.*_value"));
var response = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", "some_longer_value")
);
Assert.Equal("response", await response.Content.ReadAsStringAsync());
Assert.Equal(HttpStatusCode.OK, response.StatusCode);
var failResponse = await SendRequestAsync(
BuildRequest(HttpMethod.Post, "/", "some_value")
);
Assert.Equal(HttpStatusCode.NotFound, failResponse.StatusCode);
}
[Fact]
public void ShouldNegateBodyMatcher()
{
var negated = Not(MatchingExactString("some"));
Assert.True(negated.IsNot);
var negatedTwice = Not(Not(MatchingExactString("some")));
Assert.False(negatedTwice.IsNot);
}
private async Task SetupRequestBodyExpectation(BodyMatcher requestBody)
{
await MockServerClient
.When(Request()
.WithMethod(HttpMethod.Post)
.WithBody(requestBody),
Times.Unlimited())
.RespondAsync(Response()
.WithStatusCode(200)
.WithBody("response")
.WithDelay(TimeSpan.Zero)
);
}
}
}
| |
using System;
using System.Threading.Tasks;
using IxMilia.BCad.Entities;
using IxMilia.BCad.Extensions;
using IxMilia.BCad.Primitives;
using IxMilia.BCad.Utilities;
using IxMilia.BCad.Helpers;
namespace IxMilia.BCad.Commands
{
public class DrawCircleCommand : ICadCommand
{
private static readonly double IsoMinorRatio = Math.Sqrt(1.5) / Math.Sqrt(2.0) * 2.0 / 3.0;
private enum CircleMode
{
Radius,
Diameter,
Isometric
}
public async Task<bool> Execute(IWorkspace workspace, object arg)
{
Entity circle = null;
var drawingPlane = workspace.DrawingPlane;
var cen = await workspace.InputService.GetPoint(new UserDirective("Select center, [ttr], or [th]ree-point", "ttr", "th"));
if (cen.Cancel) return false;
if (cen.HasValue)
{
var mode = CircleMode.Radius;
while (circle == null)
{
switch (mode)
{
case CircleMode.Radius:
{
var rad = await workspace.InputService.GetPoint(new UserDirective("Enter radius or [d]iameter/[i]sometric", "d", "i"), (p) =>
{
return new IPrimitive[]
{
new PrimitiveLine(cen.Value, p),
new PrimitiveEllipse(cen.Value, (p - cen.Value).Length, drawingPlane.Normal)
};
});
if (rad.Cancel) return false;
if (rad.HasValue)
{
circle = new Circle(cen.Value, (rad.Value - cen.Value).Length, drawingPlane.Normal);
}
else // switch modes
{
if (rad.Directive == null)
{
return false;
}
switch (rad.Directive)
{
case "d":
mode = CircleMode.Diameter;
break;
case "i":
mode = CircleMode.Isometric;
break;
}
}
break;
}
case CircleMode.Diameter:
{
var dia = await workspace.InputService.GetPoint(new UserDirective("Enter diameter or [r]adius/[i]sometric", "r", "i"), (p) =>
{
return new IPrimitive[]
{
new PrimitiveLine(cen.Value, p),
new PrimitiveEllipse(cen.Value, (p - cen.Value).Length, drawingPlane.Normal)
};
});
if (dia.Cancel) return false;
if (dia.HasValue)
{
circle = new Circle(cen.Value, (dia.Value - cen.Value).Length * 0.5, drawingPlane.Normal);
}
else // switch modes
{
if (dia.Directive == null)
{
return false;
}
switch (dia.Directive)
{
case "r":
mode = CircleMode.Radius;
break;
case "i":
mode = CircleMode.Isometric;
break;
}
}
break;
}
case CircleMode.Isometric:
{
var isoRad = await workspace.InputService.GetPoint(new UserDirective("Enter isometric-radius or [r]adius/[d]iameter", "r", "d"), (p) =>
{
return new IPrimitive[]
{
new PrimitiveLine(cen.Value, p),
new PrimitiveEllipse(cen.Value,
Vector.SixtyDegrees * (p - cen.Value).Length * MathHelper.SqrtThreeHalves,
drawingPlane.Normal,
IsoMinorRatio,
0.0,
360.0)
};
});
if (isoRad.Cancel) return false;
if (isoRad.HasValue)
{
circle = new Ellipse(cen.Value,
Vector.SixtyDegrees * (isoRad.Value - cen.Value).Length * MathHelper.SqrtThreeHalves,
IsoMinorRatio,
0.0,
360.0,
drawingPlane.Normal);
}
else // switch modes
{
if (isoRad.Directive == null)
{
return false;
}
switch (isoRad.Directive)
{
case "r":
mode = CircleMode.Radius;
break;
case "d":
mode = CircleMode.Diameter;
break;
}
}
break;
}
}
}
}
else
{
switch (cen.Directive)
{
case "ttr":
var firstEntity = await workspace.InputService.GetEntity(new UserDirective("First entity"));
if (firstEntity.Cancel || !firstEntity.HasValue)
break;
var secondEntity = await workspace.InputService.GetEntity(new UserDirective("Second entity"));
if (secondEntity.Cancel || !secondEntity.HasValue)
break;
var radius = await workspace.InputService.GetDistance();
var ellipse = EditUtilities.Ttr(drawingPlane, firstEntity.Value, secondEntity.Value, radius.Value);
if (ellipse != null)
{
circle = ellipse.ToEntity();
}
break;
case "2":
break;
case "th":
var first = await workspace.InputService.GetPoint(new UserDirective("First point"));
if (first.Cancel || !first.HasValue)
break;
var second = await workspace.InputService.GetPoint(new UserDirective("Second point"), p =>
new[]
{
new PrimitiveLine(first.Value, p)
});
if (second.Cancel || !second.HasValue)
break;
var third = await workspace.InputService.GetPoint(new UserDirective("Third point"), p =>
{
var c = PrimitiveEllipse.ThreePointCircle(first.Value, second.Value, p);
if (c == null)
return new IPrimitive[]
{
new PrimitiveLine(first.Value, second.Value),
new PrimitiveLine(second.Value, p),
new PrimitiveLine(p, first.Value)
};
else
return new IPrimitive[]
{
new PrimitiveLine(first.Value, second.Value),
new PrimitiveLine(second.Value, p),
new PrimitiveLine(p, first.Value),
c
};
});
if (third.Cancel || !third.HasValue)
break;
var circ = PrimitiveEllipse.ThreePointCircle(first.Value, second.Value, third.Value);
if (circ != null)
{
circle = new Circle(circ.Center, circ.MajorAxis.Length, circ.Normal);
}
break;
}
}
if (circle != null)
{
workspace.AddToCurrentLayer(circle);
}
return true;
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System.Linq;
using Test.Cryptography;
using Xunit;
namespace System.Security.Cryptography.X509Certificates.Tests
{
public static class ExtensionsTests
{
[Fact]
public static void ReadExtensions()
{
using (X509Certificate2 c = new X509Certificate2(TestData.MsCertificate))
{
X509ExtensionCollection exts = c.Extensions;
int count = exts.Count;
Assert.Equal(6, count);
X509Extension[] extensions = new X509Extension[count];
exts.CopyTo(extensions, 0);
extensions = extensions.OrderBy(e => e.Oid.Value).ToArray();
// There are an awful lot of magic-looking values in this large test.
// These values are embedded within the certificate, and the test is
// just verifying the object interpretation. In the event the test data
// (TestData.MsCertificate) is replaced, this whole body will need to be
// redone.
{
// Authority Information Access
X509Extension aia = extensions[0];
Assert.Equal("1.3.6.1.5.5.7.1.1", aia.Oid.Value);
Assert.False(aia.Critical);
byte[] expectedDer = (
"304c304a06082b06010505073002863e687474703a2f2f7777772e6d" +
"6963726f736f66742e636f6d2f706b692f63657274732f4d6963436f" +
"645369675043415f30382d33312d323031302e637274").HexToByteArray();
Assert.Equal(expectedDer, aia.RawData);
}
{
// Subject Key Identifier
X509Extension skid = extensions[1];
Assert.Equal("2.5.29.14", skid.Oid.Value);
Assert.False(skid.Critical);
byte[] expected = "04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray();
Assert.Equal(expected, skid.RawData);
Assert.True(skid is X509SubjectKeyIdentifierExtension);
X509SubjectKeyIdentifierExtension rich = (X509SubjectKeyIdentifierExtension)skid;
Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", rich.SubjectKeyIdentifier);
}
{
// Subject Alternative Names
X509Extension sans = extensions[2];
Assert.Equal("2.5.29.17", sans.Oid.Value);
Assert.False(sans.Critical);
byte[] expected = (
"3048a4463044310d300b060355040b13044d4f505231333031060355" +
"0405132a33313539352b34666166306237312d616433372d34616133" +
"2d613637312d373662633035323334346164").HexToByteArray();
Assert.Equal(expected, sans.RawData);
}
{
// CRL Distribution Points
X509Extension cdps = extensions[3];
Assert.Equal("2.5.29.31", cdps.Oid.Value);
Assert.False(cdps.Critical);
byte[] expected = (
"304d304ba049a0478645687474703a2f2f63726c2e6d6963726f736f" +
"66742e636f6d2f706b692f63726c2f70726f64756374732f4d696343" +
"6f645369675043415f30382d33312d323031302e63726c").HexToByteArray();
Assert.Equal(expected, cdps.RawData);
}
{
// Authority Key Identifier
X509Extension akid = extensions[4];
Assert.Equal("2.5.29.35", akid.Oid.Value);
Assert.False(akid.Critical);
byte[] expected = "30168014cb11e8cad2b4165801c9372e331616b94c9a0a1f".HexToByteArray();
Assert.Equal(expected, akid.RawData);
}
{
// Extended Key Usage (X.509/2000 says Extended, Win32/NetFX say Enhanced)
X509Extension eku = extensions[5];
Assert.Equal("2.5.29.37", eku.Oid.Value);
Assert.False(eku.Critical);
byte[] expected = "300a06082b06010505070303".HexToByteArray();
Assert.Equal(expected, eku.RawData);
Assert.True(eku is X509EnhancedKeyUsageExtension);
X509EnhancedKeyUsageExtension rich = (X509EnhancedKeyUsageExtension)eku;
OidCollection usages = rich.EnhancedKeyUsages;
Assert.Equal(1, usages.Count);
Oid oid = usages[0];
// Code Signing
Assert.Equal("1.3.6.1.5.5.7.3.3", oid.Value);
}
}
}
[Fact]
public static void KeyUsageExtensionDefaultCtor()
{
X509KeyUsageExtension e = new X509KeyUsageExtension();
string oidValue = e.Oid.Value;
Assert.Equal("2.5.29.15", oidValue);
byte[] r = e.RawData;
Assert.Null(r);
X509KeyUsageFlags keyUsages = e.KeyUsages;
Assert.Equal(X509KeyUsageFlags.None, keyUsages);
}
[Fact]
public static void KeyUsageExtension_CrlSign()
{
TestKeyUsageExtension(X509KeyUsageFlags.CrlSign, false, "03020102".HexToByteArray());
}
[Fact]
public static void KeyUsageExtension_DataEncipherment()
{
TestKeyUsageExtension(X509KeyUsageFlags.DataEncipherment, false, "03020410".HexToByteArray());
}
[Fact]
public static void KeyUsageExtension_DecipherOnly()
{
TestKeyUsageExtension(X509KeyUsageFlags.DecipherOnly, false, "0303070080".HexToByteArray());
}
[Fact]
public static void KeyUsageExtension_DigitalSignature()
{
TestKeyUsageExtension(X509KeyUsageFlags.DigitalSignature, false, "03020780".HexToByteArray());
}
[Fact]
public static void KeyUsageExtension_EncipherOnly()
{
TestKeyUsageExtension(X509KeyUsageFlags.EncipherOnly, false, "03020001".HexToByteArray());
}
[Fact]
public static void KeyUsageExtension_KeyAgreement()
{
TestKeyUsageExtension(X509KeyUsageFlags.KeyAgreement, false, "03020308".HexToByteArray());
}
[Fact]
public static void KeyUsageExtension_KeyCertSign()
{
TestKeyUsageExtension(X509KeyUsageFlags.KeyCertSign, false, "03020204".HexToByteArray());
}
[Fact]
public static void KeyUsageExtension_KeyEncipherment()
{
TestKeyUsageExtension(X509KeyUsageFlags.KeyEncipherment, false, "03020520".HexToByteArray());
}
[Fact]
public static void KeyUsageExtension_None()
{
TestKeyUsageExtension(X509KeyUsageFlags.None, false, "030100".HexToByteArray());
}
[Fact]
public static void KeyUsageExtension_NonRepudiation()
{
TestKeyUsageExtension(X509KeyUsageFlags.NonRepudiation, false, "03020640".HexToByteArray());
}
[Fact]
public static void KeyUsageExtension_BER()
{
// Extensions encoded inside PKCS#8 on Windows may use BER encoding that would be invalid DER.
// Ensure that no exception is thrown and the value is decoded correctly.
X509KeyUsageExtension ext;
ext = new X509KeyUsageExtension(new AsnEncodedData("230403020080".HexToByteArray()), false);
Assert.Equal(X509KeyUsageFlags.DigitalSignature, ext.KeyUsages);
ext = new X509KeyUsageExtension(new AsnEncodedData("038200020080".HexToByteArray()), false);
Assert.Equal(X509KeyUsageFlags.DigitalSignature, ext.KeyUsages);
}
[Fact]
public static void BasicConstraintsExtensionDefault()
{
X509BasicConstraintsExtension e = new X509BasicConstraintsExtension();
string oidValue = e.Oid.Value;
Assert.Equal("2.5.29.19", oidValue);
byte[] rawData = e.RawData;
Assert.Null(rawData);
Assert.False(e.CertificateAuthority);
Assert.False(e.HasPathLengthConstraint);
Assert.Equal(0, e.PathLengthConstraint);
}
[Theory]
[MemberData(nameof(BasicConstraintsData))]
public static void BasicConstraintsExtensionEncode(
bool certificateAuthority,
bool hasPathLengthConstraint,
int pathLengthConstraint,
bool critical,
string expectedDerString)
{
X509BasicConstraintsExtension ext = new X509BasicConstraintsExtension(
certificateAuthority,
hasPathLengthConstraint,
pathLengthConstraint,
critical);
byte[] expectedDer = expectedDerString.HexToByteArray();
Assert.Equal(expectedDer, ext.RawData);
}
[Theory]
[MemberData(nameof(BasicConstraintsData))]
public static void BasicConstraintsExtensionDecode(
bool certificateAuthority,
bool hasPathLengthConstraint,
int pathLengthConstraint,
bool critical,
string rawDataString)
{
byte[] rawData = rawDataString.HexToByteArray();
int expectedPathLengthConstraint = hasPathLengthConstraint ? pathLengthConstraint : 0;
X509BasicConstraintsExtension ext = new X509BasicConstraintsExtension(new AsnEncodedData(rawData), critical);
Assert.Equal(certificateAuthority, ext.CertificateAuthority);
Assert.Equal(hasPathLengthConstraint, ext.HasPathLengthConstraint);
Assert.Equal(expectedPathLengthConstraint, ext.PathLengthConstraint);
}
public static object[][] BasicConstraintsData = new object[][]
{
new object[] { false, false, 0, false, "3000" },
new object[] { false, false, 121, false, "3000" },
new object[] { true, false, 0, false, "30030101ff" },
new object[] { false, true, 0, false, "3003020100" },
new object[] { false, true, 7654321, false, "3005020374cbb1" },
new object[] { true, true, 559, false, "30070101ff0202022f" },
};
[Fact]
public static void BasicConstraintsExtension_BER()
{
// Extensions encoded inside PKCS#8 on Windows may use BER encoding that would be invalid DER.
// Ensure that no exception is thrown and the value is decoded correctly.
X509BasicConstraintsExtension ext;
ext = new X509BasicConstraintsExtension(new AsnEncodedData("30800101000201080000".HexToByteArray()), false);
Assert.Equal(false, ext.CertificateAuthority);
Assert.Equal(true, ext.HasPathLengthConstraint);
Assert.Equal(8, ext.PathLengthConstraint);
}
[Fact]
public static void EnhancedKeyUsageExtensionDefault()
{
X509EnhancedKeyUsageExtension e = new X509EnhancedKeyUsageExtension();
string oidValue = e.Oid.Value;
Assert.Equal("2.5.29.37", oidValue);
byte[] rawData = e.RawData;
Assert.Null(rawData);
OidCollection usages = e.EnhancedKeyUsages;
Assert.Equal(0, usages.Count);
}
[Fact]
public static void EnhancedKeyUsageExtension_Empty()
{
OidCollection usages = new OidCollection();
TestEnhancedKeyUsageExtension(usages, false, "3000".HexToByteArray());
}
[Fact]
public static void EnhancedKeyUsageExtension_2Oids()
{
Oid oid1 = new Oid("1.3.6.1.5.5.7.3.1");
Oid oid2 = new Oid("1.3.6.1.4.1.311.10.3.1");
OidCollection usages = new OidCollection();
usages.Add(oid1);
usages.Add(oid2);
TestEnhancedKeyUsageExtension(usages, false, "301606082b06010505070301060a2b0601040182370a0301".HexToByteArray());
}
[Theory]
[InlineData("1")]
[InlineData("3.0")]
[InlineData("Invalid Value")]
public static void EnhancedKeyUsageExtension_InvalidOid(string invalidOidValue)
{
OidCollection oids = new OidCollection
{
new Oid(invalidOidValue)
};
Assert.ThrowsAny<CryptographicException>(() => new X509EnhancedKeyUsageExtension(oids, false));
}
[Fact]
public static void EnhancedKeyUsageExtension_ImmutableOids()
{
Oid oid1 = new Oid("1.3.6.1.5.5.7.3.1");
OidCollection usages = new OidCollection();
X509EnhancedKeyUsageExtension e = new X509EnhancedKeyUsageExtension(usages, false);
Assert.Equal(0, e.EnhancedKeyUsages.Count);
usages.Add(oid1);
Assert.Equal(0, e.EnhancedKeyUsages.Count);
e.EnhancedKeyUsages.Add(oid1);
Assert.Equal(0, e.EnhancedKeyUsages.Count);
Assert.NotSame(e.EnhancedKeyUsages, e.EnhancedKeyUsages);
}
[Fact]
public static void SubjectKeyIdentifierExtensionDefault()
{
X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension();
string oidValue = e.Oid.Value;
Assert.Equal("2.5.29.14", oidValue);
byte[] rawData = e.RawData;
Assert.Null(rawData);
string skid = e.SubjectKeyIdentifier;
Assert.Null(skid);
}
[Fact]
public static void SubjectKeyIdentifierExtension_Bytes()
{
byte[] sk = { 1, 2, 3, 4 };
X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(sk, false);
byte[] rawData = e.RawData;
Assert.Equal("040401020304".HexToByteArray(), rawData);
e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false);
string skid = e.SubjectKeyIdentifier;
Assert.Equal("01020304", skid);
}
[Fact]
public static void SubjectKeyIdentifierExtension_String()
{
string sk = "01ABcd";
X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(sk, false);
byte[] rawData = e.RawData;
Assert.Equal("040301abcd".HexToByteArray(), rawData);
e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false);
string skid = e.SubjectKeyIdentifier;
Assert.Equal("01ABCD", skid);
}
[Fact]
public static void SubjectKeyIdentifierExtension_PublicKey()
{
PublicKey pk;
using (var cert = new X509Certificate2(TestData.MsCertificate))
{
pk = cert.PublicKey;
}
X509SubjectKeyIdentifierExtension e = new X509SubjectKeyIdentifierExtension(pk, false);
byte[] rawData = e.RawData;
Assert.Equal("04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(), rawData);
e = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false);
string skid = e.SubjectKeyIdentifier;
Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", skid);
}
[Fact]
public static void SubjectKeyIdentifierExtension_PublicKeySha1()
{
TestSubjectKeyIdentifierExtension(
TestData.MsCertificate,
X509SubjectKeyIdentifierHashAlgorithm.Sha1,
false,
"04145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray(),
"5971A65A334DDA980780FF841EBE87F9723241F2");
}
[Fact]
public static void SubjectKeyIdentifierExtension_PublicKeyShortSha1()
{
TestSubjectKeyIdentifierExtension(
TestData.MsCertificate,
X509SubjectKeyIdentifierHashAlgorithm.ShortSha1,
false,
"04084ebe87f9723241f2".HexToByteArray(),
"4EBE87F9723241F2");
}
[Fact]
public static void SubjectKeyIdentifierExtension_PublicKeyCapiSha1()
{
TestSubjectKeyIdentifierExtension(
TestData.MsCertificate,
X509SubjectKeyIdentifierHashAlgorithm.CapiSha1,
false,
"0414a260a870be1145ed71e2bb5aa19463a4fe9dcc41".HexToByteArray(),
"A260A870BE1145ED71E2BB5AA19463A4FE9DCC41");
}
[Fact]
public static void SubjectKeyIdentifierExtension_BER()
{
// Extensions encoded inside PKCS#8 on Windows may use BER encoding that would be invalid DER.
// Ensure that no exception is thrown and the value is decoded correctly.
X509SubjectKeyIdentifierExtension ext;
byte[] rawData = "0481145971a65a334dda980780ff841ebe87f9723241f2".HexToByteArray();
ext = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), false);
string skid = ext.SubjectKeyIdentifier;
Assert.Equal("5971A65A334DDA980780FF841EBE87F9723241F2", skid);
}
[Fact]
public static void ReadInvalidExtension_KeyUsage()
{
X509KeyUsageExtension keyUsageExtension =
new X509KeyUsageExtension(new AsnEncodedData(Array.Empty<byte>()), false);
Assert.ThrowsAny<CryptographicException>(() => keyUsageExtension.KeyUsages);
}
private static void TestKeyUsageExtension(X509KeyUsageFlags flags, bool critical, byte[] expectedDer)
{
X509KeyUsageExtension ext = new X509KeyUsageExtension(flags, critical);
byte[] rawData = ext.RawData;
Assert.Equal(expectedDer, rawData);
// Assert that format doesn't crash
string s = ext.Format(false);
// Rebuild it from the RawData.
ext = new X509KeyUsageExtension(new AsnEncodedData(rawData), critical);
Assert.Equal(flags, ext.KeyUsages);
}
private static void TestEnhancedKeyUsageExtension(
OidCollection usages,
bool critical,
byte[] expectedDer)
{
X509EnhancedKeyUsageExtension ext = new X509EnhancedKeyUsageExtension(usages, critical);
byte[] rawData = ext.RawData;
Assert.Equal(expectedDer, rawData);
ext = new X509EnhancedKeyUsageExtension(new AsnEncodedData(rawData), critical);
OidCollection actualUsages = ext.EnhancedKeyUsages;
Assert.Equal(usages.Count, actualUsages.Count);
for (int i = 0; i < usages.Count; i++)
{
Assert.Equal(usages[i].Value, actualUsages[i].Value);
}
}
private static void TestSubjectKeyIdentifierExtension(
byte[] certBytes,
X509SubjectKeyIdentifierHashAlgorithm algorithm,
bool critical,
byte[] expectedDer,
string expectedIdentifier)
{
PublicKey pk;
using (var cert = new X509Certificate2(certBytes))
{
pk = cert.PublicKey;
}
X509SubjectKeyIdentifierExtension ext =
new X509SubjectKeyIdentifierExtension(pk, algorithm, critical);
byte[] rawData = ext.RawData;
Assert.Equal(expectedDer, rawData);
ext = new X509SubjectKeyIdentifierExtension(new AsnEncodedData(rawData), critical);
Assert.Equal(expectedIdentifier, ext.SubjectKeyIdentifier);
}
}
}
| |
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>
/// Controller class for Guardia_Triage
/// </summary>
[System.ComponentModel.DataObject]
public partial class GuardiaTriageController
{
// Preload our schema..
GuardiaTriage thisSchemaLoad = new GuardiaTriage();
private string userName = String.Empty;
protected string UserName
{
get
{
if (userName.Length == 0)
{
if (System.Web.HttpContext.Current != null)
{
userName=System.Web.HttpContext.Current.User.Identity.Name;
}
else
{
userName=System.Threading.Thread.CurrentPrincipal.Identity.Name;
}
}
return userName;
}
}
[DataObjectMethod(DataObjectMethodType.Select, true)]
public GuardiaTriageCollection FetchAll()
{
GuardiaTriageCollection coll = new GuardiaTriageCollection();
Query qry = new Query(GuardiaTriage.Schema);
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public GuardiaTriageCollection FetchByID(object Id)
{
GuardiaTriageCollection coll = new GuardiaTriageCollection().Where("id", Id).Load();
return coll;
}
[DataObjectMethod(DataObjectMethodType.Select, false)]
public GuardiaTriageCollection FetchByQuery(Query qry)
{
GuardiaTriageCollection coll = new GuardiaTriageCollection();
coll.LoadAndCloseReader(qry.ExecuteReader());
return coll;
}
[DataObjectMethod(DataObjectMethodType.Delete, true)]
public bool Delete(object Id)
{
return (GuardiaTriage.Delete(Id) == 1);
}
[DataObjectMethod(DataObjectMethodType.Delete, false)]
public bool Destroy(object Id)
{
return (GuardiaTriage.Destroy(Id) == 1);
}
/// <summary>
/// Inserts a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Insert, true)]
public void Insert(int RegistroGuardia,int? IdEfector,DateTime FechaHora,string TensionArterial,int? FrecuenciaCardiaca,int? FrecuenciaRespiratoria,double? Temperatura,int? SaturacionOxigeno,int? GlasgowOcular,int? GlasgowVerbal,int? GlasgowMotor,double? Peso,string PupilasTamano,string PupilasReactividad,string PupilasSimetria,string Sensorio,string Sibilancia,string MuscAccesorio,string IngresoAlimentacionCant,string IngresoAlimentacionTipo,string IngresoSolucion,string IngresoOtros,string EgresoDepos,string EgresoOrina,string EgresoVomito,string EgresoSng,string EgresoOtros,string Observaciones,int? AuditUser,int? EscalaDelDolor,int? IdClasificacion,bool? Triage)
{
GuardiaTriage item = new GuardiaTriage();
item.RegistroGuardia = RegistroGuardia;
item.IdEfector = IdEfector;
item.FechaHora = FechaHora;
item.TensionArterial = TensionArterial;
item.FrecuenciaCardiaca = FrecuenciaCardiaca;
item.FrecuenciaRespiratoria = FrecuenciaRespiratoria;
item.Temperatura = Temperatura;
item.SaturacionOxigeno = SaturacionOxigeno;
item.GlasgowOcular = GlasgowOcular;
item.GlasgowVerbal = GlasgowVerbal;
item.GlasgowMotor = GlasgowMotor;
item.Peso = Peso;
item.PupilasTamano = PupilasTamano;
item.PupilasReactividad = PupilasReactividad;
item.PupilasSimetria = PupilasSimetria;
item.Sensorio = Sensorio;
item.Sibilancia = Sibilancia;
item.MuscAccesorio = MuscAccesorio;
item.IngresoAlimentacionCant = IngresoAlimentacionCant;
item.IngresoAlimentacionTipo = IngresoAlimentacionTipo;
item.IngresoSolucion = IngresoSolucion;
item.IngresoOtros = IngresoOtros;
item.EgresoDepos = EgresoDepos;
item.EgresoOrina = EgresoOrina;
item.EgresoVomito = EgresoVomito;
item.EgresoSng = EgresoSng;
item.EgresoOtros = EgresoOtros;
item.Observaciones = Observaciones;
item.AuditUser = AuditUser;
item.EscalaDelDolor = EscalaDelDolor;
item.IdClasificacion = IdClasificacion;
item.Triage = Triage;
item.Save(UserName);
}
/// <summary>
/// Updates a record, can be used with the Object Data Source
/// </summary>
[DataObjectMethod(DataObjectMethodType.Update, true)]
public void Update(int Id,int RegistroGuardia,int? IdEfector,DateTime FechaHora,string TensionArterial,int? FrecuenciaCardiaca,int? FrecuenciaRespiratoria,double? Temperatura,int? SaturacionOxigeno,int? GlasgowOcular,int? GlasgowVerbal,int? GlasgowMotor,double? Peso,string PupilasTamano,string PupilasReactividad,string PupilasSimetria,string Sensorio,string Sibilancia,string MuscAccesorio,string IngresoAlimentacionCant,string IngresoAlimentacionTipo,string IngresoSolucion,string IngresoOtros,string EgresoDepos,string EgresoOrina,string EgresoVomito,string EgresoSng,string EgresoOtros,string Observaciones,int? AuditUser,int? EscalaDelDolor,int? IdClasificacion,bool? Triage)
{
GuardiaTriage item = new GuardiaTriage();
item.MarkOld();
item.IsLoaded = true;
item.Id = Id;
item.RegistroGuardia = RegistroGuardia;
item.IdEfector = IdEfector;
item.FechaHora = FechaHora;
item.TensionArterial = TensionArterial;
item.FrecuenciaCardiaca = FrecuenciaCardiaca;
item.FrecuenciaRespiratoria = FrecuenciaRespiratoria;
item.Temperatura = Temperatura;
item.SaturacionOxigeno = SaturacionOxigeno;
item.GlasgowOcular = GlasgowOcular;
item.GlasgowVerbal = GlasgowVerbal;
item.GlasgowMotor = GlasgowMotor;
item.Peso = Peso;
item.PupilasTamano = PupilasTamano;
item.PupilasReactividad = PupilasReactividad;
item.PupilasSimetria = PupilasSimetria;
item.Sensorio = Sensorio;
item.Sibilancia = Sibilancia;
item.MuscAccesorio = MuscAccesorio;
item.IngresoAlimentacionCant = IngresoAlimentacionCant;
item.IngresoAlimentacionTipo = IngresoAlimentacionTipo;
item.IngresoSolucion = IngresoSolucion;
item.IngresoOtros = IngresoOtros;
item.EgresoDepos = EgresoDepos;
item.EgresoOrina = EgresoOrina;
item.EgresoVomito = EgresoVomito;
item.EgresoSng = EgresoSng;
item.EgresoOtros = EgresoOtros;
item.Observaciones = Observaciones;
item.AuditUser = AuditUser;
item.EscalaDelDolor = EscalaDelDolor;
item.IdClasificacion = IdClasificacion;
item.Triage = Triage;
item.Save(UserName);
}
}
}
| |
// Public domain by Christopher Diggins
// See: http://research.microsoft.com/Users/luca/Papers/BasicTypechecking.pdf
using System;
using System.Collections.Generic;
using System.Text;
using System.Diagnostics;
namespace Cat
{
public class ConstraintSolver
{
public class TypeException : Exception
{
public TypeException(string s)
: base(s)
{ }
public TypeException(Constraint c1, Constraint c2)
: this("constraint " + c1 + " is not compatible with " + c2)
{ }
}
#region fields
List<ConstraintList> mConstraintList; // left null, because it is created upon request
Dictionary<string, ConstraintList> mLookup = new Dictionary<string, ConstraintList>();
List<Pair<Vector>> mConstraintQueue = new List<Pair<Vector>>();
List<Relation> mGenericRenamingQueue = new List<Relation>();
Dictionary<string, Var> mVarPool = new Dictionary<string, Var>();
int mnId = 0;
List<Pair<Constant>> mDeductions = new List<Pair<Constant>>();
Dictionary<Relation, List<Relation>> mConstrainedRelations
= new Dictionary<Relation, List<Relation>>();
#endregion
#region deduction functions
public void AddDeduction(Constant c, Constant d)
{
Log("deduction " + c.ToString() + " = " + d.ToString());
mDeductions.Add(new Pair<Constant>(c, d));
}
public List<Pair<Constant>> GetDeductions()
{
return mDeductions;
}
#endregion
#region utility functions
public static T Last<T>(List<T> a)
{
return a[a.Count - 1];
}
public static Pair<Vector> VecPair(Vector v1, Vector v2)
{
return new Pair<Vector>(v1, v2);
}
public static void Err(string s)
{
throw new Exception(s);
}
public static void Check(bool b, string s)
{
if (!b)
Err(s);
}
public static void Log(string s)
{
if (Config.gbVerboseInference)
Output.WriteLine(s);
}
public bool IsRecursiveRelation(string s, Constraint c)
{
Relation rel = c as Relation;
if (rel == null)
return false;
foreach (Constraint tmp in rel.GetLeft())
if (tmp.EqualsVar(s))
return true;
foreach (Constraint tmp in rel.GetRight())
if (tmp.EqualsVar(s))
return true;
return false;
}
#endregion
#region constraint functions
/// <summary>
/// Currently only used to prevent recursive relations
/// from entering an infinite loop
/// </summary>
public bool IsRelationConstrained(Relation left, Relation right)
{
if (mConstrainedRelations.ContainsKey(left))
{
if (mConstrainedRelations[left].Contains(right))
return true;
}
return false;
}
/// <summary>
/// Currently only used to prevent recursive relations
/// from entering an infinite loop
/// </summary>
public void MarkRelationConstrained(Relation left, Relation right)
{
if (!mConstrainedRelations.ContainsKey(left))
mConstrainedRelations.Add(left, new List<Relation>());
if (!mConstrainedRelations[left].Contains(right))
mConstrainedRelations[left].Add(right);
if (!mConstrainedRelations.ContainsKey(right))
mConstrainedRelations.Add(right, new List<Relation>());
if (!mConstrainedRelations[right].Contains(left))
mConstrainedRelations[right].Add(left);
}
public void AddTopLevelConstraints(Vector vLeft, Vector vRight)
{
AddVecConstraint(vLeft, vRight);
}
public void AddToConstraintQueue(Vector v1, Vector v2)
{
// Don't add redundnant things to the constraint queue
foreach (Pair<Vector> pair in mConstraintQueue)
if ((pair.First == v1) && (pair.Second == v2))
return;
Log("adding to constraint queue: " + v1.ToString() + " = " + v2.ToString());
mConstraintQueue.Add(new Pair<Vector>(v1, v2));
}
public void AddSubConstraints(Constraint c1, Constraint c2)
{
if (c1 == c2) return;
if ((c1 is Vector) && (c2 is Vector))
{
AddToConstraintQueue(c1 as Vector, c2 as Vector);
}
else if ((c1 is Relation) && (c2 is Relation))
{
Relation r1 = c1 as Relation;
Relation r2 = c2 as Relation;
AddToConstraintQueue(r1.GetLeft(), r2.GetLeft());
AddToConstraintQueue(r1.GetRight(), r2.GetRight());
}
}
public void AddVarConstraint(Var v, Constraint c)
{
if (c is RecursiveRelation)
return;
AddConstraintToList(c, GetConstraints(v.ToString()));
}
public void AddRelConstraint(Relation r1, Relation r2)
{
if (IsRelationConstrained(r1, r2))
return;
MarkRelationConstrained(r1, r2);
AddVecConstraint(r1.GetLeft(), r2.GetLeft());
AddVecConstraint(r1.GetRight(), r2.GetRight());
}
public void AddVecConstraint(Vector v1, Vector v2)
{
if (v1 == v2)
return;
if (v1.IsEmpty() && v2.IsEmpty())
return;
if (v1.IsEmpty())
if (!(v2.GetFirst() is VectorVar))
Err("Only vector variables can be equal to empty vectors");
if (v2.IsEmpty())
if (!(v1.GetFirst() is VectorVar))
Err("Only vector variables can be equal to empty vectors");
Log("Constraining vector: " + v1.ToString() + " = " + v2.ToString());
if (v1.GetFirst() is VectorVar)
{
Check(v1.GetCount() == 1,
"Vector variables can only occur in the last position of a vector");
if ((v2.GetCount() > 0) && v2.GetFirst() is VectorVar)
{
ConstrainVars(v1.GetFirst() as Var, v2.GetFirst() as Var);
}
else
{
AddVarConstraint(v1.GetFirst() as VectorVar, v2);
}
}
else if (v2.GetFirst() is VectorVar)
{
AddVarConstraint(v2.GetFirst() as VectorVar, v1);
}
else
{
AddConstraint(v1.GetFirst(), v2.GetFirst());
// Recursive call
AddVecConstraint(v1.GetRest(), v2.GetRest());
ConstrainQueuedItems();
}
}
public void AddConstraintToList(Constraint c, ConstraintList a)
{
if (c is Var)
{
// Update the constraint list associated with this particular variable
// to now be "a".
string sVar = c.ToString();
Trace.Assert(mLookup.ContainsKey(sVar));
ConstraintList list = mLookup[sVar];
if (list == a)
Err("Internal error, expected constraint list to contain constraint " + c.ToString());
mLookup[sVar] = a;
}
if (a.Contains(c))
return;
foreach (Constraint k in a)
AddSubConstraints(k, c);
a.Add(c);
}
public void ConstrainVars(Var v1, Var v2)
{
Check(
((v1 is ScalarVar) && (v2 is ScalarVar)) ||
((v1 is VectorVar) && (v2 is VectorVar)),
"Incompatible variable kinds " + v1.ToString() + " and " + v2.ToString());
ConstrainVars(v1.ToString(), v2.ToString());
}
public void ConstrainVars(string s1, string s2)
{
if (s1.Equals(s2))
return;
ConstraintList a1 = GetConstraints(s1);
ConstraintList a2 = GetConstraints(s2);
if (a1 == a2)
return;
Trace.Assert(a1 != null);
Trace.Assert(a2 != null);
Log("Constraining var: " + s1 + " = " + s2);
foreach (Constraint c in a2)
AddConstraintToList(c, a1);
ConstrainQueuedItems();
}
public void ConstrainQueuedItems()
{
// While we have items left in the queue to merge, we merge them
while (mConstraintQueue.Count > 0)
{
Pair<Vector> p = mConstraintQueue[0];
mConstraintQueue.RemoveAt(0);
Log("Constraining queue item");
AddVecConstraint(p.First, p.Second);
}
}
public void CheckConstraintQueueEmpty()
{
Check(mConstraintQueue.Count == 0, "constraint queue is not empty");
}
ConstraintList GetConstraints(string s)
{
if (!mLookup.ContainsKey(s))
{
ConstraintList a = new ConstraintList();
a.Add(CreateVar(s));
mLookup.Add(s, a);
}
Trace.Assert(mLookup[s].ContainsVar(s));
return mLookup[s];
}
public void AddConstraint(Constraint c1, Constraint c2)
{
if (c1 == c2)
return;
if ((c1 is Var) && (c2 is Var))
ConstrainVars(c1 as Var, c2 as Var);
else if (c1 is Var)
AddVarConstraint(c1 as Var, c2);
else if (c2 is Var)
AddVarConstraint(c2 as Var, c1);
else if ((c1 is Vector) && (c2 is Vector))
AddVecConstraint(c1 as Vector, c2 as Vector);
else if ((c1 is Relation) && (c2 is Relation))
AddRelConstraint(c1 as Relation, c2 as Relation);
else if (c1 is Relation) {
// BUG: RecursiveRelations are not automatically compatible with other relations.
if (!(c2.ToString().Equals("self")) && (!c2.ToString().Equals("any")))
throw new TypeException(c1, c2);
}
else if (c2 is Relation)
{
// BUG: RecursiveRelations are not automatically compatible with other relations.
if (!(c1.ToString().Equals("self")) &&(!c1.ToString().Equals("any")))
throw new TypeException(c1, c2);
}
else if (c1 is Constant && c2 is Constant) {
if (!c1.ToString().Equals(c2.ToString())
&& !c1.ToString().Equals("any")
&& !c2.ToString().Equals("any"))
throw new TypeException(c1, c2);
}
else if (c1 is RecursiveRelation || c2 is RecursiveRelation)
{
if (c1 is RecursiveRelation)
if (!c2.ToString().Equals("any"))
throw new TypeException(c1, c2);
}
else
{
throw new TypeException("unhandled constraint scenario");
}
}
/// <summary>
/// Constructs the list of unique constraint lists
/// </summary>
public void ComputeConstraintLists()
{
mConstraintList = new List<ConstraintList>();
foreach (ConstraintList list in mLookup.Values)
if (!mConstraintList.Contains(list))
mConstraintList.Add(list);
}
public List<ConstraintList> GetConstraintLists()
{
if (mConstraintList == null)
throw new Exception("constraint lists haven't been computed");
return mConstraintList;
}
public IEnumerable<string> GetConstrainedVars()
{
return mLookup.Keys;
}
public void LogConstraints()
{
foreach (ConstraintList list in GetConstraintLists())
Log(list.ToString());
}
public bool IsConstrained(string s)
{
return mLookup.ContainsKey(s);
}
#endregion
#region vars and unifiers
public IEnumerable<string> GetAllVars()
{
return mVarPool.Keys;
}
public string GetUniqueVarName(string s)
{
int n = s.IndexOf("$");
if (n > 0)
s = s.Substring(0, n);
return s + "$" + mnId++.ToString();
}
public Var CreateUniqueVar(string s)
{
return CreateVar(GetUniqueVarName(s));
}
public Var CreateVar(string s)
{
Trace.Assert(s.Length > 0);
if (!mVarPool.ContainsKey(s))
{
Var v = char.IsUpper(s[0])
? new VectorVar(s) as Var
: new ScalarVar(s) as Var;
mVarPool.Add(s, v);
return v;
}
else
{
return mVarPool[s];
}
}
public void ComputeUnifiers()
{
foreach (ConstraintList list in GetConstraintLists())
{
Trace.Assert(list.Count > 0);
list.ComputeUnifier();
}
}
private void QueueForRenamingOfGenerics(Relation rel)
{
mGenericRenamingQueue.Add(rel);
}
public void RenameRelationsInQueue()
{
Log("Renaming generic variables of relations in queue");
while (mGenericRenamingQueue.Count > 0)
{
RenameGenericVars(mGenericRenamingQueue[0]);
mGenericRenamingQueue.RemoveAt(0);
}
}
public void RenameGenericVars(Relation rel)
{
Dictionary<string, string> newNames = new Dictionary<string, string>();
VarNameList generics = rel.GetGenericVars();
Log("Generics of " + rel.ToString() + " are " + generics.ToString());
// TODO: temp
if (rel.GetParent() == null)
Log(rel.ToString() + " has no parent"); else
Log("Parent of " + rel.ToString() + " is " + rel.GetParent().ToString());
foreach (string s in generics)
newNames.Add(s, GetUniqueVarName(s));
RenameVars(rel, newNames);
}
public Constraint GetUnifierFor(Var v)
{
Constraint ret = GetUnifierFor(v.ToString());
if (ret == null) return v;
return ret;
}
public Constraint GetUnifierFor(string s)
{
if (!IsConstrained(s))
return null;
return mLookup[s].GetUnifier().Clone();
}
public Constraint GetResolvedUnifierFor(string s)
{
Constraint ret = GetUnifierFor(s);
Check(ret != null, "internal error, no unifier found for " + s);
ret = Resolve(ret, new Stack<Constraint>(), null);
Log("Resolved unifier for " + s + " is " + ret.ToString());
RenameRelationsInQueue();
Log("After unique variable naming " + ret.ToString());
return ret;
}
public void RenameVars(Relation rel, Dictionary<string, string> vars)
{
foreach (Var v in rel.GetAllVars())
if (vars.ContainsKey(v.ToString()))
v.Rename(vars[v.ToString()]);
}
public IEnumerable<Constraint> GetUnifiers()
{
foreach (ConstraintList list in GetConstraintLists())
yield return list.GetUnifier();
}
public IEnumerable<Relation> GetRelationUnifiers()
{
foreach (Constraint c in GetUnifiers())
if (c is Relation)
yield return c as Relation;
}
#endregion
#region resolve functions
public Constraint ResolveRelationConstraint(Constraint c, Stack<Constraint> visited,
Relation parent, VarNameList topVars, VarNameList allVars)
{
VarNameList nonGenerics = parent.GetNonGenericsForChildren();
if (c is Var)
{
Var v = c as Var;
Constraint u = Resolve(v, visited, parent);
if (u is Relation)
{
Relation r = u as Relation;
// Make sure we don't add variables to the non-generics
// list which occured in a duplicate.
if (!topVars.Contains(v))
{
VarNameList subVars = r.GetAllVarNames();
foreach (string s in subVars)
if (allVars.Contains(s))
nonGenerics.Add(s);
allVars.AddRange(subVars);
}
else
{
Log("duplicate of variable " + v.ToString() + ", with unifier " + r.ToString());
QueueForRenamingOfGenerics(r);
}
}
else if (u is Var)
{
nonGenerics.Add(u as Var);
}
topVars.Add(v);
return u;
}
else
{
Constraint u = Resolve(c, visited, parent);
// non-vars should not resolve to vars
Trace.Assert(!(u is Var));
if (u is Relation)
{
Relation r = u as Relation;
VarNameList subVars = r.GetAllVarNames();
foreach (string s in subVars)
if (allVars.Contains(s))
nonGenerics.Add(s);
allVars.AddRange(subVars);
}
return u;
}
}
public Relation ResolveRelation(Relation r, Stack<Constraint> visited, Relation parent)
{
/// NOTES: It may become neccessary to resolve in stages, first resolve variables, then
/// resolve relations. This would make it easier to catch variables which are just
/// aliases for each other. I am not sure at this point, whether such a condition
/// could arise. I may alternatively choose to simply rename all generics, but that
/// would have a significant computational cost.
r.SetParent(parent);
r.GetNonGenericsForChildren().AddRange(r.GetAllVarNames());
Vector vLeft = new Vector();
Vector vRight = new Vector();
VarNameList allVars = new VarNameList();
VarNameList topVars = new VarNameList();
foreach (Constraint c in r.GetLeft())
vLeft.Add(ResolveRelationConstraint(c, visited, r, topVars, allVars));
foreach (Constraint c in r.GetRight())
vRight.Add(ResolveRelationConstraint(c, visited, r, topVars, allVars));
Relation ret = new Relation(vLeft, vRight);
// Make sure we set the parent for the newly created relation as well
ret.SetParent(parent);
Log("Resolved relation " + r.ToString());
Log("to " + ret.ToString());
Log("non-generics = " + r.GetNonGenericsForChildren());
return ret;
}
public Vector ResolveVector(Vector vec, Stack<Constraint> visited, Relation parent)
{
Vector ret = new Vector();
foreach (Constraint c in vec)
ret.Add(Resolve(c, visited, parent));
return ret;
}
public Constraint ResolveVar(Var v, Stack<Constraint> visited, Relation parent)
{
Constraint ret = GetUnifierFor(v);
if (ret == null)
{
ret = v;
}
else if (ret == v)
{
// do nothing
}
else if (ret is Var)
{
Trace.Assert((ret as Var) == ret);
}
else if (ret is Vector)
{
ret = Resolve(ret, visited, parent);
}
else if (ret is Relation)
{
ret = Resolve(ret, visited, parent);
}
else if (ret is Constant)
{
// do nothing
}
else if (ret is RecursiveRelation)
{
// do nothing
}
else
{
Err("Unhandled constraint " + ret.ToString());
}
//Log("Resolved var");
//Log(c.ToString() + " to " + ret.ToString());
return ret;
}
public Constraint GetRecursiveVar(Constraint c, Stack<Constraint> visited)
{
if (!(c is Var))
return null;
Var v = c as Var;
Constraint[] a = visited.ToArray();
Relation prevRelation = null;
for (int i = 0; i < a.Length; ++i)
{
Constraint tmp = a[i];
if (tmp is Var)
{
Var v2 = tmp as Var;
if (v2.ToString().Equals(v.ToString()))
{
if (prevRelation == null)
{
// Recursive variable
Trace.Assert(c is VectorVar);
return c;
}
return new RecursiveRelation();
}
}
else if (tmp is Relation)
{
prevRelation = tmp as Relation;
}
}
return null;
}
/// <summary>
/// This takes a unifier and replaces all variables with their unifiers.
/// </summary>
public Constraint Resolve(Constraint c, Stack<Constraint> visited, Relation parent)
{
Constraint rec = GetRecursiveVar(c, visited);
if (rec != null)
return rec;
visited.Push(c);
Constraint ret;
if (c is Var)
{
ret = ResolveVar(c as Var, visited, parent);
}
else if (c is Vector)
{
ret = ResolveVector(c as Vector, visited, parent);
}
else if (c is Relation)
{
ret = ResolveRelation(c as Relation, visited, parent);
}
else
{
ret = c;
}
visited.Pop();
Trace.Assert(ret != null);
return ret;
}
#endregion
}
}
| |
/*
* 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 log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
namespace OpenSim.Groups
{
public class HGGroupsServiceRobustConnector : ServiceConnector
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private HGGroupsService m_GroupsService;
private string m_ConfigName = "Groups";
// Called by Robust shell
public HGGroupsServiceRobustConnector(IConfigSource config, IHttpServer server, string configName) :
this(config, server, configName, null, null)
{
}
// Called by the sim-bound module
public HGGroupsServiceRobustConnector(IConfigSource config, IHttpServer server, string configName, IOfflineIMService im, IUserAccountService users) :
base(config, server, configName)
{
if (configName != String.Empty)
m_ConfigName = configName;
m_log.DebugFormat("[Groups.RobustHGConnector]: Starting with config name {0}", m_ConfigName);
string homeURI = Util.GetConfigVarFromSections<string>(config, "HomeURI",
new string[] { "Startup", "Hypergrid", m_ConfigName}, string.Empty);
if (homeURI == string.Empty)
throw new Exception(String.Format("[Groups.RobustHGConnector]: please provide the HomeURI [Startup] or in section {0}", m_ConfigName));
IConfig cnf = config.Configs[m_ConfigName];
if (cnf == null)
throw new Exception(String.Format("[Groups.RobustHGConnector]: {0} section does not exist", m_ConfigName));
if (im == null)
{
string imDll = cnf.GetString("OfflineIMService", string.Empty);
if (imDll == string.Empty)
throw new Exception(String.Format("[Groups.RobustHGConnector]: please provide OfflineIMService in section {0}", m_ConfigName));
Object[] args = new Object[] { config };
im = ServerUtils.LoadPlugin<IOfflineIMService>(imDll, args);
}
if (users == null)
{
string usersDll = cnf.GetString("UserAccountService", string.Empty);
if (usersDll == string.Empty)
throw new Exception(String.Format("[Groups.RobustHGConnector]: please provide UserAccountService in section {0}", m_ConfigName));
Object[] args = new Object[] { config };
users = ServerUtils.LoadPlugin<IUserAccountService>(usersDll, args);
}
m_GroupsService = new HGGroupsService(config, im, users, homeURI);
server.AddStreamHandler(new HGGroupsServicePostHandler(m_GroupsService));
}
}
public class HGGroupsServicePostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private HGGroupsService m_GroupsService;
public HGGroupsServicePostHandler(HGGroupsService service) :
base("POST", "/hg-groups")
{
m_GroupsService = 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();
request.Remove("METHOD");
m_log.DebugFormat("[Groups.RobustHGConnector]: {0}", method);
switch (method)
{
case "POSTGROUP":
return HandleAddGroupProxy(request);
case "REMOVEAGENTFROMGROUP":
return HandleRemoveAgentFromGroup(request);
case "GETGROUP":
return HandleGetGroup(request);
case "ADDNOTICE":
return HandleAddNotice(request);
case "VERIFYNOTICE":
return HandleVerifyNotice(request);
case "GETGROUPMEMBERS":
return HandleGetGroupMembers(request);
case "GETGROUPROLES":
return HandleGetGroupRoles(request);
case "GETROLEMEMBERS":
return HandleGetRoleMembers(request);
}
m_log.DebugFormat("[Groups.RobustHGConnector]: unknown method request: {0}", method);
}
catch (Exception e)
{
m_log.Error(string.Format("[Groups.RobustHGConnector]: Exception {0} ", e.Message), e);
}
return FailureResult();
}
byte[] HandleAddGroupProxy(Dictionary<string, object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID")
|| !request.ContainsKey("AgentID")
|| !request.ContainsKey("AccessToken") || !request.ContainsKey("Location"))
NullResult(result, "Bad network data");
else
{
string RequestingAgentID = request["RequestingAgentID"].ToString();
string agentID = request["AgentID"].ToString();
UUID groupID = new UUID(request["GroupID"].ToString());
string accessToken = request["AccessToken"].ToString();
string location = request["Location"].ToString();
string name = string.Empty;
if (request.ContainsKey("Name"))
name = request["Name"].ToString();
string reason = string.Empty;
bool success = m_GroupsService.CreateGroupProxy(RequestingAgentID, agentID, accessToken, groupID, location, name, out reason);
result["REASON"] = reason;
result["RESULT"] = success.ToString();
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleRemoveAgentFromGroup(Dictionary<string, object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (!request.ContainsKey("AccessToken") || !request.ContainsKey("AgentID") ||
!request.ContainsKey("GroupID"))
NullResult(result, "Bad network data");
else
{
UUID groupID = new UUID(request["GroupID"].ToString());
string agentID = request["AgentID"].ToString();
string token = request["AccessToken"].ToString();
if (!m_GroupsService.RemoveAgentFromGroup(agentID, agentID, groupID, token))
NullResult(result, "Internal error");
else
result["RESULT"] = "true";
}
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(ServerUtils.BuildXmlResponse(result));
}
byte[] HandleGetGroup(Dictionary<string, object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("AccessToken"))
NullResult(result, "Bad network data");
else
{
string RequestingAgentID = request["RequestingAgentID"].ToString();
string token = request["AccessToken"].ToString();
UUID groupID = UUID.Zero;
string groupName = string.Empty;
if (request.ContainsKey("GroupID"))
groupID = new UUID(request["GroupID"].ToString());
if (request.ContainsKey("Name"))
groupName = request["Name"].ToString();
ExtendedGroupRecord grec = m_GroupsService.GetGroupRecord(RequestingAgentID, groupID, groupName, token);
if (grec == null)
NullResult(result, "Group not found");
else
result["RESULT"] = GroupsDataUtils.GroupRecord(grec);
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetGroupMembers(Dictionary<string, object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AccessToken"))
NullResult(result, "Bad network data");
else
{
UUID groupID = new UUID(request["GroupID"].ToString());
string requestingAgentID = request["RequestingAgentID"].ToString();
string token = request["AccessToken"].ToString();
List<ExtendedGroupMembersData> members = m_GroupsService.GetGroupMembers(requestingAgentID, groupID, token);
if (members == null || (members != null && members.Count == 0))
{
NullResult(result, "No members");
}
else
{
Dictionary<string, object> dict = new Dictionary<string, object>();
int i = 0;
foreach (ExtendedGroupMembersData m in members)
{
dict["m-" + i++] = GroupsDataUtils.GroupMembersData(m);
}
result["RESULT"] = dict;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetGroupRoles(Dictionary<string, object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AccessToken"))
NullResult(result, "Bad network data");
else
{
UUID groupID = new UUID(request["GroupID"].ToString());
string requestingAgentID = request["RequestingAgentID"].ToString();
string token = request["AccessToken"].ToString();
List<GroupRolesData> roles = m_GroupsService.GetGroupRoles(requestingAgentID, groupID, token);
if (roles == null || (roles != null && roles.Count == 0))
{
NullResult(result, "No members");
}
else
{
Dictionary<string, object> dict = new Dictionary<string, object>();
int i = 0;
foreach (GroupRolesData r in roles)
dict["r-" + i++] = GroupsDataUtils.GroupRolesData(r);
result["RESULT"] = dict;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleGetRoleMembers(Dictionary<string, object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("AccessToken"))
NullResult(result, "Bad network data");
else
{
UUID groupID = new UUID(request["GroupID"].ToString());
string requestingAgentID = request["RequestingAgentID"].ToString();
string token = request["AccessToken"].ToString();
List<ExtendedGroupRoleMembersData> rmembers = m_GroupsService.GetGroupRoleMembers(requestingAgentID, groupID, token);
if (rmembers == null || (rmembers != null && rmembers.Count == 0))
{
NullResult(result, "No members");
}
else
{
Dictionary<string, object> dict = new Dictionary<string, object>();
int i = 0;
foreach (ExtendedGroupRoleMembersData rm in rmembers)
dict["rm-" + i++] = GroupsDataUtils.GroupRoleMembersData(rm);
result["RESULT"] = dict;
}
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleAddNotice(Dictionary<string, object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (!request.ContainsKey("RequestingAgentID") || !request.ContainsKey("GroupID") || !request.ContainsKey("NoticeID") ||
!request.ContainsKey("FromName") || !request.ContainsKey("Subject") || !request.ContainsKey("Message") ||
!request.ContainsKey("HasAttachment"))
NullResult(result, "Bad network data");
else
{
bool hasAtt = bool.Parse(request["HasAttachment"].ToString());
byte attType = 0;
string attName = string.Empty;
string attOwner = string.Empty;
UUID attItem = UUID.Zero;
if (request.ContainsKey("AttachmentType"))
attType = byte.Parse(request["AttachmentType"].ToString());
if (request.ContainsKey("AttachmentName"))
attName = request["AttachmentType"].ToString();
if (request.ContainsKey("AttachmentItemID"))
attItem = new UUID(request["AttachmentItemID"].ToString());
if (request.ContainsKey("AttachmentOwnerID"))
attOwner = request["AttachmentOwnerID"].ToString();
bool success = m_GroupsService.AddNotice(request["RequestingAgentID"].ToString(), new UUID(request["GroupID"].ToString()),
new UUID(request["NoticeID"].ToString()), request["FromName"].ToString(), request["Subject"].ToString(),
request["Message"].ToString(), hasAtt, attType, attName, attItem, attOwner);
result["RESULT"] = success.ToString();
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
byte[] HandleVerifyNotice(Dictionary<string, object> request)
{
Dictionary<string, object> result = new Dictionary<string, object>();
if (!request.ContainsKey("NoticeID") || !request.ContainsKey("GroupID"))
NullResult(result, "Bad network data");
else
{
UUID noticeID = new UUID(request["NoticeID"].ToString());
UUID groupID = new UUID(request["GroupID"].ToString());
bool success = m_GroupsService.VerifyNotice(noticeID, groupID);
//m_log.DebugFormat("[XXX]: VerifyNotice returned {0}", success);
result["RESULT"] = success.ToString();
}
string xmlString = ServerUtils.BuildXmlResponse(result);
//m_log.DebugFormat("[XXX]: resp string: {0}", xmlString);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
//
//
//
//
//
#region Helpers
private void NullResult(Dictionary<string, object> result, string reason)
{
result["RESULT"] = "NULL";
result["REASON"] = reason;
}
private byte[] FailureResult()
{
Dictionary<string, object> result = new Dictionary<string, object>();
NullResult(result, "Unknown method");
string xmlString = ServerUtils.BuildXmlResponse(result);
return Util.UTF8NoBomEncoding.GetBytes(xmlString);
}
#endregion
}
}
| |
using RootSystem = System;
using System.Linq;
using System.Collections.Generic;
namespace Windows.Kinect
{
//
// Windows.Kinect.BodyIndexFrameReader
//
public sealed partial class BodyIndexFrameReader : RootSystem.IDisposable, Helper.INativeWrapper
{
internal RootSystem.IntPtr _pNative;
RootSystem.IntPtr Helper.INativeWrapper.nativePtr { get { return _pNative; } }
// Constructors and Finalizers
internal BodyIndexFrameReader(RootSystem.IntPtr pNative)
{
_pNative = pNative;
Windows_Kinect_BodyIndexFrameReader_AddRefObject(ref _pNative);
}
~BodyIndexFrameReader()
{
Dispose(false);
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_BodyIndexFrameReader_ReleaseObject(ref RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_BodyIndexFrameReader_AddRefObject(ref RootSystem.IntPtr pNative);
private void Dispose(bool disposing)
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Helper.NativeObjectCache.RemoveObject<BodyIndexFrameReader>(_pNative);
if (disposing)
{
Windows_Kinect_BodyIndexFrameReader_Dispose(_pNative);
}
Windows_Kinect_BodyIndexFrameReader_ReleaseObject(ref _pNative);
_pNative = RootSystem.IntPtr.Zero;
}
// Public Properties
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Windows_Kinect_BodyIndexFrameReader_get_BodyIndexFrameSource(RootSystem.IntPtr pNative);
public Windows.Kinect.BodyIndexFrameSource BodyIndexFrameSource
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("BodyIndexFrameReader");
}
RootSystem.IntPtr objectPointer = Windows_Kinect_BodyIndexFrameReader_get_BodyIndexFrameSource(_pNative);
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.BodyIndexFrameSource>(objectPointer, n => new Windows.Kinect.BodyIndexFrameSource(n));
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern bool Windows_Kinect_BodyIndexFrameReader_get_IsPaused(RootSystem.IntPtr pNative);
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_BodyIndexFrameReader_put_IsPaused(RootSystem.IntPtr pNative, bool isPaused);
public bool IsPaused
{
get
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("BodyIndexFrameReader");
}
return Windows_Kinect_BodyIndexFrameReader_get_IsPaused(_pNative);
}
set
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("BodyIndexFrameReader");
}
Windows_Kinect_BodyIndexFrameReader_put_IsPaused(_pNative, value);
}
}
// Events
private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.BodyIndexFrameArrivedEventArgs>>> Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Kinect.BodyIndexFrameArrivedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate))]
private static void Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Windows.Kinect.BodyIndexFrameArrivedEventArgs>> callbackList = null;
Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<BodyIndexFrameReader>(pNative);
var args = new Windows.Kinect.BodyIndexFrameArrivedEventArgs(result);
foreach(var func in callbackList)
{
#if UNITY_METRO || UNITY_XBOXONE
UnityEngine.WSA.Application.InvokeOnAppThread(() => { try { func(objThis, args); } catch { } }, true);
#else
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
#endif
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_BodyIndexFrameReader_add_FrameArrived(RootSystem.IntPtr pNative, _Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Windows.Kinect.BodyIndexFrameArrivedEventArgs> FrameArrived
{
add
{
#if !UNITY_METRO && !UNITY_XBOXONE
Helper.EventPump.EnsureInitialized();
#endif
Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate(Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_Handler);
_Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Windows_Kinect_BodyIndexFrameReader_add_FrameArrived(_pNative, del, false);
}
}
}
remove
{
Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Windows_Kinect_BodyIndexFrameReader_add_FrameArrived(_pNative, Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_Handler, true);
_Windows_Kinect_BodyIndexFrameArrivedEventArgs_Delegate_Handle.Free();
}
}
}
}
private static RootSystem.Runtime.InteropServices.GCHandle _Windows_Data_PropertyChangedEventArgs_Delegate_Handle;
[RootSystem.Runtime.InteropServices.UnmanagedFunctionPointer(RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private delegate void _Windows_Data_PropertyChangedEventArgs_Delegate(RootSystem.IntPtr args, RootSystem.IntPtr pNative);
private static Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>> Windows_Data_PropertyChangedEventArgs_Delegate_callbacks = new Helper.CollectionMap<RootSystem.IntPtr, List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>>>();
[AOT.MonoPInvokeCallbackAttribute(typeof(_Windows_Data_PropertyChangedEventArgs_Delegate))]
private static void Windows_Data_PropertyChangedEventArgs_Delegate_Handler(RootSystem.IntPtr result, RootSystem.IntPtr pNative)
{
List<RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs>> callbackList = null;
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryGetValue(pNative, out callbackList);
lock(callbackList)
{
var objThis = Helper.NativeObjectCache.GetObject<BodyIndexFrameReader>(pNative);
var args = new Windows.Data.PropertyChangedEventArgs(result);
foreach(var func in callbackList)
{
#if UNITY_METRO || UNITY_XBOXONE
UnityEngine.WSA.Application.InvokeOnAppThread(() => { try { func(objThis, args); } catch { } }, true);
#else
Helper.EventPump.Instance.Enqueue(() => { try { func(objThis, args); } catch { } });
#endif
}
}
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_BodyIndexFrameReader_add_PropertyChanged(RootSystem.IntPtr pNative, _Windows_Data_PropertyChangedEventArgs_Delegate eventCallback, bool unsubscribe);
public event RootSystem.EventHandler<Windows.Data.PropertyChangedEventArgs> PropertyChanged
{
add
{
#if !UNITY_METRO && !UNITY_XBOXONE
Helper.EventPump.EnsureInitialized();
#endif
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Add(value);
if(callbackList.Count == 1)
{
var del = new _Windows_Data_PropertyChangedEventArgs_Delegate(Windows_Data_PropertyChangedEventArgs_Delegate_Handler);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle = RootSystem.Runtime.InteropServices.GCHandle.Alloc(del);
Windows_Kinect_BodyIndexFrameReader_add_PropertyChanged(_pNative, del, false);
}
}
}
remove
{
Windows_Data_PropertyChangedEventArgs_Delegate_callbacks.TryAddDefault(_pNative);
var callbackList = Windows_Data_PropertyChangedEventArgs_Delegate_callbacks[_pNative];
lock (callbackList)
{
callbackList.Remove(value);
if(callbackList.Count == 0)
{
Windows_Kinect_BodyIndexFrameReader_add_PropertyChanged(_pNative, Windows_Data_PropertyChangedEventArgs_Delegate_Handler, true);
_Windows_Data_PropertyChangedEventArgs_Delegate_Handle.Free();
}
}
}
}
// Public Methods
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern RootSystem.IntPtr Windows_Kinect_BodyIndexFrameReader_AcquireLatestFrame(RootSystem.IntPtr pNative);
public Windows.Kinect.BodyIndexFrame AcquireLatestFrame()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
throw new RootSystem.ObjectDisposedException("BodyIndexFrameReader");
}
RootSystem.IntPtr objectPointer = Windows_Kinect_BodyIndexFrameReader_AcquireLatestFrame(_pNative);
if (objectPointer == RootSystem.IntPtr.Zero)
{
return null;
}
return Helper.NativeObjectCache.CreateOrGetObject<Windows.Kinect.BodyIndexFrame>(objectPointer, n => new Windows.Kinect.BodyIndexFrame(n));
}
[RootSystem.Runtime.InteropServices.DllImport("XboxOneUnityAddin", CallingConvention=RootSystem.Runtime.InteropServices.CallingConvention.Cdecl)]
private static extern void Windows_Kinect_BodyIndexFrameReader_Dispose(RootSystem.IntPtr pNative);
public void Dispose()
{
if (_pNative == RootSystem.IntPtr.Zero)
{
return;
}
Dispose(true);
RootSystem.GC.SuppressFinalize(this);
}
}
}
| |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
// Note: Exception messages call ToString instead of Name to avoid MissingMetadataException when just outputting basic info
using System;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace TestLibrary
{
/// <summary>
/// A collection of helper classes to test various conditions within
/// unit tests. If the condition being tested is not met, an exception
/// is thrown.
/// </summary>
public static class Assert
{
/// <summary>
/// Asserts that the given delegate throws an <see cref="ArgumentNullException"/> with the given parameter name.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="parameterName">
/// A <see cref="String"/> containing the parameter of name to check, <see langword="null"/> to skip parameter validation.
/// </param>
/// <returns>
/// The thrown <see cref="ArgumentNullException"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <see cref="ArgumentNullException"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="ArgumentException.ParamName"/> is not equal to <paramref name="parameterName"/> .
/// </exception>
public static ArgumentNullException ThrowsArgumentNullException(string parameterName, Action action, string message = null)
{
return ThrowsArgumentException<ArgumentNullException>(parameterName, action, message);
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="ArgumentException"/> with the given parameter name.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="parameterName">
/// A <see cref="String"/> containing the parameter of name to check, <see langword="null"/> to skip parameter validation.
/// </param>
/// <returns>
/// The thrown <see cref="ArgumentException"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <see cref="ArgumentException"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="ArgumentException.ParamName"/> is not equal to <paramref name="parameterName"/> .
/// </exception>
public static ArgumentException ThrowsArgumentException(string parameterName, Action action, string message = null)
{
return ThrowsArgumentException<ArgumentException>(parameterName, action, message);
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="ArgumentException"/> of type <typeparamref name="T"/> with the given parameter name.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="parameterName">
/// A <see cref="String"/> containing the parameter of name to check, <see langword="null"/> to skip parameter validation.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="ArgumentException.ParamName"/> is not equal to <paramref name="parameterName"/> .
/// </exception>
public static T ThrowsArgumentException<T>(string parameterName, Action action, string message = null)
where T : ArgumentException
{
T exception = Throws<T>(action, message);
#if DEBUG
// ParamName's not available on ret builds
if (parameterName != null)
Assert.AreEqual(parameterName, exception.ParamName, "Expected '{0}.ParamName' to be '{1}'. {2}", typeof(T), parameterName, message);
#endif
return exception;
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="AggregateException"/> with a base exception <see cref="Exception"/> of type <typeparam name="T" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <returns>
/// The base <see cref="Exception"/> of the <see cref="AggregateException"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="AggregateException"/> of was not thrown.
/// -or-
/// </para>
/// <see cref="AggregateException.GetBaseException()"/> is not of type <typeparam name="TBase"/>.
/// </exception>
public static TBase ThrowsAggregateException<TBase>(Action action, string message = "") where TBase : Exception
{
AggregateException exception = Throws<AggregateException>(action, message);
Exception baseException = exception.GetBaseException();
if (baseException == null)
Assert.Fail("Expected 'AggregateException.GetBaseException()' to be '{0}', however it is null. {1}", typeof(TBase), message);
if (baseException.GetType() != typeof(TBase))
Assert.Fail("Expected 'AggregateException.GetBaseException()', to be '{0}', however, '{1}' is. {2}", typeof(TBase), baseException.GetType(), message);
return (TBase)baseException;
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="Exception"/> of type <typeparam name="T" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="format">
/// A <see cref="String"/> containing format information for when the assertion fails.
/// </param>
/// <param name="args">
/// An <see cref="Array"/> of arguments to be formatted.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// </exception>
public static T Throws<T>(Action action, string format, params Object[] args) where T : Exception
{
return Throws<T>(action, String.Format(format, args));
}
/// <summary>
/// Asserts that the given delegate throws an <see cref="Exception"/> of type <typeparam name="T" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="options">
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception. The default is <see cref="AssertThrowsOptions.None"/>.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// </exception>
public static T Throws<T>(Action action, string message = "", AssertThrowsOptions options = AssertThrowsOptions.None) where T : Exception
{
Exception exception = RunWithCatch(action);
if (exception == null)
Assert.Fail("Expected '{0}' to be thrown. {1}", typeof(T).ToString(), message);
if (!IsOfExceptionType<T>(exception, options))
Assert.Fail("Expected '{0}' to be thrown, however '{1}' was thrown. {2}", typeof(T), exception.GetType(), message);
return (T)exception;
}
/// <summary>
/// Asserts that the given async delegate throws an <see cref="Exception"/> of type <typeparam name="T".
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Func{}"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="options">
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception. The default is <see cref="AssertThrowsOptions.None"/>.
/// </param>
/// <returns>
/// The thrown <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// </exception>
public static async Task<T> ThrowsAsync<T>(Func<Task> action, string message = "", AssertThrowsOptions options = AssertThrowsOptions.None) where T : Exception
{
Exception exception = await RunWithCatchAsync(action);
if (exception == null)
Assert.Fail("Expected '{0}' to be thrown. {1}", typeof(T).ToString(), message);
if (!IsOfExceptionType<T>(exception, options))
Assert.Fail("Expected '{0}' to be thrown, however '{1}' was thrown. {2}", typeof(T), exception.GetType(), message);
return (T)exception;
}
/// <summary>
/// Asserts that the given async delegate throws an <see cref="Exception"/> of type <typeparam name="T" /> and <see cref="Exception.InnerException"/>
/// returns an <see cref="Exception"/> of type <typeparam name="TInner" />.
/// </summary>
/// <param name="action">
/// The delagate of type <see cref="Action"/> to execute.
/// </param>
/// <param name="message">
/// A <see cref="String"/> containing additional information for when the assertion fails.
/// </param>
/// <param name="options">
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception. The default is <see cref="AssertThrowsOptions.None"/>.
/// </param>
/// <returns>
/// The thrown inner <see cref="Exception"/>.
/// </returns>
/// <exception cref="AssertFailedException">
/// <see cref="Exception"/> of type <typeparam name="T"/> was not thrown.
/// <para>
/// -or-
/// </para>
/// <see cref="Exception.InnerException"/> is not of type <typeparam name="TInner"/>.
/// </exception>
public static TInner Throws<T, TInner>(Action action, string message = "", AssertThrowsOptions options = AssertThrowsOptions.None)
where T : Exception
where TInner : Exception
{
T outerException = Throws<T>(action, message, options);
if (outerException.InnerException == null)
Assert.Fail("Expected '{0}.InnerException' to be '{1}', however it is null. {2}", typeof(T), typeof(TInner), message);
if (!IsOfExceptionType<TInner>(outerException.InnerException, options))
Assert.Fail("Expected '{0}.InnerException', to be '{1}', however, '{2}' is. {3}", typeof(T), typeof(TInner), outerException.InnerException.GetType(), message);
return (TInner)outerException.InnerException;
}
/// <summary>
/// Tests whether the specified condition is true and throws an exception
/// if the condition is false.
/// </summary>
/// <param name="condition">The condition the test expects to be true.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is false. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is false.
/// </exception>
public static void IsTrue(bool condition, string format, params Object[] args)
{
if (!condition)
{
Assert.HandleFail("Assert.IsTrue", String.Format(format, args));
}
}
/// <summary>
/// Tests whether the specified condition is true and throws an exception
/// if the condition is false.
/// </summary>
/// <param name="condition">The condition the test expects to be true.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is false. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is false.
/// </exception>
public static void IsTrue(bool condition, string message = "")
{
if (!condition)
{
Assert.HandleFail("Assert.IsTrue", message);
}
}
/// <summary>
/// Tests whether the specified condition is false and throws an exception
/// if the condition is true.
/// </summary>
/// <param name="condition">The condition the test expects to be false.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is true. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is true.
/// </exception>
public static void IsFalse(bool condition, string message = "")
{
if (condition)
{
Assert.HandleFail("Assert.IsFalse", message);
}
}
/// <summary>
/// Tests whether the specified condition is false and throws an exception
/// if the condition is true.
/// </summary>
/// <param name="condition">The condition the test expects to be false.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="condition"/>
/// is true. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="condition"/> is true.
/// </exception>
public static void IsFalse(bool condition, string format, params Object[] args)
{
IsFalse(condition, String.Format(format, args));
}
/// <summary>
/// Tests whether the specified object is null and throws an exception
/// if it is not.
/// </summary>
/// <param name="value">The object the test expects to be null.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="value"/>
/// is not null. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="value"/> is not null.
/// </exception>
public static void IsNull(object value, string message = "")
{
if (value != null)
{
Assert.HandleFail("Assert.IsNull", message);
}
}
/// <summary>
/// Tests whether the specified object is null and throws an exception
/// if it is not.
/// </summary>
/// <param name="value">The object the test expects to be null.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="value"/>
/// is not null. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="value"/> is not null.
/// </exception>
public static void IsNull(object value, string format, params Object[] args)
{
IsNull(value, String.Format(format, args));
}
/// <summary>
/// Tests whether the specified object is non-null and throws an exception
/// if it is null.
/// </summary>
/// <param name="value">The object the test expects not to be null.</param>
/// <param name="message">
/// The message to include in the exception when <paramref name="value"/>
/// is null. The message is shown in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="value"/> is null.
/// </exception>
public static void IsNotNull(object value, string message = "")
{
if (value == null)
{
Assert.HandleFail("Assert.IsNotNull", message);
}
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreEqual<T>(T expected, T actual, string message = "")
{
const string EXPECTED_MSG = @"Expected: [{1}]. Actual: [{2}]. {0}";
if (!Object.Equals(expected, actual))
{
string finalMessage = String.Format(EXPECTED_MSG, message, (object)expected ?? "NULL", (object)actual ?? "NULL");
Assert.HandleFail("Assert.AreEqual", finalMessage);
}
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreEqual<T>(T expected, T actual, string format, params Object[] args)
{
AreEqual<T>(expected, actual, String.Format(format, args));
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object that we do not want it to be.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreNotEqual<T>(T notExpected, T actual, string message = "")
{
if (Object.Equals(notExpected, actual))
{
String finalMessage =
String.Format(@"Expected any value except:[{1}]. Actual:[{2}]. {0}",
message, notExpected, actual);
Assert.HandleFail("Assert.AreNotEqual", finalMessage);
}
}
/// <summary>
/// Tests whether the expected object is equal to the actual object and
/// throws an exception if it is not.
/// </summary>
/// <param name="notExpected">Expected object that we do not want it to be.</param>
/// <param name="actual">Actual object.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreNotEqual<T>(T notExpected, T actual, string format, params Object[] args)
{
AreNotEqual<T>(notExpected, actual, String.Format(format, args));
}
/// <summary>
/// Tests whether the two lists are the same length and contain the same objects (using Object.Equals()) in the same order and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected list.</param>
/// <param name="actual">Actual list.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqual<T>(T[] expected, T[] actual, string message = "")
{
Assert.AreEqual(expected.Length, actual.Length, message);
for (int i = 0; i < expected.Length; i++)
Assert.AreEqual<T>(expected[i], actual[i], message);
}
/// <summary>
/// Tests whether the two lists are the same length and contain the same objects (using Object.Equals()) in the same order and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected list.</param>
/// <param name="actual">Actual list.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqual<T>(T[] expected, T[] actual, string format, params Object[] args)
{
AreAllEqual<T>(expected, actual, String.Format(format, args));
}
/// <summary>
/// Tests whether the two lists are the same length and contain the same objects (using Object.Equals()) (but not necessarily in the same order) and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected list.</param>
/// <param name="actual">Actual list.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqualUnordered<T>(T[] expected, T[] actual)
{
Assert.AreEqual(expected.Length, actual.Length);
int count = expected.Length;
bool[] removedFromActual = new bool[count];
for (int i = 0; i < count; i++)
{
T item1 = expected[i];
bool foundMatch = false;
for (int j = 0; j < count; j++)
{
if (!removedFromActual[j])
{
T item2 = actual[j];
if ((item1 == null && item2 == null) || (item1 != null && item1.Equals(item2)))
{
foundMatch = true;
removedFromActual[j] = true;
break;
}
}
}
if (!foundMatch)
Assert.HandleFail("Assert.AreAllEqualUnordered", "First array has element not found in second array: " + item1);
}
return;
}
/// <summary>
/// Tests whether the two enumerables are the same length and contain the same objects (using Object.Equals()) in the same order and
/// throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected enumerables.</param>
/// <param name="actual">Actual enumerables.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqual<T>(IEnumerable<T> expected, IEnumerable<T> actual, string message = "")
{
AreAllEqual(CopyToArray(expected), CopyToArray(actual), message);
}
/// <summary>
/// Tests whether the two enumerables are the same length and contain the same objects (using Object.Equals()) (but not necessarily
/// in the same order) and throws an exception if it is not.
/// </summary>
/// <param name="expected">Expected enumerable.</param>
/// <param name="actual">Actual enumerable.</param>
/// <param name="message">Message to display upon failure.</param>
public static void AreAllEqualUnordered<T>(IEnumerable<T> expected, IEnumerable<T> actual, string message = "")
{
AreAllEqualUnordered(CopyToArray(expected), CopyToArray(actual), message);
}
/// <summary>
/// Iterates through an IEnumerable to generate an array of elements. The rational for using this instead of
/// System.Linq.ToArray is that this will not require a dependency on System.Linq.dll
/// </summary>
private static T[] CopyToArray<T>(IEnumerable<T> source)
{
T[] items = new T[4];
int count = 0;
if (source == null)
return null;
foreach (var item in source)
{
if (items.Length == count)
{
var newItems = new T[checked(count * 2)];
Array.Copy(items, 0, newItems, 0, count);
items = newItems;
}
items[count] = item;
count++;
}
if (items.Length == count)
return items;
var finalItems = new T[count];
Array.Copy(items, 0, finalItems, 0, count);
return finalItems;
}
/// <summary>
/// Tests whether the specified objects both refer to the same object and
/// throws an exception if the two inputs do not refer to the same object.
/// </summary>
/// <param name="expected">
/// The first object to compare. This is the value the test expects.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="expected"/> does not refer to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreSame(object expected, object actual)
{
Assert.AreSame(expected, actual, string.Empty);
}
/// <summary>
/// Tests whether the specified objects both refer to the same object and
/// throws an exception if the two inputs do not refer to the same object.
/// </summary>
/// <param name="expected">
/// The first object to compare. This is the value the test expects.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <param name="message">
/// The message to include in the exception when <paramref name="actual"/>
/// is not the same as <paramref name="expected"/>. The message is shown
/// in test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="expected"/> does not refer to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreSame(object expected, object actual, string message)
{
if (!Object.ReferenceEquals(expected, actual))
{
string finalMessage = message;
ValueType valExpected = expected as ValueType;
if (valExpected != null)
{
ValueType valActual = actual as ValueType;
if (valActual != null)
{
finalMessage = message == null ? String.Empty : message;
}
}
Assert.HandleFail("Assert.AreSame", finalMessage);
}
}
/// <summary>
/// Tests whether the specified objects refer to different objects and
/// throws an exception if the two inputs refer to the same object.
/// </summary>
/// <param name="notExpected">
/// The first object to compare. This is the value the test expects not
/// to match <paramref name="actual"/>.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="notExpected"/> refers to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreNotSame(object notExpected, object actual)
{
Assert.AreNotSame(notExpected, actual, string.Empty);
}
/// <summary>
/// Tests whether the specified objects refer to different objects and
/// throws an exception if the two inputs refer to the same object.
/// </summary>
/// <param name="notExpected">
/// The first object to compare. This is the value the test expects not
/// to match <paramref name="actual"/>.
/// </param>
/// <param name="actual">
/// The second object to compare. This is the value produced by the code under test.
/// </param>
/// <param name="message">
/// The message to include in the exception when <paramref name="actual"/>
/// is the same as <paramref name="notExpected"/>. The message is shown in
/// test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Thrown if <paramref name="notExpected"/> refers to the same object
/// as <paramref name="actual"/>.
/// </exception>
static public void AreNotSame(object notExpected, object actual, string message)
{
if (Object.ReferenceEquals(notExpected, actual))
{
Assert.HandleFail("Assert.AreNotSame", message);
}
}
static public void OfType<T>(object obj)
{
if (!(obj is T))
{
Assert.HandleFail(
"Assert.IsOfType",
$"Expected an object of type [{typeof(T).AssemblyQualifiedName}], got type of type [{obj.GetType().AssemblyQualifiedName}].");
}
}
/// <summary>
/// Throws an AssertFailedException.
/// </summary>
/// <exception cref="AssertFailedException">
/// Always thrown.
/// </exception>
public static void Fail()
{
Assert.HandleFail("Assert.Fail", "");
}
/// <summary>
/// Throws an AssertFailedException.
/// </summary>
/// <param name="message">
/// The message to include in the exception. The message is shown in
/// test results.
/// </param>
/// <exception cref="AssertFailedException">
/// Always thrown.
/// </exception>
public static void Fail(string message, params object[] args)
{
string exceptionMessage = args.Length == 0 ? message : string.Format(message, args);
Assert.HandleFail("Assert.Fail", exceptionMessage);
}
/// <summary>
/// Helper function that creates and throws an exception.
/// </summary>
/// <param name="assertionName">name of the assertion throwing an exception.</param>
/// <param name="message">message describing conditions for assertion failure.</param>
/// <param name="parameters">The parameters.</param>
/// TODO: Modify HandleFail to take in parameters
internal static void HandleFail(string assertionName, string message)
{
// change this to use AssertFailedException
throw new AssertTestException(assertionName + ": " + message);
}
[Obsolete("Did you mean to call Assert.AreEqual()")]
public static new bool Equals(Object o1, Object o2)
{
Assert.Fail("Don\u2019t call this.");
throw new Exception();
}
private static bool IsOfExceptionType<T>(Exception thrown, AssertThrowsOptions options)
{
if ((options & AssertThrowsOptions.AllowDerived) == AssertThrowsOptions.AllowDerived)
return thrown is T;
return thrown.GetType() == typeof(T);
}
private static Exception RunWithCatch(Action action)
{
try
{
action();
return null;
}
catch (Exception ex)
{
return ex;
}
}
private static async Task<Exception> RunWithCatchAsync(Func<Task> action)
{
try
{
await action();
return null;
}
catch (Exception ex)
{
return ex;
}
}
}
/// <summary>
/// Exception raised by the Assert on Fail
/// </summary>
public class AssertTestException : Exception
{
public AssertTestException(string message)
: base(message)
{
}
public AssertTestException()
: base()
{
}
}
public static class ExceptionAssert
{
public static void Throws<T>(String message, Action a) where T : Exception
{
Assert.Throws<T>(a, message);
}
}
/// <summary>
/// Specifies whether <see cref="Assert.Throws{T}"/> should require an exact type match when comparing the expected exception type with the thrown exception.
/// </summary>
[Flags]
public enum AssertThrowsOptions
{
/// <summary>
/// Specifies that <see cref="Assert.Throws{T}"/> should require an exact type
/// match when comparing the specified exception type with the throw exception.
/// </summary>
None = 0,
/// <summary>
/// Specifies that <see cref="Assert.Throws{T}"/> should not require an exact type
/// match when comparing the specified exception type with the thrown exception.
/// </summary>
AllowDerived = 1,
}
}
| |
#region Namespaces
using System;
using System.Collections;
using System.ComponentModel;
using System.Drawing;
using System.Text;
using System.Text.RegularExpressions;
using System.Data;
using System.Windows.Forms;
using Epi;
using Epi.Data.Services;
using Epi.Windows.Controls;
#endregion //Namespaces
namespace Epi.Windows.Analysis.Dialogs
{
/// <summary>
/// Dialog for Define Variable command
/// </summary>
public partial class DefineVariableDialog : CommandDesignDialog
{
#region Constructors
/// <summary>
/// Default constructor - NOT TO BE USED FOR INSTANTIATION
/// </summary>
[Obsolete("Use of default constructor not allowed", true)]
public DefineVariableDialog()
{
InitializeComponent();
//if (!this.DesignMode) // designer throws an error
//{
// this.btnOK.Click += new System.EventHandler(this.btnOK_Click);
// this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click);
//}
}
/// <summary>
/// Constructor for DefineVariable dialog
/// </summary>
public DefineVariableDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm)
: base(frm)
{
InitializeComponent();
Construct();
}
/// <summary>
/// Oveloaded constructor for DefineVariableDialog which
/// </summary>
/// <param name="frm">The main form</param>
/// <param name="showSave">Boolean to denote whether to show the Save Only button on the dialog</param>
public DefineVariableDialog(Epi.Windows.Analysis.Forms.AnalysisMainForm frm, bool showSave)
: base(frm)
{
InitializeComponent();
if (showSave)
{
showSaveOnly = true;
this.btnSaveOnly.Click += new System.EventHandler(this.btnSaveOnly_Click);
}
Construct();
}
#endregion Constructors
#region Private Attributes
private bool showSaveOnly = false;
#endregion Private Attributes
#region Public Methods
#endregion Public Methods
#region Private Methods
private void Construct()
{
if (!this.DesignMode)
{
LoadVarTypes();
this.btnOK.Click += new System.EventHandler( this.btnOK_Click );
}
}
/// <summary>
/// Reposition buttons on dialog
/// </summary>
private void RepositionButtons()
{
if (btnSaveOnly.Visible)
{
int x = btnClear.Left;
int y = btnClear.Top;
btnClear.Location = new Point(btnCancel.Left, y);
btnCancel.Location = new Point(btnOK.Left, y);
btnOK.Location = new Point(btnSaveOnly.Left, y);
btnSaveOnly.Location = new Point(x, y);
}
}
/// <summary>
/// Loads the Variable Type combo box
/// </summary>
private void LoadVarTypes()
{
LocalizedComboBox cmb = cmbVarType;
if (cmb.DataSource == null)
{
cmb.Items.Clear();
cmb.DataSource = AppData.Instance.DataTypesDataTable.DefaultView;
cmb.DisplayMember = ColumnNames.NAME;
cmb.ValueMember = ColumnNames.DATATYPEID;
cmb.SkipTranslation = false;
cmb.SelectedIndex = -1;
}
//Localization.LocalizeComboBoxItems(cmb,false);
}
#endregion //Private Methods
#region Event Handlers
/// <summary>
/// Clears user input
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void btnClear_Click(object sender, System.EventArgs e)
{
txtVarName.Text = string.Empty;
cmbVarType.SelectedIndex = -1;
cmbVarType.SelectedIndex = -1;
txtDLLObjectDef.Text = string.Empty;
rdbStandard.Checked = true;
this.cmbVarType.SelectedItem = null;
}
/// <summary>
/// Enables OK and Save Only if validation passes
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
private void txtVarName_Leave(object sender, System.EventArgs e)
{
CheckForInputSufficiency();
}
/// <summary>
/// Loads the dialog
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void DefineVariableDialog_Load(object sender, EventArgs e)
{
btnSaveOnly.Visible = showSaveOnly;
if (showSaveOnly)
{
RepositionButtons();
}
}
/// <summary>
/// Handles the Text Changed event of the variable name textbox
/// </summary>
/// <param name="sender">Object that fired the event</param>
/// <param name="e">.NET supplied event parameters</param>
private void txtVarName_TextChanged(object sender, EventArgs e)
{
CheckForInputSufficiency();
}
private void cmbVarType_SelectedIndexChanged(object sender, EventArgs e)
{
if (cmbVarType.Text.Equals("Object"))
{
lblDLLObjectDef.Enabled = true;
txtDLLObjectDef.Enabled = true;
}
else
{
txtDLLObjectDef.Text = string.Empty;
lblDLLObjectDef.Enabled = false;
txtDLLObjectDef.Enabled = false;
}
CheckForInputSufficiency();
}
private void txtDLLObjectDef_TextChanged(object sender, EventArgs e)
{
CheckForInputSufficiency();
}
/// <summary>
/// Opens a process to show the related help topic
/// </summary>
/// <param name="sender">Object that fired the event.</param>
/// <param name="e">.NET supplied event args.</param>
protected override void btnHelp_Click(object sender, System.EventArgs e)
{
System.Diagnostics.Process.Start("http://www.cdc.gov/epiinfo/user-guide/command-reference/analysis-commands-define.html");
}
#endregion Event Handlers
#region Protected Methods
/// <summary>
/// Validates user input
/// </summary>
/// <returns>true if ErrorMessages.Count is 0; otherwise false</returns>
protected override bool ValidateInput()
{
base.ValidateInput();
lblVarNameErr.Text = string.Empty;
lblVarNameErr.Visible = false;
if (string.IsNullOrEmpty(txtVarName.Text.Trim()))
{
ErrorMessages.Add(SharedStrings.EMPTY_VARNAME);
}
else
{
string strTestForSymbols = txtVarName.Text;
Regex regex = new Regex("[\\w\\d]", RegexOptions.IgnoreCase);
string strResultOfSymbolTest = regex.Replace(strTestForSymbols, string.Empty);
string strMessage = string.Empty;
if (strResultOfSymbolTest.Length > 0)
{
strMessage = string.Format(SharedStrings.INVALID_CHARS_IN_VAR_NAME, strResultOfSymbolTest);
ErrorMessages.Add(strMessage);
lblVarNameErr.Text = strMessage;
lblVarNameErr.Visible = true;
}
if (AppData.Instance.IsReservedWord(txtVarName.Text.Trim()))
{
strMessage = SharedStrings.VAR_NAME_IS_RESERVED;
ErrorMessages.Add(strMessage);
lblVarNameErr.Text = strMessage;
lblVarNameErr.Visible = true;
}
//ToDo: Check for duplicate variable names.
//Something like done in the Rule_Define.cs with this.Context.MemoryRegion.IsVariableInScope(txtVarName.Text)
if (string.IsNullOrEmpty(txtDLLObjectDef.Text.Trim()) && cmbVarType.Text.Equals("Object"))
{
ErrorMessages.Add(SharedStrings.EMPTY_DLL_DEF);
}
}
return (ErrorMessages.Count == 0);
}
/// <summary>
/// Generates command text
/// </summary>
protected override void GenerateCommand()
{
StringBuilder sb = new StringBuilder();
string variableName = txtVarName.Text.Trim() ;
string variableScope = (string)WinUtil.GetSelectedRadioButton(gbxScope).Tag;
// If the Variable Scope is the same as default, then remove it.
if (string.Compare(variableScope, Epi.Defaults.VariableScope.ToString(), true) == 0)
{
variableScope = string.Empty;
}
sb.Append(CommandNames.DEFINE).Append(StringLiterals.SPACE);
sb.Append(variableName).Append(StringLiterals.SPACE);
if (!string.IsNullOrEmpty(variableScope))
{
sb.Append(variableScope).Append(StringLiterals.SPACE);
}
if (!string.IsNullOrEmpty(cmbVarType.Text))
{
DataRow row = ((DataRowView)cmbVarType.SelectedItem).Row;
string expression = row[ColumnNames.EXPRESSION].ToString();
if (!string.IsNullOrEmpty(expression))
{
sb.Append(expression).Append(StringLiterals.SPACE);
}
}
if (!string.IsNullOrEmpty(txtDLLObjectDef.Text.Trim()))
{
sb.Append(StringLiterals.DOUBLEQUOTES).Append(txtDLLObjectDef.Text.Trim()).Append(StringLiterals.DOUBLEQUOTES);
}
CommandText = sb.ToString();
}
/// <summary>
/// Sets enabled property of OK and Save Only
/// </summary>
public override void CheckForInputSufficiency()
{
bool inputValid = ValidateInput();
btnOK.Enabled = inputValid;
btnSaveOnly.Enabled = inputValid;
}
#endregion Protected Methods
private void txtVarName_KeyDown(object sender, KeyEventArgs e)
{
if (e.KeyCode == Keys.Space)
{
e.SuppressKeyPress = true;
}
}
}
}
| |
//------------------------------------------------------------------------------
// Microsoft Avalon
// Copyright (c) Microsoft Corporation, 2001, 2002
//
// File: Rect.cs
//------------------------------------------------------------------------------
using System;
using System.Diagnostics;
using System.ComponentModel;
using System.ComponentModel.Design.Serialization;
using System.Reflection;
using System.Text;
using System.Collections;
using System.Globalization;
using MS.Internal;
using System.Windows;
using System.Windows.Media;
using System.Runtime.InteropServices;
using System.Security;
using System.Security.Permissions;
using MS.Internal.WindowsBase;
namespace System.Windows
{
/// <summary>
/// Rect - The primitive which represents a rectangle. Rects are stored as
/// X, Y (Location) and Width and Height (Size). As a result, Rects cannot have negative
/// Width or Height.
/// </summary>
public partial struct Rect
{
#region Constructors
/// <summary>
/// Constructor which sets the initial values to the values of the parameters
/// </summary>
public Rect(Point location,
Size size)
{
if (size.IsEmpty)
{
this = s_empty;
}
else
{
_x = location._x;
_y = location._y;
_width = size._width;
_height = size._height;
}
}
/// <summary>
/// Constructor which sets the initial values to the values of the parameters.
/// Width and Height must be non-negative
/// </summary>
public Rect(double x,
double y,
double width,
double height)
{
if (width < 0 || height < 0)
{
throw new System.ArgumentException(SR.Get(SRID.Size_WidthAndHeightCannotBeNegative));
}
_x = x;
_y = y;
_width = width;
_height = height;
}
/// <summary>
/// Constructor which sets the initial values to bound the two points provided.
/// </summary>
public Rect(Point point1,
Point point2)
{
_x = Math.Min(point1._x, point2._x);
_y = Math.Min(point1._y, point2._y);
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
_width = Math.Max(Math.Max(point1._x, point2._x) - _x, 0);
_height = Math.Max(Math.Max(point1._y, point2._y) - _y, 0);
}
/// <summary>
/// Constructor which sets the initial values to bound the point provided and the point
/// which results from point + vector.
/// </summary>
public Rect(Point point,
Vector vector): this(point, point+vector)
{
}
/// <summary>
/// Constructor which sets the initial values to bound the (0,0) point and the point
/// that results from (0,0) + size.
/// </summary>
public Rect(Size size)
{
if(size.IsEmpty)
{
this = s_empty;
}
else
{
_x = _y = 0;
_width = size.Width;
_height = size.Height;
}
}
#endregion Constructors
#region Statics
/// <summary>
/// Empty - a static property which provides an Empty rectangle. X and Y are positive-infinity
/// and Width and Height are negative infinity. This is the only situation where Width or
/// Height can be negative.
/// </summary>
public static Rect Empty
{
get
{
return s_empty;
}
}
#endregion Statics
#region Public Properties
/// <summary>
/// IsEmpty - this returns true if this rect is the Empty rectangle.
/// Note: If width or height are 0 this Rectangle still contains a 0 or 1 dimensional set
/// of points, so this method should not be used to check for 0 area.
/// </summary>
public bool IsEmpty
{
get
{
// The funny width and height tests are to handle NaNs
Debug.Assert((!(_width < 0) && !(_height < 0)) || (this == Empty));
return _width < 0;
}
}
/// <summary>
/// Location - The Point representing the origin of the Rectangle
/// </summary>
public Point Location
{
get
{
return new Point(_x, _y);
}
set
{
if (IsEmpty)
{
throw new System.InvalidOperationException(SR.Get(SRID.Rect_CannotModifyEmptyRect));
}
_x = value._x;
_y = value._y;
}
}
/// <summary>
/// Size - The Size representing the area of the Rectangle
/// </summary>
public Size Size
{
get
{
if (IsEmpty)
return Size.Empty;
return new Size(_width, _height);
}
set
{
if (value.IsEmpty)
{
this = s_empty;
}
else
{
if (IsEmpty)
{
throw new System.InvalidOperationException(SR.Get(SRID.Rect_CannotModifyEmptyRect));
}
_width = value._width;
_height = value._height;
}
}
}
/// <summary>
/// X - The X coordinate of the Location.
/// If this is the empty rectangle, the value will be positive infinity.
/// If this rect is Empty, setting this property is illegal.
/// </summary>
public double X
{
get
{
return _x;
}
set
{
if (IsEmpty)
{
throw new System.InvalidOperationException(SR.Get(SRID.Rect_CannotModifyEmptyRect));
}
_x = value;
}
}
/// <summary>
/// Y - The Y coordinate of the Location
/// If this is the empty rectangle, the value will be positive infinity.
/// If this rect is Empty, setting this property is illegal.
/// </summary>
public double Y
{
get
{
return _y;
}
set
{
if (IsEmpty)
{
throw new System.InvalidOperationException(SR.Get(SRID.Rect_CannotModifyEmptyRect));
}
_y = value;
}
}
/// <summary>
/// Width - The Width component of the Size. This cannot be set to negative, and will only
/// be negative if this is the empty rectangle, in which case it will be negative infinity.
/// If this rect is Empty, setting this property is illegal.
/// </summary>
public double Width
{
get
{
return _width;
}
set
{
if (IsEmpty)
{
throw new System.InvalidOperationException(SR.Get(SRID.Rect_CannotModifyEmptyRect));
}
if (value < 0)
{
throw new System.ArgumentException(SR.Get(SRID.Size_WidthCannotBeNegative));
}
_width = value;
}
}
/// <summary>
/// Height - The Height component of the Size. This cannot be set to negative, and will only
/// be negative if this is the empty rectangle, in which case it will be negative infinity.
/// If this rect is Empty, setting this property is illegal.
/// </summary>
public double Height
{
get
{
return _height;
}
set
{
if (IsEmpty)
{
throw new System.InvalidOperationException(SR.Get(SRID.Rect_CannotModifyEmptyRect));
}
if (value < 0)
{
throw new System.ArgumentException(SR.Get(SRID.Size_HeightCannotBeNegative));
}
_height = value;
}
}
/// <summary>
/// Left Property - This is a read-only alias for X
/// If this is the empty rectangle, the value will be positive infinity.
/// </summary>
public double Left
{
get
{
return _x;
}
}
/// <summary>
/// Top Property - This is a read-only alias for Y
/// If this is the empty rectangle, the value will be positive infinity.
/// </summary>
public double Top
{
get
{
return _y;
}
}
/// <summary>
/// Right Property - This is a read-only alias for X + Width
/// If this is the empty rectangle, the value will be negative infinity.
/// </summary>
public double Right
{
get
{
if (IsEmpty)
{
return Double.NegativeInfinity;
}
return _x + _width;
}
}
/// <summary>
/// Bottom Property - This is a read-only alias for Y + Height
/// If this is the empty rectangle, the value will be negative infinity.
/// </summary>
public double Bottom
{
get
{
if (IsEmpty)
{
return Double.NegativeInfinity;
}
return _y + _height;
}
}
/// <summary>
/// TopLeft Property - This is a read-only alias for the Point which is at X, Y
/// If this is the empty rectangle, the value will be positive infinity, positive infinity.
/// </summary>
public Point TopLeft
{
get
{
return new Point(Left, Top);
}
}
/// <summary>
/// TopRight Property - This is a read-only alias for the Point which is at X + Width, Y
/// If this is the empty rectangle, the value will be negative infinity, positive infinity.
/// </summary>
public Point TopRight
{
get
{
return new Point(Right, Top);
}
}
/// <summary>
/// BottomLeft Property - This is a read-only alias for the Point which is at X, Y + Height
/// If this is the empty rectangle, the value will be positive infinity, negative infinity.
/// </summary>
public Point BottomLeft
{
get
{
return new Point(Left, Bottom);
}
}
/// <summary>
/// BottomRight Property - This is a read-only alias for the Point which is at X + Width, Y + Height
/// If this is the empty rectangle, the value will be negative infinity, negative infinity.
/// </summary>
public Point BottomRight
{
get
{
return new Point(Right, Bottom);
}
}
#endregion Public Properties
#region Public Methods
/// <summary>
/// Contains - Returns true if the Point is within the rectangle, inclusive of the edges.
/// Returns false otherwise.
/// </summary>
/// <param name="point"> The point which is being tested </param>
/// <returns>
/// Returns true if the Point is within the rectangle.
/// Returns false otherwise
/// </returns>
public bool Contains(Point point)
{
return Contains(point._x, point._y);
}
/// <summary>
/// Contains - Returns true if the Point represented by x,y is within the rectangle inclusive of the edges.
/// Returns false otherwise.
/// </summary>
/// <param name="x"> X coordinate of the point which is being tested </param>
/// <param name="y"> Y coordinate of the point which is being tested </param>
/// <returns>
/// Returns true if the Point represented by x,y is within the rectangle.
/// Returns false otherwise.
/// </returns>
public bool Contains(double x, double y)
{
if (IsEmpty)
{
return false;
}
return ContainsInternal(x,y);
}
/// <summary>
/// Contains - Returns true if the Rect non-Empty and is entirely contained within the
/// rectangle, inclusive of the edges.
/// Returns false otherwise
/// </summary>
public bool Contains(Rect rect)
{
if (IsEmpty || rect.IsEmpty)
{
return false;
}
return (_x <= rect._x &&
_y <= rect._y &&
_x+_width >= rect._x+rect._width &&
_y+_height >= rect._y+rect._height );
}
/// <summary>
/// IntersectsWith - Returns true if the Rect intersects with this rectangle
/// Returns false otherwise.
/// Note that if one edge is coincident, this is considered an intersection.
/// </summary>
/// <returns>
/// Returns true if the Rect intersects with this rectangle
/// Returns false otherwise.
/// or Height
/// </returns>
/// <param name="rect"> Rect </param>
public bool IntersectsWith(Rect rect)
{
if (IsEmpty || rect.IsEmpty)
{
return false;
}
return (rect.Left <= Right) &&
(rect.Right >= Left) &&
(rect.Top <= Bottom) &&
(rect.Bottom >= Top);
}
/// <summary>
/// Intersect - Update this rectangle to be the intersection of this and rect
/// If either this or rect are Empty, the result is Empty as well.
/// </summary>
/// <param name="rect"> The rect to intersect with this </param>
public void Intersect(Rect rect)
{
if (!this.IntersectsWith(rect))
{
this = Empty;
}
else
{
double left = Math.Max(Left, rect.Left);
double top = Math.Max(Top, rect.Top);
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
_width = Math.Max(Math.Min(Right, rect.Right) - left, 0);
_height = Math.Max(Math.Min(Bottom, rect.Bottom) - top, 0);
_x = left;
_y = top;
}
}
/// <summary>
/// Intersect - Return the result of the intersection of rect1 and rect2.
/// If either this or rect are Empty, the result is Empty as well.
/// </summary>
public static Rect Intersect(Rect rect1, Rect rect2)
{
rect1.Intersect(rect2);
return rect1;
}
/// <summary>
/// Union - Update this rectangle to be the union of this and rect.
/// </summary>
public void Union(Rect rect)
{
if (IsEmpty)
{
this = rect;
}
else if (!rect.IsEmpty)
{
double left = Math.Min(Left, rect.Left);
double top = Math.Min(Top, rect.Top);
// We need this check so that the math does not result in NaN
if ((rect.Width == Double.PositiveInfinity) || (Width == Double.PositiveInfinity))
{
_width = Double.PositiveInfinity;
}
else
{
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
double maxRight = Math.Max(Right, rect.Right);
_width = Math.Max(maxRight - left, 0);
}
// We need this check so that the math does not result in NaN
if ((rect.Height == Double.PositiveInfinity) || (Height == Double.PositiveInfinity))
{
_height = Double.PositiveInfinity;
}
else
{
// Max with 0 to prevent double weirdness from causing us to be (-epsilon..0)
double maxBottom = Math.Max(Bottom, rect.Bottom);
_height = Math.Max(maxBottom - top, 0);
}
_x = left;
_y = top;
}
}
/// <summary>
/// Union - Return the result of the union of rect1 and rect2.
/// </summary>
public static Rect Union(Rect rect1, Rect rect2)
{
rect1.Union(rect2);
return rect1;
}
/// <summary>
/// Union - Update this rectangle to be the union of this and point.
/// </summary>
public void Union(Point point)
{
Union(new Rect(point, point));
}
/// <summary>
/// Union - Return the result of the union of rect and point.
/// </summary>
public static Rect Union(Rect rect, Point point)
{
rect.Union(new Rect(point, point));
return rect;
}
/// <summary>
/// Offset - translate the Location by the offset provided.
/// If this is Empty, this method is illegal.
/// </summary>
public void Offset(Vector offsetVector)
{
if (IsEmpty)
{
throw new System.InvalidOperationException(SR.Get(SRID.Rect_CannotCallMethod));
}
_x += offsetVector._x;
_y += offsetVector._y;
}
/// <summary>
/// Offset - translate the Location by the offset provided
/// If this is Empty, this method is illegal.
/// </summary>
public void Offset(double offsetX, double offsetY)
{
if (IsEmpty)
{
throw new System.InvalidOperationException(SR.Get(SRID.Rect_CannotCallMethod));
}
_x += offsetX;
_y += offsetY;
}
/// <summary>
/// Offset - return the result of offsetting rect by the offset provided
/// If this is Empty, this method is illegal.
/// </summary>
public static Rect Offset(Rect rect, Vector offsetVector)
{
rect.Offset(offsetVector.X, offsetVector.Y);
return rect;
}
/// <summary>
/// Offset - return the result of offsetting rect by the offset provided
/// If this is Empty, this method is illegal.
/// </summary>
public static Rect Offset(Rect rect, double offsetX, double offsetY)
{
rect.Offset(offsetX, offsetY);
return rect;
}
/// <summary>
/// Inflate - inflate the bounds by the size provided, in all directions
/// If this is Empty, this method is illegal.
/// </summary>
public void Inflate(Size size)
{
Inflate(size._width, size._height);
}
/// <summary>
/// Inflate - inflate the bounds by the size provided, in all directions.
/// If -width is > Width / 2 or -height is > Height / 2, this Rect becomes Empty
/// If this is Empty, this method is illegal.
/// </summary>
public void Inflate(double width, double height)
{
if (IsEmpty)
{
throw new System.InvalidOperationException(SR.Get(SRID.Rect_CannotCallMethod));
}
_x -= width;
_y -= height;
// Do two additions rather than multiplication by 2 to avoid spurious overflow
// That is: (A + 2 * B) != ((A + B) + B) if 2*B overflows.
// Note that multiplication by 2 might work in this case because A should start
// positive & be "clamped" to positive after, but consider A = Inf & B = -MAX.
_width += width;
_width += width;
_height += height;
_height += height;
// We catch the case of inflation by less than -width/2 or -height/2 here. This also
// maintains the invariant that either the Rect is Empty or _width and _height are
// non-negative, even if the user parameters were NaN, though this isn't strictly maintained
// by other methods.
if ( !(_width >= 0 && _height >= 0) )
{
this = s_empty;
}
}
/// <summary>
/// Inflate - return the result of inflating rect by the size provided, in all directions
/// If this is Empty, this method is illegal.
/// </summary>
public static Rect Inflate(Rect rect, Size size)
{
rect.Inflate(size._width, size._height);
return rect;
}
/// <summary>
/// Inflate - return the result of inflating rect by the size provided, in all directions
/// If this is Empty, this method is illegal.
/// </summary>
public static Rect Inflate(Rect rect, double width, double height)
{
rect.Inflate(width, height);
return rect;
}
/// <summary>
/// Returns the bounds of the transformed rectangle.
/// The Empty Rect is not affected by this call.
/// </summary>
/// <returns>
/// The rect which results from the transformation.
/// </returns>
/// <param name="rect"> The Rect to transform. </param>
/// <param name="matrix"> The Matrix by which to transform. </param>
public static Rect Transform(Rect rect, Matrix matrix)
{
MatrixUtil.TransformRect(ref rect, ref matrix);
return rect;
}
/// <summary>
/// Updates rectangle to be the bounds of the original value transformed
/// by the matrix.
/// The Empty Rect is not affected by this call.
/// </summary>
/// <param name="matrix"> Matrix </param>
public void Transform(Matrix matrix)
{
MatrixUtil.TransformRect(ref this, ref matrix);
}
/// <summary>
/// Scale the rectangle in the X and Y directions
/// </summary>
/// <param name="scaleX"> The scale in X </param>
/// <param name="scaleY"> The scale in Y </param>
public void Scale(double scaleX, double scaleY)
{
if (IsEmpty)
{
return;
}
_x *= scaleX;
_y *= scaleY;
_width *= scaleX;
_height *= scaleY;
// If the scale in the X dimension is negative, we need to normalize X and Width
if (scaleX < 0)
{
// Make X the left-most edge again
_x += _width;
// and make Width positive
_width *= -1;
}
// Do the same for the Y dimension
if (scaleY < 0)
{
// Make Y the top-most edge again
_y += _height;
// and make Height positive
_height *= -1;
}
}
#endregion Public Methods
#region Private Methods
/// <summary>
/// ContainsInternal - Performs just the "point inside" logic
/// </summary>
/// <returns>
/// bool - true if the point is inside the rect
/// </returns>
/// <param name="x"> The x-coord of the point to test </param>
/// <param name="y"> The y-coord of the point to test </param>
private bool ContainsInternal(double x, double y)
{
// We include points on the edge as "contained".
// We do "x - _width <= _x" instead of "x <= _x + _width"
// so that this check works when _width is PositiveInfinity
// and _x is NegativeInfinity.
return ((x >= _x) && (x - _width <= _x) &&
(y >= _y) && (y - _height <= _y));
}
static private Rect CreateEmptyRect()
{
Rect rect = new Rect();
// We can't set these via the property setters because negatives widths
// are rejected in those APIs.
rect._x = Double.PositiveInfinity;
rect._y = Double.PositiveInfinity;
rect._width = Double.NegativeInfinity;
rect._height = Double.NegativeInfinity;
return rect;
}
#endregion Private Methods
#region Private Fields
private readonly static Rect s_empty = CreateEmptyRect();
#endregion Private Fields
}
}
| |
/******************************************************************************
* Spine Runtimes Software License
* Version 2.1
*
* Copyright (c) 2013, Esoteric Software
* All rights reserved.
*
* You are granted a perpetual, non-exclusive, non-sublicensable and
* non-transferable license to install, execute and perform the Spine Runtimes
* Software (the "Software") solely for internal use. Without the written
* permission of Esoteric Software (typically granted by licensing Spine), you
* may not (a) modify, translate, adapt or otherwise create derivative works,
* improvements of the Software or develop new applications using the Software
* or (b) remove, delete, alter or obscure any trademarks or any copyright,
* trademark, patent or other intellectual property or proprietary rights
* notices on or in the Software, including any copy thereof. Redistributions
* in binary or source form must include this license and terms.
*
* THIS SOFTWARE IS PROVIDED BY ESOTERIC SOFTWARE "AS IS" AND ANY EXPRESS OR
* IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
* MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO
* EVENT SHALL ESOTERIC SOFTARE 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.
*****************************************************************************/
/*****************************************************************************
* Skeleton Utility created by Mitch Thompson
* Full irrevocable rights and permissions granted to Esoteric Software
*****************************************************************************/
using UnityEngine;
using UnityEditor;
#if UNITY_4_3
//nothing
#else
using UnityEditor.AnimatedValues;
#endif
using System.Collections;
using System.Collections.Generic;
using Spine;
using System.Reflection;
[CustomEditor(typeof(SkeletonUtility))]
public class SkeletonUtilityInspector : Editor {
public static void AttachIcon (SkeletonUtilityBone utilityBone) {
Skeleton skeleton = utilityBone.skeletonUtility.skeletonRenderer.skeleton;
Texture2D icon;
if (utilityBone.bone.Data.Length == 0)
icon = SpineEditorUtilities.Icons.nullBone;
else
icon = SpineEditorUtilities.Icons.boneNib;
foreach (IkConstraint c in skeleton.IkConstraints) {
if (c.Target == utilityBone.bone) {
icon = SpineEditorUtilities.Icons.constraintNib;
break;
}
}
typeof(EditorGUIUtility).InvokeMember("SetIconForObject", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.NonPublic, null, null, new object[2] {
utilityBone.gameObject,
icon
});
}
static void AttachIconsToChildren (Transform root) {
if (root != null) {
var utilityBones = root.GetComponentsInChildren<SkeletonUtilityBone>();
foreach (var utilBone in utilityBones) {
AttachIcon(utilBone);
}
}
}
static SkeletonUtilityInspector () {
#if UNITY_4_3
showSlots = false;
#else
showSlots = new AnimBool(false);
#endif
}
SkeletonUtility skeletonUtility;
Skeleton skeleton;
SkeletonRenderer skeletonRenderer;
Transform transform;
bool isPrefab;
Dictionary<Slot, List<Attachment>> attachmentTable = new Dictionary<Slot, List<Attachment>>();
//GUI stuff
#if UNITY_4_3
static bool showSlots;
#else
static AnimBool showSlots;
#endif
void OnEnable () {
skeletonUtility = (SkeletonUtility)target;
skeletonRenderer = skeletonUtility.GetComponent<SkeletonRenderer>();
skeleton = skeletonRenderer.skeleton;
transform = skeletonRenderer.transform;
if (skeleton == null) {
skeletonRenderer.Reset();
skeletonRenderer.LateUpdate();
skeleton = skeletonRenderer.skeleton;
}
UpdateAttachments();
if (PrefabUtility.GetPrefabType(this.target) == PrefabType.Prefab)
isPrefab = true;
}
void OnDestroy () {
}
void OnSceneGUI () {
if (skeleton == null) {
OnEnable();
return;
}
float flipRotation = skeleton.FlipX ? -1 : 1;
foreach (Bone b in skeleton.Bones) {
Vector3 vec = transform.TransformPoint(new Vector3(b.WorldX, b.WorldY, 0));
Quaternion rot = Quaternion.Euler(0, 0, b.WorldRotation * flipRotation);
Vector3 forward = transform.TransformDirection(rot * Vector3.right);
forward *= flipRotation;
SpineEditorUtilities.Icons.boneMaterial.SetPass(0);
Graphics.DrawMeshNow(SpineEditorUtilities.Icons.boneMesh, Matrix4x4.TRS(vec, Quaternion.LookRotation(transform.forward, forward), Vector3.one * b.Data.Length * b.WorldScaleX));
}
}
void UpdateAttachments () {
attachmentTable = new Dictionary<Slot, List<Attachment>>();
Skin skin = skeleton.Skin;
if (skin == null) {
skin = skeletonRenderer.skeletonDataAsset.GetSkeletonData(true).DefaultSkin;
}
for (int i = skeleton.Slots.Count-1; i >= 0; i--) {
List<Attachment> attachments = new List<Attachment>();
skin.FindAttachmentsForSlot(i, attachments);
attachmentTable.Add(skeleton.Slots[i], attachments);
}
}
void SpawnHierarchyButton (string label, string tooltip, SkeletonUtilityBone.Mode mode, bool pos, bool rot, bool sca, params GUILayoutOption[] options) {
GUIContent content = new GUIContent(label, tooltip);
if (GUILayout.Button(content, options)) {
if (skeletonUtility.skeletonRenderer == null)
skeletonUtility.skeletonRenderer = skeletonUtility.GetComponent<SkeletonRenderer>();
if (skeletonUtility.boneRoot != null) {
return;
}
skeletonUtility.SpawnHierarchy(mode, pos, rot, sca);
SkeletonUtilityBone[] boneComps = skeletonUtility.GetComponentsInChildren<SkeletonUtilityBone>();
foreach (SkeletonUtilityBone b in boneComps)
AttachIcon(b);
}
}
public override void OnInspectorGUI () {
if (isPrefab) {
GUILayout.Label(new GUIContent("Cannot edit Prefabs", SpineEditorUtilities.Icons.warning));
return;
}
skeletonUtility.boneRoot = (Transform)EditorGUILayout.ObjectField("Bone Root", skeletonUtility.boneRoot, typeof(Transform), true);
GUILayout.BeginHorizontal();
EditorGUI.BeginDisabledGroup(skeletonUtility.boneRoot != null);
{
if (GUILayout.Button(new GUIContent("Spawn Hierarchy", SpineEditorUtilities.Icons.skeleton), GUILayout.Width(150), GUILayout.Height(24)))
SpawnHierarchyContextMenu();
}
EditorGUI.EndDisabledGroup();
if (GUILayout.Button(new GUIContent("Spawn Submeshes", SpineEditorUtilities.Icons.subMeshRenderer), GUILayout.Width(150), GUILayout.Height(24)))
skeletonUtility.SpawnSubRenderers(true);
GUILayout.EndHorizontal();
EditorGUI.BeginChangeCheck();
skeleton.FlipX = EditorGUILayout.ToggleLeft("Flip X", skeleton.FlipX);
skeleton.FlipY = EditorGUILayout.ToggleLeft("Flip Y", skeleton.FlipY);
if (EditorGUI.EndChangeCheck()) {
skeletonRenderer.LateUpdate();
SceneView.RepaintAll();
}
#if UNITY_4_3
showSlots = EditorGUILayout.Foldout(showSlots, "Slots");
#else
showSlots.target = EditorGUILayout.Foldout(showSlots.target, "Slots");
if (EditorGUILayout.BeginFadeGroup(showSlots.faded)) {
#endif
foreach (KeyValuePair<Slot, List<Attachment>> pair in attachmentTable) {
Slot slot = pair.Key;
EditorGUILayout.BeginHorizontal();
EditorGUI.indentLevel = 1;
EditorGUILayout.LabelField(new GUIContent(slot.Data.Name, SpineEditorUtilities.Icons.slot), GUILayout.ExpandWidth(false));
EditorGUI.BeginChangeCheck();
Color c = EditorGUILayout.ColorField(new Color(slot.R, slot.G, slot.B, slot.A), GUILayout.Width(60));
if (EditorGUI.EndChangeCheck()) {
slot.SetColor(c);
skeletonRenderer.LateUpdate();
}
EditorGUILayout.EndHorizontal();
foreach (Attachment attachment in pair.Value) {
if (slot.Attachment == attachment) {
GUI.contentColor = Color.white;
} else {
GUI.contentColor = Color.grey;
}
EditorGUI.indentLevel = 2;
bool isAttached = attachment == slot.Attachment;
Texture2D icon = null;
if (attachment is MeshAttachment || attachment is SkinnedMeshAttachment)
icon = SpineEditorUtilities.Icons.mesh;
else
icon = SpineEditorUtilities.Icons.image;
bool swap = EditorGUILayout.ToggleLeft(new GUIContent(attachment.Name, icon), attachment == slot.Attachment);
if (!isAttached && swap) {
slot.Attachment = attachment;
skeletonRenderer.LateUpdate();
} else if (isAttached && !swap) {
slot.Attachment = null;
skeletonRenderer.LateUpdate();
}
GUI.contentColor = Color.white;
}
}
#if UNITY_4_3
#else
}
EditorGUILayout.EndFadeGroup();
if (showSlots.isAnimating)
Repaint();
#endif
}
void SpawnHierarchyContextMenu () {
GenericMenu menu = new GenericMenu();
menu.AddItem(new GUIContent("Follow"), false, SpawnFollowHierarchy);
menu.AddItem(new GUIContent("Follow (Root Only)"), false, SpawnFollowHierarchyRootOnly);
menu.AddSeparator("");
menu.AddItem(new GUIContent("Override"), false, SpawnOverrideHierarchy);
menu.AddItem(new GUIContent("Override (Root Only)"), false, SpawnOverrideHierarchyRootOnly);
menu.ShowAsContext();
}
void SpawnFollowHierarchy () {
Selection.activeGameObject = skeletonUtility.SpawnHierarchy(SkeletonUtilityBone.Mode.Follow, true, true, true);
AttachIconsToChildren(skeletonUtility.boneRoot);
}
void SpawnFollowHierarchyRootOnly () {
Selection.activeGameObject = skeletonUtility.SpawnRoot(SkeletonUtilityBone.Mode.Follow, true, true, true);
AttachIconsToChildren(skeletonUtility.boneRoot);
}
void SpawnOverrideHierarchy () {
Selection.activeGameObject = skeletonUtility.SpawnHierarchy(SkeletonUtilityBone.Mode.Override, true, true, true);
AttachIconsToChildren(skeletonUtility.boneRoot);
}
void SpawnOverrideHierarchyRootOnly () {
Selection.activeGameObject = skeletonUtility.SpawnRoot(SkeletonUtilityBone.Mode.Override, true, true, true);
AttachIconsToChildren(skeletonUtility.boneRoot);
}
}
| |
#region Copyright notice and license
// Protocol Buffers - Google's data interchange format
// Copyright 2008 Google Inc. All rights reserved.
// http://github.com/jskeet/dotnet-protobufs/
// Original C++/Java/Python code:
// http://code.google.com/p/protobuf/
//
// 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.Collections.Generic;
using System.Globalization;
using System.IO;
using System.Text;
using Google.ProtocolBuffers.Descriptors;
using System.Collections;
namespace Google.ProtocolBuffers {
/// <summary>
/// Provides ASCII text formatting support for messages.
/// TODO(jonskeet): Parsing support.
/// </summary>
public static class TextFormat {
/// <summary>
/// Outputs a textual representation of the Protocol Message supplied into
/// the parameter output.
/// </summary>
public static void Print(IMessage message, TextWriter output) {
TextGenerator generator = new TextGenerator(output);
Print(message, generator);
}
/// <summary>
/// Outputs a textual representation of <paramref name="fields" /> to <paramref name="output"/>.
/// </summary>
public static void Print(UnknownFieldSet fields, TextWriter output) {
TextGenerator generator = new TextGenerator(output);
PrintUnknownFields(fields, generator);
}
public static string PrintToString(IMessage message) {
StringWriter text = new StringWriter();
Print(message, text);
return text.ToString();
}
public static string PrintToString(UnknownFieldSet fields) {
StringWriter text = new StringWriter();
Print(fields, text);
return text.ToString();
}
private static void Print(IMessage message, TextGenerator generator) {
foreach (KeyValuePair<FieldDescriptor, object> entry in message.AllFields) {
PrintField(entry.Key, entry.Value, generator);
}
PrintUnknownFields(message.UnknownFields, generator);
}
internal static void PrintField(FieldDescriptor field, object value, TextGenerator generator) {
if (field.IsRepeated) {
// Repeated field. Print each element.
foreach (object element in (IEnumerable) value) {
PrintSingleField(field, element, generator);
}
} else {
PrintSingleField(field, value, generator);
}
}
private static void PrintSingleField(FieldDescriptor field, Object value, TextGenerator generator) {
if (field.IsExtension) {
generator.Print("[");
// We special-case MessageSet elements for compatibility with proto1.
if (field.ContainingType.Options.MessageSetWireFormat
&& field.FieldType == FieldType.Message
&& field.IsOptional
// object equality (TODO(jonskeet): Work out what this comment means!)
&& field.ExtensionScope == field.MessageType) {
generator.Print(field.MessageType.FullName);
} else {
generator.Print(field.FullName);
}
generator.Print("]");
} else {
if (field.FieldType == FieldType.Group) {
// Groups must be serialized with their original capitalization.
generator.Print(field.MessageType.Name);
} else {
generator.Print(field.Name);
}
}
if (field.MappedType == MappedType.Message) {
generator.Print(" {\n");
generator.Indent();
} else {
generator.Print(": ");
}
PrintFieldValue(field, value, generator);
if (field.MappedType == MappedType.Message) {
generator.Outdent();
generator.Print("}");
}
generator.Print("\n");
}
private static void PrintFieldValue(FieldDescriptor field, object value, TextGenerator generator) {
switch (field.FieldType) {
case FieldType.Int32:
case FieldType.Int64:
case FieldType.SInt32:
case FieldType.SInt64:
case FieldType.SFixed32:
case FieldType.SFixed64:
case FieldType.Float:
case FieldType.Double:
case FieldType.UInt32:
case FieldType.UInt64:
case FieldType.Fixed32:
case FieldType.Fixed64:
// The simple Object.ToString converts using the current culture.
// We want to always use the invariant culture so it's predictable.
generator.Print(((IConvertible) value).ToString(CultureInfo.InvariantCulture));
break;
case FieldType.Bool:
// Explicitly use the Java true/false
generator.Print((bool) value ? "true" : "false");
break;
case FieldType.String:
generator.Print("\"");
generator.Print(EscapeText((string) value));
generator.Print("\"");
break;
case FieldType.Bytes: {
generator.Print("\"");
generator.Print(EscapeBytes((ByteString) value));
generator.Print("\"");
break;
}
case FieldType.Enum: {
generator.Print(((EnumValueDescriptor) value).Name);
break;
}
case FieldType.Message:
case FieldType.Group:
Print((IMessage) value, generator);
break;
}
}
private static void PrintUnknownFields(UnknownFieldSet unknownFields, TextGenerator generator) {
foreach (KeyValuePair<int, UnknownField> entry in unknownFields.FieldDictionary) {
String prefix = entry.Key.ToString() + ": ";
UnknownField field = entry.Value;
foreach (ulong value in field.VarintList) {
generator.Print(prefix);
generator.Print(value.ToString());
generator.Print("\n");
}
foreach (uint value in field.Fixed32List) {
generator.Print(prefix);
generator.Print(string.Format("0x{0:x8}", value));
generator.Print("\n");
}
foreach (ulong value in field.Fixed64List) {
generator.Print(prefix);
generator.Print(string.Format("0x{0:x16}", value));
generator.Print("\n");
}
foreach (ByteString value in field.LengthDelimitedList) {
generator.Print(entry.Key.ToString());
generator.Print(": \"");
generator.Print(EscapeBytes(value));
generator.Print("\"\n");
}
foreach (UnknownFieldSet value in field.GroupList) {
generator.Print(entry.Key.ToString());
generator.Print(" {\n");
generator.Indent();
PrintUnknownFields(value, generator);
generator.Outdent();
generator.Print("}\n");
}
}
}
internal static ulong ParseUInt64(string text) {
return (ulong) ParseInteger(text, false, true);
}
internal static long ParseInt64(string text) {
return ParseInteger(text, true, true);
}
internal static uint ParseUInt32(string text) {
return (uint) ParseInteger(text, false, false);
}
internal static int ParseInt32(string text) {
return (int) ParseInteger(text, true, false);
}
internal static float ParseFloat(string text) {
switch (text) {
case "-inf":
case "-infinity":
case "-inff":
case "-infinityf":
return float.NegativeInfinity;
case "inf":
case "infinity":
case "inff":
case "infinityf":
return float.PositiveInfinity;
case "nan":
case "nanf":
return float.NaN;
default:
return float.Parse(text, CultureInfo.InvariantCulture);
}
}
internal static double ParseDouble(string text) {
switch (text) {
case "-inf":
case "-infinity":
return double.NegativeInfinity;
case "inf":
case "infinity":
return double.PositiveInfinity;
case "nan":
return double.NaN;
default:
return double.Parse(text, CultureInfo.InvariantCulture);
}
}
/// <summary>
/// Parses an integer in hex (leading 0x), decimal (no prefix) or octal (leading 0).
/// Only a negative sign is permitted, and it must come before the radix indicator.
/// </summary>
private static long ParseInteger(string text, bool isSigned, bool isLong) {
string original = text;
bool negative = false;
if (text.StartsWith("-")) {
if (!isSigned) {
throw new FormatException("Number must be positive: " + original);
}
negative = true;
text = text.Substring(1);
}
int radix = 10;
if (text.StartsWith("0x")) {
radix = 16;
text = text.Substring(2);
} else if (text.StartsWith("0")) {
radix = 8;
}
ulong result;
try {
// Workaround for https://connect.microsoft.com/VisualStudio/feedback/ViewFeedback.aspx?FeedbackID=278448
// We should be able to use Convert.ToUInt64 for all cases.
result = radix == 10 ? ulong.Parse(text) : Convert.ToUInt64(text, radix);
} catch (OverflowException) {
// Convert OverflowException to FormatException so there's a single exception type this method can throw.
string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32, isSigned ? "" : "un");
throw new FormatException("Number out of range for " + numberDescription + ": " + original);
}
if (negative) {
ulong max = isLong ? 0x8000000000000000UL : 0x80000000L;
if (result > max) {
string numberDescription = string.Format("{0}-bit signed integer", isLong ? 64 : 32);
throw new FormatException("Number out of range for " + numberDescription + ": " + original);
}
return -((long) result);
} else {
ulong max = isSigned
? (isLong ? (ulong) long.MaxValue : int.MaxValue)
: (isLong ? ulong.MaxValue : uint.MaxValue);
if (result > max) {
string numberDescription = string.Format("{0}-bit {1}signed integer", isLong ? 64 : 32, isSigned ? "" : "un");
throw new FormatException("Number out of range for " + numberDescription + ": " + original);
}
return (long) result;
}
}
/// <summary>
/// Tests a character to see if it's an octal digit.
/// </summary>
private static bool IsOctal(char c) {
return '0' <= c && c <= '7';
}
/// <summary>
/// Tests a character to see if it's a hex digit.
/// </summary>
private static bool IsHex(char c) {
return ('0' <= c && c <= '9') ||
('a' <= c && c <= 'f') ||
('A' <= c && c <= 'F');
}
/// <summary>
/// Interprets a character as a digit (in any base up to 36) and returns the
/// numeric value.
/// </summary>
private static int ParseDigit(char c) {
if ('0' <= c && c <= '9') {
return c - '0';
} else if ('a' <= c && c <= 'z') {
return c - 'a' + 10;
} else {
return c - 'A' + 10;
}
}
/// <summary>
/// Unescapes a text string as escaped using <see cref="EscapeText(string)" />.
/// Two-digit hex escapes (starting with "\x" are also recognised.
/// </summary>
internal static string UnescapeText(string input) {
return UnescapeBytes(input).ToStringUtf8();
}
/// <summary>
/// Like <see cref="EscapeBytes" /> but escapes a text string.
/// The string is first encoded as UTF-8, then each byte escaped individually.
/// The returned value is guaranteed to be entirely ASCII.
/// </summary>
internal static string EscapeText(string input) {
return EscapeBytes(ByteString.CopyFromUtf8(input));
}
/// <summary>
/// Escapes bytes in the format used in protocol buffer text format, which
/// is the same as the format used for C string literals. All bytes
/// that are not printable 7-bit ASCII characters are escaped, as well as
/// backslash, single-quote, and double-quote characters. Characters for
/// which no defined short-hand escape sequence is defined will be escaped
/// using 3-digit octal sequences.
/// The returned value is guaranteed to be entirely ASCII.
/// </summary>
internal static String EscapeBytes(ByteString input) {
StringBuilder builder = new StringBuilder(input.Length);
foreach (byte b in input) {
switch (b) {
// C# does not use \a or \v
case 0x07: builder.Append("\\a" ); break;
case (byte)'\b': builder.Append("\\b" ); break;
case (byte)'\f': builder.Append("\\f" ); break;
case (byte)'\n': builder.Append("\\n" ); break;
case (byte)'\r': builder.Append("\\r" ); break;
case (byte)'\t': builder.Append("\\t" ); break;
case 0x0b: builder.Append("\\v" ); break;
case (byte)'\\': builder.Append("\\\\"); break;
case (byte)'\'': builder.Append("\\\'"); break;
case (byte)'"' : builder.Append("\\\""); break;
default:
if (b >= 0x20 && b < 128) {
builder.Append((char) b);
} else {
builder.Append('\\');
builder.Append((char) ('0' + ((b >> 6) & 3)));
builder.Append((char) ('0' + ((b >> 3) & 7)));
builder.Append((char) ('0' + (b & 7)));
}
break;
}
}
return builder.ToString();
}
/// <summary>
/// Performs string unescaping from C style (octal, hex, form feeds, tab etc) into a byte string.
/// </summary>
internal static ByteString UnescapeBytes(string input) {
byte[] result = new byte[input.Length];
int pos = 0;
for (int i = 0; i < input.Length; i++) {
char c = input[i];
if (c > 127 || c < 32) {
throw new FormatException("Escaped string must only contain ASCII");
}
if (c != '\\') {
result[pos++] = (byte) c;
continue;
}
if (i + 1 >= input.Length) {
throw new FormatException("Invalid escape sequence: '\\' at end of string.");
}
i++;
c = input[i];
if (c >= '0' && c <= '7') {
// Octal escape.
int code = ParseDigit(c);
if (i + 1 < input.Length && IsOctal(input[i+1])) {
i++;
code = code * 8 + ParseDigit(input[i]);
}
if (i + 1 < input.Length && IsOctal(input[i+1])) {
i++;
code = code * 8 + ParseDigit(input[i]);
}
result[pos++] = (byte) code;
} else {
switch (c) {
case 'a': result[pos++] = 0x07; break;
case 'b': result[pos++] = (byte) '\b'; break;
case 'f': result[pos++] = (byte) '\f'; break;
case 'n': result[pos++] = (byte) '\n'; break;
case 'r': result[pos++] = (byte) '\r'; break;
case 't': result[pos++] = (byte) '\t'; break;
case 'v': result[pos++] = 0x0b; break;
case '\\': result[pos++] = (byte) '\\'; break;
case '\'': result[pos++] = (byte) '\''; break;
case '"': result[pos++] = (byte) '\"'; break;
case 'x':
// hex escape
int code;
if (i + 1 < input.Length && IsHex(input[i+1])) {
i++;
code = ParseDigit(input[i]);
} else {
throw new FormatException("Invalid escape sequence: '\\x' with no digits");
}
if (i + 1 < input.Length && IsHex(input[i+1])) {
++i;
code = code * 16 + ParseDigit(input[i]);
}
result[pos++] = (byte)code;
break;
default:
throw new FormatException("Invalid escape sequence: '\\" + c + "'");
}
}
}
return ByteString.CopyFrom(result, 0, pos);
}
public static void Merge(string text, IBuilder builder) {
Merge(text, ExtensionRegistry.Empty, builder);
}
public static void Merge(TextReader reader, IBuilder builder) {
Merge(reader, ExtensionRegistry.Empty, builder);
}
public static void Merge(TextReader reader, ExtensionRegistry registry, IBuilder builder) {
Merge(reader.ReadToEnd(), registry, builder);
}
public static void Merge(string text, ExtensionRegistry registry, IBuilder builder) {
TextTokenizer tokenizer = new TextTokenizer(text);
while (!tokenizer.AtEnd) {
MergeField(tokenizer, registry, builder);
}
}
/// <summary>
/// Parses a single field from the specified tokenizer and merges it into
/// the builder.
/// </summary>
private static void MergeField(TextTokenizer tokenizer, ExtensionRegistry extensionRegistry,
IBuilder builder) {
FieldDescriptor field;
MessageDescriptor type = builder.DescriptorForType;
ExtensionInfo extension = null;
if (tokenizer.TryConsume("[")) {
// An extension.
StringBuilder name = new StringBuilder(tokenizer.ConsumeIdentifier());
while (tokenizer.TryConsume(".")) {
name.Append(".");
name.Append(tokenizer.ConsumeIdentifier());
}
extension = extensionRegistry[name.ToString()];
if (extension == null) {
throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name + "\" not found in the ExtensionRegistry.");
} else if (extension.Descriptor.ContainingType != type) {
throw tokenizer.CreateFormatExceptionPreviousToken("Extension \"" + name + "\" does not extend message type \"" +
type.FullName + "\".");
}
tokenizer.Consume("]");
field = extension.Descriptor;
} else {
String name = tokenizer.ConsumeIdentifier();
field = type.FindDescriptor<FieldDescriptor>(name);
// Group names are expected to be capitalized as they appear in the
// .proto file, which actually matches their type names, not their field
// names.
if (field == null) {
// Explicitly specify the invariant culture so that this code does not break when
// executing in Turkey.
String lowerName = name.ToLower(CultureInfo.InvariantCulture);
field = type.FindDescriptor<FieldDescriptor>(lowerName);
// If the case-insensitive match worked but the field is NOT a group,
// TODO(jonskeet): What? Java comment ends here!
if (field != null && field.FieldType != FieldType.Group) {
field = null;
}
}
// Again, special-case group names as described above.
if (field != null && field.FieldType == FieldType.Group && field.MessageType.Name != name) {
field = null;
}
if (field == null) {
throw tokenizer.CreateFormatExceptionPreviousToken(
"Message type \"" + type.FullName + "\" has no field named \"" + name + "\".");
}
}
object value = null;
if (field.MappedType == MappedType.Message) {
tokenizer.TryConsume(":"); // optional
String endToken;
if (tokenizer.TryConsume("<")) {
endToken = ">";
} else {
tokenizer.Consume("{");
endToken = "}";
}
IBuilder subBuilder;
if (extension == null) {
subBuilder = builder.CreateBuilderForField(field);
} else {
subBuilder = extension.DefaultInstance.WeakCreateBuilderForType();
}
while (!tokenizer.TryConsume(endToken)) {
if (tokenizer.AtEnd) {
throw tokenizer.CreateFormatException("Expected \"" + endToken + "\".");
}
MergeField(tokenizer, extensionRegistry, subBuilder);
}
value = subBuilder.WeakBuild();
} else {
tokenizer.Consume(":");
switch (field.FieldType) {
case FieldType.Int32:
case FieldType.SInt32:
case FieldType.SFixed32:
value = tokenizer.ConsumeInt32();
break;
case FieldType.Int64:
case FieldType.SInt64:
case FieldType.SFixed64:
value = tokenizer.ConsumeInt64();
break;
case FieldType.UInt32:
case FieldType.Fixed32:
value = tokenizer.ConsumeUInt32();
break;
case FieldType.UInt64:
case FieldType.Fixed64:
value = tokenizer.ConsumeUInt64();
break;
case FieldType.Float:
value = tokenizer.ConsumeFloat();
break;
case FieldType.Double:
value = tokenizer.ConsumeDouble();
break;
case FieldType.Bool:
value = tokenizer.ConsumeBoolean();
break;
case FieldType.String:
value = tokenizer.ConsumeString();
break;
case FieldType.Bytes:
value = tokenizer.ConsumeByteString();
break;
case FieldType.Enum: {
EnumDescriptor enumType = field.EnumType;
if (tokenizer.LookingAtInteger()) {
int number = tokenizer.ConsumeInt32();
value = enumType.FindValueByNumber(number);
if (value == null) {
throw tokenizer.CreateFormatExceptionPreviousToken(
"Enum type \"" + enumType.FullName +
"\" has no value with number " + number + ".");
}
} else {
String id = tokenizer.ConsumeIdentifier();
value = enumType.FindValueByName(id);
if (value == null) {
throw tokenizer.CreateFormatExceptionPreviousToken(
"Enum type \"" + enumType.FullName +
"\" has no value named \"" + id + "\".");
}
}
break;
}
case FieldType.Message:
case FieldType.Group:
throw new InvalidOperationException("Can't get here.");
}
}
if (field.IsRepeated) {
builder.WeakAddRepeatedField(field, value);
} else {
builder.SetField(field, value);
}
}
}
}
| |
/*
* 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.Collections.Generic;
using Directory = Lucene.Net.Store.Directory;
namespace Lucene.Net.Index
{
/// <summary><p>This class implements a {@link MergePolicy} that tries
/// to merge segments into levels of exponentially
/// increasing size, where each level has < mergeFactor
/// segments in it. Whenever a given levle has mergeFactor
/// segments or more in it, they will be merged.</p>
///
/// <p>This class is abstract and requires a subclass to
/// define the {@link #size} method which specifies how a
/// segment's size is determined. {@link LogDocMergePolicy}
/// is one subclass that measures size by document count in
/// the segment. {@link LogByteSizeMergePolicy} is another
/// subclass that measures size as the total byte size of the
/// file(s) for the segment.</p>
/// </summary>
public abstract class LogMergePolicy : MergePolicy
{
/// <summary>Defines the allowed range of log(size) for each
/// level. A level is computed by taking the max segment
/// log size, minuse LEVEL_LOG_SPAN, and finding all
/// segments falling within that range.
/// </summary>
public const double LEVEL_LOG_SPAN = 0.75;
/// <summary>Default merge factor, which is how many segments are
/// merged at a time
/// </summary>
public const int DEFAULT_MERGE_FACTOR = 10;
/// <summary>Default maximum segment size. A segment of this size</summary>
/// <seealso cref="setMaxMergeDocs">
/// </seealso>
public static readonly int DEFAULT_MAX_MERGE_DOCS = System.Int32.MaxValue;
private int mergeFactor = DEFAULT_MERGE_FACTOR;
internal long minMergeSize;
internal long maxMergeSize;
internal int maxMergeDocs = DEFAULT_MAX_MERGE_DOCS;
private bool useCompoundFile = true;
private bool useCompoundDocStore = true;
private IndexWriter writer;
private void Message(System.String message)
{
if (writer != null)
writer.Message("LMP: " + message);
}
/// <summary><p>Returns the number of segments that are merged at
/// once and also controls the total number of segments
/// allowed to accumulate in the index.</p>
/// </summary>
public virtual int GetMergeFactor()
{
return mergeFactor;
}
/// <summary>Determines how often segment indices are merged by
/// addDocument(). With smaller values, less RAM is used
/// while indexing, and searches on unoptimized indices are
/// faster, but indexing speed is slower. With larger
/// values, more RAM is used during indexing, and while
/// searches on unoptimized indices are slower, indexing is
/// faster. Thus larger values (> 10) are best for batch
/// index creation, and smaller values (< 10) for indices
/// that are interactively maintained.
/// </summary>
public virtual void SetMergeFactor(int mergeFactor)
{
if (mergeFactor < 2)
throw new System.ArgumentException("mergeFactor cannot be less than 2");
this.mergeFactor = mergeFactor;
}
// Javadoc inherited
public override bool UseCompoundFile(SegmentInfos infos, SegmentInfo info)
{
return useCompoundFile;
}
/// <summary>Sets whether compound file format should be used for
/// newly flushed and newly merged segments.
/// </summary>
public virtual void SetUseCompoundFile(bool useCompoundFile)
{
this.useCompoundFile = useCompoundFile;
}
/// <summary>Returns true if newly flushed and newly merge segments</summary>
/// <seealso cref="">
/// #setUseCompoundFile
/// </seealso>
public virtual bool GetUseCompoundFile()
{
return useCompoundFile;
}
// Javadoc inherited
public override bool UseCompoundDocStore(SegmentInfos infos)
{
return useCompoundDocStore;
}
/// <summary>Sets whether compound file format should be used for
/// newly flushed and newly merged doc store
/// segment files (term vectors and stored fields).
/// </summary>
public virtual void SetUseCompoundDocStore(bool useCompoundDocStore)
{
this.useCompoundDocStore = useCompoundDocStore;
}
/// <summary>Returns true if newly flushed and newly merge doc
/// store segment files (term vectors and stored fields)
/// </summary>
/// <seealso cref="">
/// #setUseCompoundDocStore
/// </seealso>
public virtual bool GetUseCompoundDocStore()
{
return useCompoundDocStore;
}
public override void Close()
{
}
abstract protected internal long Size(SegmentInfo info);
private bool IsOptimized(SegmentInfos infos, IndexWriter writer, int maxNumSegments, Dictionary<SegmentInfo,SegmentInfo> segmentsToOptimize)
{
int numSegments = infos.Count;
int numToOptimize = 0;
SegmentInfo optimizeInfo = null;
for (int i = 0; i < numSegments && numToOptimize <= maxNumSegments; i++)
{
SegmentInfo info = infos.Info(i);
if (segmentsToOptimize.ContainsKey(info))
{
numToOptimize++;
optimizeInfo = info;
}
}
return numToOptimize <= maxNumSegments && (numToOptimize != 1 || IsOptimized(writer, optimizeInfo));
}
/// <summary>Returns true if this single nfo is optimized (has no
/// pending norms or deletes, is in the same dir as the
/// writer, and matches the current compound file setting
/// </summary>
private bool IsOptimized(IndexWriter writer, SegmentInfo info)
{
return !info.HasDeletions() && !info.HasSeparateNorms() && info.dir == writer.GetDirectory() && info.GetUseCompoundFile() == useCompoundFile;
}
/// <summary>Returns the merges necessary to optimize the index.
/// This merge policy defines "optimized" to mean only one
/// segment in the index, where that segment has no
/// deletions pending nor separate norms, and it is in
/// compound file format if the current useCompoundFile
/// setting is true. This method returns multiple merges
/// (mergeFactor at a time) so the {@link MergeScheduler}
/// in use may make use of concurrency.
/// </summary>
public override MergeSpecification FindMergesForOptimize(SegmentInfos infos, IndexWriter writer, int maxNumSegments, Dictionary<SegmentInfo,SegmentInfo> segmentsToOptimize)
{
MergeSpecification spec;
System.Diagnostics.Debug.Assert(maxNumSegments > 0);
if (!IsOptimized(infos, writer, maxNumSegments, segmentsToOptimize))
{
// Find the newest (rightmost) segment that needs to
// be optimized (other segments may have been flushed
// since optimize started):
int last = infos.Count;
while (last > 0)
{
SegmentInfo info = infos.Info(--last);
if (segmentsToOptimize.ContainsKey(info))
{
last++;
break;
}
}
if (last > 0)
{
spec = new MergeSpecification();
// First, enroll all "full" merges (size
// mergeFactor) to potentially be run concurrently:
while (last - maxNumSegments + 1 >= mergeFactor)
{
spec.Add(new OneMerge(infos.Range(last - mergeFactor, last), useCompoundFile));
last -= mergeFactor;
}
// Only if there are no full merges pending do we
// add a final partial (< mergeFactor segments) merge:
if (0 == spec.merges.Count)
{
if (maxNumSegments == 1)
{
// Since we must optimize down to 1 segment, the
// choice is simple:
if (last > 1 || !IsOptimized(writer, infos.Info(0)))
spec.Add(new OneMerge(infos.Range(0, last), useCompoundFile));
}
else if (last > maxNumSegments)
{
// Take care to pick a partial merge that is
// least cost, but does not make the index too
// lopsided. If we always just picked the
// partial tail then we could produce a highly
// lopsided index over time:
// We must merge this many segments to leave
// maxNumSegments in the index (from when
// optimize was first kicked off):
int finalMergeSize = last - maxNumSegments + 1;
// Consider all possible starting points:
long bestSize = 0;
int bestStart = 0;
for (int i = 0; i < last - finalMergeSize + 1; i++)
{
long sumSize = 0;
for (int j = 0; j < finalMergeSize; j++)
sumSize += Size(infos.Info(j + i));
if (i == 0 || (sumSize < 2 * Size(infos.Info(i - 1)) && sumSize < bestSize))
{
bestStart = i;
bestSize = sumSize;
}
}
spec.Add(new OneMerge(infos.Range(bestStart, bestStart + finalMergeSize), useCompoundFile));
}
}
}
else
spec = null;
}
else
spec = null;
return spec;
}
/// <summary>
/// Finds merges necessary to expunge all deletes from the
/// index. We simply merge adjacent segments that have
/// deletes, up to mergeFactor at a time.
/// </summary>
public override MergeSpecification FindMergesToExpungeDeletes(SegmentInfos segmentInfos, IndexWriter writer)
{
this.writer = writer;
int numSegments = segmentInfos.Count;
Message("findMergesToExpungeDeletes: " + numSegments + " segments");
MergeSpecification spec = new MergeSpecification();
int firstSegmentWithDeletions = -1;
for (int i = 0; i < numSegments; i++)
{
SegmentInfo info = segmentInfos.Info(i);
if (info.HasDeletions())
{
Message(" segment " + info.name + " has deletions");
if (firstSegmentWithDeletions == -1)
firstSegmentWithDeletions = i;
else if (i - firstSegmentWithDeletions == mergeFactor)
{
// We've seen mergeFactor segments in a row with
// deletions, so force a merge now:
Message(" add merge " + firstSegmentWithDeletions + " to " + (i - 1) + " inclusive");
spec.Add(new OneMerge(segmentInfos.Range(firstSegmentWithDeletions, i), useCompoundFile));
firstSegmentWithDeletions = i;
}
}
else if (firstSegmentWithDeletions != -1)
{
// End of a sequence of segments with deletions, so,
// merge those past segments even if it's fewer than
// mergeFactor segments
Message(" add merge " + firstSegmentWithDeletions + " to " + (i - 1) + " inclusive");
spec.Add(new OneMerge(segmentInfos.Range(firstSegmentWithDeletions, i), useCompoundFile));
firstSegmentWithDeletions = -1;
}
}
if (firstSegmentWithDeletions != -1)
{
Message(" add merge " + firstSegmentWithDeletions + " to " + (numSegments - 1) + " inclusive");
spec.Add(new OneMerge(segmentInfos.Range(firstSegmentWithDeletions, numSegments), useCompoundFile));
}
return spec;
}
/// <summary>Checks if any merges are now necessary and returns a
/// {@link MergePolicy.MergeSpecification} if so. A merge
/// is necessary when there are more than {@link
/// #setMergeFactor} segments at a given level. When
/// multiple levels have too many segments, this method
/// will return multiple merges, allowing the {@link
/// MergeScheduler} to use concurrency.
/// </summary>
public override MergeSpecification FindMerges(SegmentInfos infos, IndexWriter writer)
{
int numSegments = infos.Count;
this.writer = writer;
Message("findMerges: " + numSegments + " segments");
// Compute levels, which is just log (base mergeFactor)
// of the size of each segment
float[] levels = new float[numSegments];
float norm = (float) System.Math.Log(mergeFactor);
Directory directory = writer.GetDirectory();
for (int i = 0; i < numSegments; i++)
{
SegmentInfo info = infos.Info(i);
long size = Size(info);
// Floor tiny segments
if (size < 1)
size = 1;
levels[i] = (float) System.Math.Log(size) / norm;
}
float levelFloor;
if (minMergeSize <= 0)
levelFloor = (float) 0.0;
else
{
levelFloor = (float) (System.Math.Log(minMergeSize) / norm);
}
// Now, we quantize the log values into levels. The
// first level is any segment whose log size is within
// LEVEL_LOG_SPAN of the max size, or, who has such as
// segment "to the right". Then, we find the max of all
// other segments and use that to define the next level
// segment, etc.
MergeSpecification spec = null;
int start = 0;
while (start < numSegments)
{
// Find max level of all segments not already
// quantized.
float maxLevel = levels[start];
for (int i = 1 + start; i < numSegments; i++)
{
float level = levels[i];
if (level > maxLevel)
maxLevel = level;
}
// Now search backwards for the rightmost segment that
// falls into this level:
float levelBottom;
if (maxLevel < levelFloor)
// All remaining segments fall into the min level
levelBottom = - 1.0F;
else
{
levelBottom = (float) (maxLevel - LEVEL_LOG_SPAN);
// Force a boundary at the level floor
if (levelBottom < levelFloor && maxLevel >= levelFloor)
levelBottom = levelFloor;
}
int upto = numSegments - 1;
while (upto >= start)
{
if (levels[upto] >= levelBottom)
{
break;
}
upto--;
}
Message(" level " + levelBottom + " to " + maxLevel + ": " + (1 + upto - start) + " segments");
// Finally, record all merges that are viable at this level:
int end = start + mergeFactor;
while (end <= 1 + upto)
{
bool anyTooLarge = false;
for (int i = start; i < end; i++)
{
SegmentInfo info = infos.Info(i);
anyTooLarge |= (Size(info) >= maxMergeSize || info.docCount >= maxMergeDocs);
}
if (!anyTooLarge)
{
if (spec == null)
spec = new MergeSpecification();
Message(" " + start + " to " + end + ": add this merge");
spec.Add(new OneMerge(infos.Range(start, end), useCompoundFile));
}
else
Message(" " + start + " to " + end + ": contains segment over maxMergeSize or maxMergeDocs; skipping");
start = end;
end = start + mergeFactor;
}
start = 1 + upto;
}
return spec;
}
/// <summary><p>Determines the largest segment (measured by
/// document count) that may be merged with other segments.
/// Small values (e.g., less than 10,000) are best for
/// interactive indexing, as this limits the length of
/// pauses while indexing to a few seconds. Larger values
/// are best for batched indexing and speedier
/// searches.</p>
///
/// <p>The default value is {@link Integer#MAX_VALUE}.</p>
///
/// <p>The default merge policy ({@link
/// LogByteSizeMergePolicy}) also allows you to set this
/// limit by net size (in MB) of the segment, using {@link
/// LogByteSizeMergePolicy#setMaxMergeMB}.</p>
/// </summary>
public virtual void SetMaxMergeDocs(int maxMergeDocs)
{
this.maxMergeDocs = maxMergeDocs;
}
/// <summary>Returns the largest segment (measured by document
/// count) that may be merged with other segments.
/// </summary>
/// <seealso cref="setMaxMergeDocs">
/// </seealso>
public virtual int GetMaxMergeDocs()
{
return maxMergeDocs;
}
}
}
| |
//------------------------------------------------------------------------------
// <copyright file="MobileErrorInfo.cs" company="Microsoft">
// Copyright (c) Microsoft Corporation. All rights reserved.
// </copyright>
//------------------------------------------------------------------------------
using System;
using System.CodeDom.Compiler;
using System.Collections;
using System.Collections.Specialized;
using System.Globalization;
using System.Text.RegularExpressions;
using System.Security.Permissions;
namespace System.Web.Mobile
{
/*
* Mobile Error Info
* Contains information about an error that occurs in a mobile application.
* This information can be used to format the error for the target device.
*
*
*/
[AspNetHostingPermission(SecurityAction.LinkDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[AspNetHostingPermission(SecurityAction.InheritanceDemand, Level=AspNetHostingPermissionLevel.Minimal)]
[Obsolete("The System.Web.Mobile.dll assembly has been deprecated and should no longer be used. For information about how to develop ASP.NET mobile applications, see http://go.microsoft.com/fwlink/?LinkId=157231.")]
public class MobileErrorInfo
{
/// <include file='doc\MobileErrorInfo.uex' path='docs/doc[@for="MobileErrorInfo.ContextKey"]/*' />
public static readonly String ContextKey = "MobileErrorInfo";
private static object _lockObject = new object();
private const String _errorType = "Type";
private const String _errorDescription = "Description";
private const String _errorMiscTitle = "MiscTitle";
private const String _errorMiscText = "MiscText";
private const String _errorFile = "File";
private const String _errorLineNumber = "LineNumber";
private static Regex[] _searchExpressions = null;
private static bool _searchExpressionsBuilt = false;
private const int _expressionCount = 3;
private StringDictionary _dictionary = new StringDictionary();
internal MobileErrorInfo(Exception e)
{
// Don't want any failure to escape here...
try
{
// For some reason, the compile exception lives in the
// InnerException.
HttpCompileException compileException =
e.InnerException as HttpCompileException;
if (compileException != null)
{
this.Type = SR.GetString(SR.MobileErrorInfo_CompilationErrorType);
this.Description = SR.GetString(SR.MobileErrorInfo_CompilationErrorDescription);
this.MiscTitle = SR.GetString(SR.MobileErrorInfo_CompilationErrorMiscTitle);
CompilerErrorCollection errors = compileException.Results.Errors;
if (errors != null && errors.Count >= 1)
{
CompilerError error = errors[0];
this.LineNumber = error.Line.ToString(CultureInfo.InvariantCulture);
this.File = error.FileName;
this.MiscText = error.ErrorNumber + ":" + error.ErrorText;
}
else
{
this.LineNumber = SR.GetString(SR.MobileErrorInfo_Unknown);
this.File = SR.GetString(SR.MobileErrorInfo_Unknown);
this.MiscText = SR.GetString(SR.MobileErrorInfo_Unknown);
}
return;
}
HttpParseException parseException = e as HttpParseException;
if (parseException != null)
{
this.Type = SR.GetString(SR.MobileErrorInfo_ParserErrorType);
this.Description = SR.GetString(SR.MobileErrorInfo_ParserErrorDescription);
this.MiscTitle = SR.GetString(SR.MobileErrorInfo_ParserErrorMiscTitle);
this.LineNumber = parseException.Line.ToString(CultureInfo.InvariantCulture);
this.File = parseException.FileName;
this.MiscText = parseException.Message;
return;
}
// We try to use the hacky way of parsing an HttpException of an
// unknown subclass.
HttpException httpException = e as HttpException;
if (httpException != null && ParseHttpException(httpException))
{
return;
}
}
catch
{
// Don't need to do anything here, just continue to base case
// below.
}
// Default to the most basic if none of the above succeed.
this.Type = e.GetType().FullName;
this.Description = e.Message;
this.MiscTitle = SR.GetString(SR.MobileErrorInfo_SourceObject);
String s = e.StackTrace;
if(s != null) {
int i = s.IndexOf('\r');
if (i != -1)
{
s = s.Substring(0, i);
}
this.MiscText = s;
}
}
/// <include file='doc\MobileErrorInfo.uex' path='docs/doc[@for="MobileErrorInfo.this"]/*' />
public String this[String key]
{
get
{
String s = _dictionary[key];
return (s == null) ? String.Empty : s;
}
set
{
_dictionary[key] = value;
}
}
/// <include file='doc\MobileErrorInfo.uex' path='docs/doc[@for="MobileErrorInfo.Type"]/*' />
public String Type
{
get
{
return this[_errorType];
}
set
{
this[_errorType] = value;
}
}
/// <include file='doc\MobileErrorInfo.uex' path='docs/doc[@for="MobileErrorInfo.Description"]/*' />
public String Description
{
get
{
return this[_errorDescription];
}
set
{
this[_errorDescription] = value;
}
}
/// <include file='doc\MobileErrorInfo.uex' path='docs/doc[@for="MobileErrorInfo.MiscTitle"]/*' />
public String MiscTitle
{
get
{
return this[_errorMiscTitle];
}
set
{
this[_errorMiscTitle] = value;
}
}
/// <include file='doc\MobileErrorInfo.uex' path='docs/doc[@for="MobileErrorInfo.MiscText"]/*' />
public String MiscText
{
get
{
return this[_errorMiscText];
}
set
{
this[_errorMiscText] = value;
}
}
/// <include file='doc\MobileErrorInfo.uex' path='docs/doc[@for="MobileErrorInfo.File"]/*' />
public String File
{
get
{
return this[_errorFile];
}
set
{
this[_errorFile] = value;
}
}
/// <include file='doc\MobileErrorInfo.uex' path='docs/doc[@for="MobileErrorInfo.LineNumber"]/*' />
public String LineNumber
{
get
{
return this[_errorLineNumber];
}
set
{
this[_errorLineNumber] = value;
}
}
// Return true if we succeed
private bool ParseHttpException(HttpException e)
{
int i;
Match match = null;
String errorMessage = e.GetHtmlErrorMessage();
if (errorMessage == null)
{
return false;
}
// Use regular expressions to scrape the message output
// for meaningful data. One problem: Some parts of the
// output are optional, and any regular expression that
// uses the ()? syntax doesn't pick it up. So, we have
// to have all the different combinations of expressions,
// and use each one in order.
EnsureSearchExpressions();
for (i = 0; i < _expressionCount; i++)
{
match = _searchExpressions[i].Match(errorMessage);
if (match.Success)
{
break;
}
}
if (i == _expressionCount)
{
return false;
}
this.Type = TrimAndClean(match.Result("${title}"));
this.Description = TrimAndClean(match.Result("${description}"));
if (i <= 1)
{
// These expressions were able to match the miscellaneous
// title/text section.
this.MiscTitle = TrimAndClean(match.Result("${misctitle}"));
this.MiscText = TrimAndClean(match.Result("${misctext}"));
}
if (i == 0)
{
// This expression was able to match the file/line #
// section.
this.File = TrimAndClean(match.Result("${file}"));
this.LineNumber = TrimAndClean(match.Result("${linenumber}"));
}
return true;
}
private static void EnsureSearchExpressions()
{
// Create precompiled search expressions. They're here
// rather than in static variables, so that we can load
// them from resources on demand. But once they're loaded,
// they're compiled and always available.
if (!_searchExpressionsBuilt)
{
lock(_lockObject)
{
if (!_searchExpressionsBuilt)
{
//
// Why three similar expressions? See ParseHttpException above.
_searchExpressions = new Regex[_expressionCount];
_searchExpressions[0] = new Regex(
"<title>(?'title'.*?)</title>.*?" +
": </b>(?'description'.*?)<br>.*?" +
"(<b>(?'misctitle'.*?): </b>(?'misctext'.*?)<br)+.*?" +
"(Source File:</b>(?'file'.*?) <b>Line:</b>(?'linenumber'.*?)<br)+",
RegexOptions.Singleline |
RegexOptions.IgnoreCase |
RegexOptions.CultureInvariant |
RegexOptions.Compiled);
_searchExpressions[1] = new Regex(
"<title>(?'title'.*?)</title>.*?" +
": </b>(?'description'.*?)<br>.*?" +
"(<b>(?'misctitle'.*?): </b>(?'misctext'.*?)<br)+.*?",
RegexOptions.Singleline |
RegexOptions.IgnoreCase |
RegexOptions.CultureInvariant |
RegexOptions.Compiled);
_searchExpressions[2] = new Regex(
"<title>(?'title'.*?)</title>.*?: </b>(?'description'.*?)<br>",
RegexOptions.Singleline |
RegexOptions.IgnoreCase |
RegexOptions.CultureInvariant |
RegexOptions.Compiled);
_searchExpressionsBuilt = true;
}
}
}
}
private static String TrimAndClean(String s)
{
return s.Replace("\r\n", " ").Trim();
}
}
}
| |
/*
* Copyright (C) 2009 JavaRosa ,Copyright (C) 2014 Simbacode
*
* 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 Constants = org.javarosa.core.model.Constants;
using EvaluationContext = org.javarosa.core.model.condition.EvaluationContext;
using DateData = org.javarosa.core.model.data.DateData;
using DateTimeData = org.javarosa.core.model.data.DateTimeData;
using DecimalData = org.javarosa.core.model.data.DecimalData;
using IAnswerData = org.javarosa.core.model.data.IAnswerData;
using IntegerData = org.javarosa.core.model.data.IntegerData;
using LongData = org.javarosa.core.model.data.LongData;
using SelectMultiData = org.javarosa.core.model.data.SelectMultiData;
using StringData = org.javarosa.core.model.data.StringData;
using TimeData = org.javarosa.core.model.data.TimeData;
using FormInstance = org.javarosa.core.model.instance.FormInstance;
using TreeElement = org.javarosa.core.model.instance.TreeElement;
using TreeReference = org.javarosa.core.model.instance.TreeReference;
//UPGRADE_TODO: The type 'org.javarosa.core.services.storage.IStorageIterator' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
using IStorageIterator = org.javarosa.core.services.storage.IStorageIterator;
//UPGRADE_TODO: The type 'org.javarosa.core.services.storage.IStorageUtility' could not be found. If it was not included in the conversion, there may be compiler issues. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1262'"
using IStorageUtility = org.javarosa.core.services.storage.IStorageUtility;
using Persistable = org.javarosa.core.services.storage.Persistable;
using ByteArrayPayload = org.javarosa.core.services.transport.payload.ByteArrayPayload;
using Externalizable = org.javarosa.core.util.externalizable.Externalizable;
using PrototypeFactory = org.javarosa.core.util.externalizable.PrototypeFactory;
using System.Collections.Generic;
using System.Collections;
namespace org.javarosa.core.model.util.restorable
{
public class RestoreUtils
{
public const System.String RECORD_ID_TAG = "rec-id";
public static IXFormyFactory xfFact;
public static TreeReference ref_Renamed(System.String refStr)
{
return xfFact.ref_Renamed(refStr);
}
public static TreeReference absRef(System.String refStr, FormInstance dm)
{
TreeReference ref_ = ref_Renamed(refStr);
if (!ref_.isAbsolute())
{
ref_ = ref_.parent(topRef(dm));
}
return ref_;
}
public static TreeReference topRef(FormInstance dm)
{
return ref_Renamed("/" + dm.getRoot().getName());
}
public static TreeReference childRef(System.String childPath, TreeReference parentRef)
{
return ref_Renamed(childPath).parent(parentRef);
}
private static FormInstance newDataModel(System.String topTag)
{
FormInstance dm = new FormInstance();
dm.addNode(ref_Renamed("/" + topTag));
return dm;
}
public static FormInstance createDataModel(Restorable r)
{
FormInstance dm = newDataModel(r.RestorableType);
if (r is Persistable)
{
addData(dm, RECORD_ID_TAG, (System.Object)((Persistable)r).ID);
}
return dm;
}
public static FormInstance createRootDataModel(Restorable r)
{
FormInstance inst = createDataModel(r);
inst.schema = "http://openrosa.org/backup";
addData(inst, "timestamp", System.DateTime.Now, Constants.DATATYPE_DATE_TIME);
return inst;
}
public static void addData(FormInstance dm, System.String xpath, System.Object data)
{
addData(dm, xpath, data, getDataType(data));
}
public static void addData(FormInstance dm, System.String xpath, System.Object data, int dataType)
{
if (data == null)
{
dataType = -1;
}
IAnswerData val;
switch (dataType)
{
case -1: val = null; break;
case Constants.DATATYPE_TEXT: val = new StringData((System.String)data); break;
case Constants.DATATYPE_INTEGER: //UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
val = new IntegerData(ref new System.Int32[] { (System.Int32)data }[0]); break;
case Constants.DATATYPE_LONG: //UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
val = new LongData(ref new System.Int64[] { (System.Int64)data }[0]); break;
case Constants.DATATYPE_DECIMAL: //UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
val = new DecimalData(ref new System.Double[] { (System.Double)data }[0]); break;
case Constants.DATATYPE_BOOLEAN: val = new StringData(((System.Boolean)data) ? "t" : "f"); break;
case Constants.DATATYPE_DATE: //UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
val = new DateData(ref new System.DateTime[] { (System.DateTime)data }[0]); break;
case Constants.DATATYPE_DATE_TIME: //UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
val = new DateTimeData(ref new System.DateTime[] { (System.DateTime)data }[0]); break;
case Constants.DATATYPE_TIME: //UPGRADE_NOTE: ref keyword was added to struct-type parameters. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1303'"
val = new TimeData(ref new System.DateTime[] { (System.DateTime)data }[0]); break;
case Constants.DATATYPE_CHOICE_LIST: val = (SelectMultiData)data; break;
default: throw new System.ArgumentException("Don't know how to handle data type [" + dataType + "]");
}
TreeReference ref_Renamed = absRef(xpath, dm);
if (dm.addNode(ref_Renamed, val, dataType) == null)
{
throw new System.SystemException("error setting value during object backup [" + xpath + "]");
}
}
//used for outgoing data
public static int getDataType(System.Object o)
{
int dataType = -1;
if (o is System.String)
{
dataType = Constants.DATATYPE_TEXT;
}
else if (o is System.Int32)
{
dataType = Constants.DATATYPE_INTEGER;
}
else if (o is System.Int64)
{
dataType = Constants.DATATYPE_LONG;
}
else if (o is System.Single || o is System.Double)
{
dataType = Constants.DATATYPE_DECIMAL;
}
else if (o is System.DateTime)
{
dataType = Constants.DATATYPE_DATE;
}
else if (o is System.Boolean)
{
dataType = Constants.DATATYPE_BOOLEAN; //booleans are serialized as a literal 't'/'f'
}
else if (o is SelectMultiData)
{
dataType = Constants.DATATYPE_CHOICE_LIST;
}
return dataType;
}
//used for incoming data
public static int getDataType(System.Type c)
{
int dataType;
if (c == typeof(System.String))
{
dataType = Constants.DATATYPE_TEXT;
}
else if (c == typeof(System.Int32))
{
dataType = Constants.DATATYPE_INTEGER;
}
else if (c == typeof(System.Int64))
{
dataType = Constants.DATATYPE_LONG;
}
else if (c == typeof(System.Single) || c == typeof(System.Double))
{
dataType = Constants.DATATYPE_DECIMAL;
}
else if (c == typeof(System.DateTime))
{
dataType = Constants.DATATYPE_DATE;
//Clayton Sims - Jun 16, 2009 - How are we handling Date v. Time v. DateTime?
}
else if (c == typeof(System.Boolean))
{
dataType = Constants.DATATYPE_TEXT; //booleans are serialized as a literal 't'/'f'
}
else
{
//UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Class.getName' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
throw new System.SystemException("Can't handle data type " + c.FullName);
}
return dataType;
}
public static System.Object getValue(System.String xpath, FormInstance tree)
{
return getValue(xpath, topRef(tree), tree);
}
public static System.Object getValue(System.String xpath, TreeReference context, FormInstance tree)
{
TreeElement node = tree.resolveReference(ref_Renamed(xpath).contextualize(context));
if (node == null)
{
throw new System.SystemException("Could not find node [" + xpath + "] when parsing saved instance!");
}
if (node.isRelevant())
{
IAnswerData val = node.getValue();
return (val == null ? null : val.Value);
}
else
{
return null;
}
}
public static void applyDataType(FormInstance dm, System.String path, TreeReference parent, System.Type type)
{
applyDataType(dm, path, parent, getDataType(type));
}
public static void applyDataType(FormInstance dm, System.String path, TreeReference parent, int dataType)
{
TreeReference ref_ = childRef(path, parent);
List<TreeReference> v = dm.expandReference(ref_);
for (int i = 0; i < v.Count; i++)
{
TreeElement e = dm.resolveReference((TreeReference)v[i]);
e.dataType = dataType;
}
}
public static void templateChild(FormInstance dm, System.String prefixPath, TreeReference parent, Restorable r)
{
TreeReference childRef = (prefixPath == null ? parent : RestoreUtils.childRef(prefixPath, parent));
childRef = org.javarosa.core.model.util.restorable.RestoreUtils.childRef(r.RestorableType, childRef);
templateData(r, dm, childRef);
}
public static void templateData(Restorable r, FormInstance dm, TreeReference parent)
{
if (parent == null)
{
parent = topRef(dm);
applyDataType(dm, "timestamp", parent, typeof(System.DateTime));
}
if (r is Persistable)
{
applyDataType(dm, RECORD_ID_TAG, parent, typeof(System.Int32));
}
r.templateData(dm, parent);
}
public static void mergeDataModel(FormInstance parent, FormInstance child, System.String xpathParent)
{
mergeDataModel(parent, child, absRef(xpathParent, parent));
}
public static void mergeDataModel(FormInstance parent, FormInstance child, TreeReference parentRef)
{
TreeElement parentNode = parent.resolveReference(parentRef);
//ugly
if (parentNode == null)
{
parentRef = parent.addNode(parentRef);
parentNode = parent.resolveReference(parentRef);
}
TreeElement childNode = child.getRoot();
int mult = parentNode.getChildMultiplicity(childNode.getName());
childNode.setMult(mult);
parentNode.addChild(childNode);
}
public static FormInstance exportRMS(IStorageUtility storage, System.Type type, System.String parentTag, IRecordFilter filter)
{
if (!typeof(Externalizable).IsAssignableFrom(type) || !typeof(Restorable).IsAssignableFrom(type))
{
return null;
}
FormInstance dm = newDataModel(parentTag);
IStorageIterator ri = storage.iterate();
while (ri.hasMore())
{
System.Object obj = ri.nextRecord();
if (filter == null || filter.filter(obj))
{
FormInstance objModel = ((Restorable)obj).exportData();
mergeDataModel(dm, objModel, topRef(dm));
}
}
return dm;
}
public static FormInstance subDataModel(TreeElement top)
{
TreeElement newTop = top.shallowCopy();
newTop.setMult(0);
return new FormInstance(newTop);
}
public static void exportRMS(FormInstance parent, System.Type type, System.String grouperName, IStorageUtility storage, IRecordFilter filter)
{
FormInstance entities = RestoreUtils.exportRMS(storage, type, grouperName, filter);
RestoreUtils.mergeDataModel(parent, entities, ".");
}
public static void importRMS(FormInstance dm, IStorageUtility storage, System.Type type, System.String path)
{
if (!typeof(Externalizable).IsAssignableFrom(type) || !typeof(Restorable).IsAssignableFrom(type))
{
return;
}
bool idMatters = typeof(Persistable).IsAssignableFrom(type);
System.String childName = ((Restorable)PrototypeFactory.getInstance(type)).RestorableType;
TreeElement e = dm.resolveReference(absRef(path, dm));
List<TreeElement> children = e.getChildrenWithName(childName);
for (int i = 0; i < children.Count; i++)
{
FormInstance child = subDataModel((TreeElement)children[i]);
Restorable inst = (Restorable)PrototypeFactory.getInstance(type);
//restore record id first so 'importData' has access to it
int recID = -1;
if (idMatters)
{
recID = ((System.Int32)getValue(RECORD_ID_TAG, child));
((Persistable)inst).ID = recID;
}
inst.importData(child);
try
{
if (idMatters)
{
storage.write((Persistable)inst);
}
else
{
storage.add((Externalizable)inst);
}
}
catch (System.Exception ex)
{
//UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Class.getName' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
//UPGRADE_TODO: The equivalent in .NET for method 'java.lang.Throwable.getMessage' may return a different value. "ms-help://MS.VSCC.v80/dv_commoner/local/redirect.htm?index='!DefaultContextWindowIndex'&keyword='jlca1043'"
throw new System.SystemException("Error importing RMS during restore! [" + type.FullName + ":" + recID + "]; " + ex.Message);
}
}
}
public static ByteArrayPayload dispatch(FormInstance dm)
{
return (ByteArrayPayload)xfFact.serializeInstance(dm);
}
public static FormInstance receive(byte[] payload, System.Type restorableType)
{
return xfFact.parseRestore(payload, restorableType);
}
public static bool getBoolean(System.Object o)
{
if (o is System.String)
{
System.String bool_Renamed = (System.String)o;
if ("t".Equals(bool_Renamed))
{
return true;
}
else if ("f".Equals(bool_Renamed))
{
return false;
}
else
{
throw new System.SystemException("boolean string must be t or f");
}
}
else
{
throw new System.SystemException("booleans are encoded as strings");
}
}
}
}
| |
using System;
using System.Linq;
using ColossalFramework;
using ColossalFramework.UI;
using TrafficManager.Traffic;
using TrafficManager.TrafficLight;
using UnityEngine;
namespace TrafficManager.UI
{
public class UITrafficManager : UIPanel
{
private static UIState _uiState = UIState.None;
private static bool _inited;
public static UIState UIState
{
set
{
if (value == UIState.None && _inited)
{
_buttonSwitchTraffic.focusedBgSprite = "ButtonMenu";
_buttonPrioritySigns.focusedBgSprite = "ButtonMenu";
_buttonManualControl.focusedBgSprite = "ButtonMenu";
_buttonTimedMain.focusedBgSprite = "ButtonMenu";
//buttonLaneRestrictions.focusedBgSprite = "ButtonMenu";
_buttonCrosswalk.focusedBgSprite = "ButtonMenu";
_buttonClearTraffic.focusedBgSprite = "ButtonMenu";
if (LoadingExtension.IsPathManagerCompatibile)
{
_buttonLaneChange.focusedBgSprite = "ButtonMenu";
_buttonToggleDespawn.focusedBgSprite = "ButtonMenu";
}
}
_uiState = value;
}
get { return _uiState; }
}
private static UIButton _buttonSwitchTraffic;
private static UIButton _buttonPrioritySigns;
private static UIButton _buttonManualControl;
private static UIButton _buttonTimedMain;
private static UIButton _buttonLaneChange;
private static UIButton _buttonLaneRestrictions;
private static UIButton _buttonCrosswalk;
private static UIButton _buttonClearTraffic;
private static UIButton _buttonToggleDespawn;
public static TrafficLightTool TrafficLightTool;
public override void Start()
{
_inited = true;
TrafficLightTool = LoadingExtension.Instance.TrafficLightTool;
backgroundSprite = "GenericPanel";
color = new Color32(75, 75, 135, 255);
width = 250;
height = LoadingExtension.IsPathManagerCompatibile ? 350 : 270;
relativePosition = new Vector3(10.48f, 80f);
UILabel title = AddUIComponent<UILabel>();
title.text = "Traffic Manager";
title.relativePosition = new Vector3(65.0f, 5.0f);
if (LoadingExtension.IsPathManagerCompatibile)
{
_buttonSwitchTraffic = _createButton("Switch traffic lights", new Vector3(35f, 30f), clickSwitchTraffic);
_buttonPrioritySigns = _createButton("Add priority signs", new Vector3(35f, 70f), clickAddPrioritySigns);
_buttonManualControl = _createButton("Manual traffic lights", new Vector3(35f, 110f), clickManualControl);
_buttonTimedMain = _createButton("Timed traffic lights", new Vector3(35f, 150f), clickTimedAdd);
_buttonLaneChange = _createButton("Change lanes", new Vector3(35f, 190f), clickChangeLanes);
//buttonLaneRestrictions = _createButton("Road Restrictions", new Vector3(35f, 230f), clickLaneRestrictions);
_buttonCrosswalk = _createButton("Add/Remove Crosswalk", new Vector3(35f, 230f), clickCrosswalk);
_buttonClearTraffic = _createButton("Clear Traffic", new Vector3(35f, 270f), clickClearTraffic);
_buttonToggleDespawn = _createButton(LoadingExtension.Instance.DespawnEnabled ? "Disable despawning" : "Enable despawning", new Vector3(35f, 310f), ClickToggleDespawn);
}
else
{
_buttonSwitchTraffic = _createButton("Switch traffic lights", new Vector3(35f, 30f), clickSwitchTraffic);
_buttonPrioritySigns = _createButton("Add priority signs", new Vector3(35f, 70f), clickAddPrioritySigns);
_buttonManualControl = _createButton("Manual traffic lights", new Vector3(35f, 110f), clickManualControl);
_buttonTimedMain = _createButton("Timed traffic lights", new Vector3(35f, 150f), clickTimedAdd);
_buttonCrosswalk = _createButton("Add/Remove Crosswalk", new Vector3(35f, 190f), clickCrosswalk);
_buttonClearTraffic = _createButton("Clear Traffic", new Vector3(35f, 230f), clickClearTraffic);
}
}
private UIButton _createButton(string text, Vector3 pos, MouseEventHandler eventClick)
{
var button = AddUIComponent<UIButton>();
button.width = 190;
button.height = 30;
button.normalBgSprite = "ButtonMenu";
button.disabledBgSprite = "ButtonMenuDisabled";
button.hoveredBgSprite = "ButtonMenuHovered";
button.focusedBgSprite = "ButtonMenu";
button.pressedBgSprite = "ButtonMenuPressed";
button.textColor = new Color32(255, 255, 255, 255);
button.playAudioEvents = true;
button.text = text;
button.relativePosition = pos;
button.eventClick += eventClick;
return button;
}
private void clickSwitchTraffic(UIComponent component, UIMouseEventParameter eventParam)
{
if (_uiState != UIState.SwitchTrafficLight)
{
_uiState = UIState.SwitchTrafficLight;
_buttonSwitchTraffic.focusedBgSprite = "ButtonMenuFocused";
TrafficLightTool.SetToolMode(ToolMode.SwitchTrafficLight);
}
else
{
_uiState = UIState.None;
_buttonSwitchTraffic.focusedBgSprite = "ButtonMenu";
TrafficLightTool.SetToolMode(ToolMode.None);
}
}
private void clickAddPrioritySigns(UIComponent component, UIMouseEventParameter eventParam)
{
Log.Message("Priority Sign Clicked.");
if (_uiState != UIState.AddStopSign)
{
_uiState = UIState.AddStopSign;
_buttonPrioritySigns.focusedBgSprite = "ButtonMenuFocused";
TrafficLightTool.SetToolMode(ToolMode.AddPrioritySigns);
}
else
{
_uiState = UIState.None;
_buttonPrioritySigns.focusedBgSprite = "ButtonMenu";
TrafficLightTool.SetToolMode(ToolMode.None);
}
}
private void clickManualControl(UIComponent component, UIMouseEventParameter eventParam)
{
if (_uiState != UIState.ManualSwitch)
{
_uiState = UIState.ManualSwitch;
_buttonManualControl.focusedBgSprite = "ButtonMenuFocused";
TrafficLightTool.SetToolMode(ToolMode.ManualSwitch);
}
else
{
_uiState = UIState.None;
_buttonManualControl.focusedBgSprite = "ButtonMenu";
TrafficLightTool.SetToolMode(ToolMode.None);
}
}
private void clickTimedAdd(UIComponent component, UIMouseEventParameter eventParam)
{
if (_uiState != UIState.TimedControlNodes)
{
_uiState = UIState.TimedControlNodes;
_buttonTimedMain.focusedBgSprite = "ButtonMenuFocused";
TrafficLightTool.SetToolMode(ToolMode.TimedLightsSelectNode);
}
else
{
_uiState = UIState.None;
_buttonTimedMain.focusedBgSprite = "ButtonMenu";
TrafficLightTool.SetToolMode(ToolMode.None);
}
}
private void clickClearTraffic(UIComponent component, UIMouseEventParameter eventParam)
{
var vehicleList = TrafficPriority.VehicleList.Keys.ToList();
lock (Singleton<VehicleManager>.instance)
{
foreach (var vehicle in
from vehicle in vehicleList
let vehicleData = Singleton<VehicleManager>.instance.m_vehicles.m_buffer[vehicle]
where vehicleData.Info.m_vehicleType == VehicleInfo.VehicleType.Car
select vehicle)
{
Singleton<VehicleManager>.instance.ReleaseVehicle(vehicle);
}
}
}
private static void ClickToggleDespawn(UIComponent component, UIMouseEventParameter eventParam)
{
LoadingExtension.Instance.DespawnEnabled = !LoadingExtension.Instance.DespawnEnabled;
if (LoadingExtension.IsPathManagerCompatibile)
{
_buttonToggleDespawn.text = LoadingExtension.Instance.DespawnEnabled
? "Disable despawning"
: "Enable despawning";
}
}
private void clickChangeLanes(UIComponent component, UIMouseEventParameter eventParam)
{
if (_uiState != UIState.LaneChange)
{
_uiState = UIState.LaneChange;
if (LoadingExtension.IsPathManagerCompatibile)
{
_buttonLaneChange.focusedBgSprite = "ButtonMenuFocused";
}
TrafficLightTool.SetToolMode(ToolMode.LaneChange);
}
else
{
_uiState = UIState.None;
if (LoadingExtension.IsPathManagerCompatibile)
{
_buttonLaneChange.focusedBgSprite = "ButtonMenu";
}
TrafficLightTool.SetToolMode(ToolMode.None);
}
}
protected virtual void ClickLaneRestrictions(UIComponent component, UIMouseEventParameter eventParam)
{
if (_uiState != UIState.LaneRestrictions)
{
_uiState = UIState.LaneRestrictions;
_buttonLaneRestrictions.focusedBgSprite = "ButtonMenuFocused";
TrafficLightTool.SetToolMode(ToolMode.LaneRestrictions);
}
else
{
_uiState = UIState.None;
_buttonLaneRestrictions.focusedBgSprite = "ButtonMenu";
TrafficLightTool.SetToolMode(ToolMode.None);
}
}
private void clickCrosswalk(UIComponent component, UIMouseEventParameter eventParam)
{
if (_uiState != UIState.Crosswalk)
{
_uiState = UIState.Crosswalk;
_buttonCrosswalk.focusedBgSprite = "ButtonMenuFocused";
TrafficLightTool.SetToolMode(ToolMode.Crosswalk);
}
else
{
_uiState = UIState.None;
_buttonCrosswalk.focusedBgSprite = "ButtonMenu";
TrafficLightTool.SetToolMode(ToolMode.None);
}
}
public override void Update()
{
switch (_uiState)
{
case UIState.None: _basePanel(); break;
case UIState.SwitchTrafficLight: _switchTrafficPanel(); break;
case UIState.AddStopSign: _addStopSignPanel(); break;
case UIState.ManualSwitch: _manualSwitchPanel(); break;
case UIState.TimedControlNodes: _timedControlNodesPanel(); break;
case UIState.TimedControlLights: _timedControlLightsPanel(); break;
case UIState.LaneChange: _laneChangePanel(); break;
case UIState.Crosswalk: _crosswalkPanel(); break;
}
}
private void _basePanel()
{
}
private void _switchTrafficPanel()
{
}
private void _addStopSignPanel()
{
}
private void _manualSwitchPanel()
{
}
private void _timedControlNodesPanel()
{
}
private void _timedControlLightsPanel()
{
}
private void _laneChangePanel()
{
if (TrafficLightTool.SelectedSegment == 0) return;
var instance = Singleton<NetManager>.instance;
var segment = instance.m_segments.m_buffer[TrafficLightTool.SelectedSegment];
var info = segment.Info;
var num2 = segment.m_lanes;
var num3 = 0;
var dir = NetInfo.Direction.Forward;
if (segment.m_startNode == TrafficLightTool.SelectedNode)
dir = NetInfo.Direction.Backward;
var dir3 = ((segment.m_flags & NetSegment.Flags.Invert) == NetSegment.Flags.None) ? dir : NetInfo.InvertDirection(dir);
while (num3 < info.m_lanes.Length && num2 != 0u)
{
if (info.m_lanes[num3].m_laneType != NetInfo.LaneType.Pedestrian && info.m_lanes[num3].m_direction == dir3)
{
//segmentLights[num3].Show();
//segmentLights[num3].relativePosition = new Vector3(35f, (float)(xPos + (offsetIdx * 40f)));
//segmentLights[num3].text = ((NetLane.Flags)instance.m_lanes.m_buffer[num2].m_flags & ~NetLane.Flags.Created).ToString();
//if (segmentLights[num3].containsMouse)
//{
// if (Input.GetMouseButton(0) && !segmentMouseDown)
// {
// switchLane(num2);
// segmentMouseDown = true;
// if (
// !TrafficPriority.isPrioritySegment(TrafficLightTool.SelectedNode,
// TrafficLightTool.SelectedSegment))
// {
// TrafficPriority.addPrioritySegment(TrafficLightTool.SelectedNode, TrafficLightTool.SelectedSegment, PrioritySegment.PriorityType.None);
// }
// }
//}
}
num2 = instance.m_lanes.m_buffer[(int)((UIntPtr)num2)].m_nextLane;
num3++;
}
}
public void SwitchLane(uint laneId)
{
var flags = (NetLane.Flags)Singleton<NetManager>.instance.m_lanes.m_buffer[laneId].m_flags;
if ((flags & NetLane.Flags.LeftForwardRight) == NetLane.Flags.LeftForwardRight)
{
Singleton<NetManager>.instance.m_lanes.m_buffer[laneId].m_flags =
(ushort) ((flags & ~NetLane.Flags.LeftForwardRight) | NetLane.Flags.Forward);
}
else if ((flags & NetLane.Flags.ForwardRight) == NetLane.Flags.ForwardRight)
{
Singleton<NetManager>.instance.m_lanes.m_buffer[laneId].m_flags =
(ushort) ((flags & ~NetLane.Flags.ForwardRight) | NetLane.Flags.LeftForwardRight);
}
else if ((flags & NetLane.Flags.LeftRight) == NetLane.Flags.LeftRight)
{
Singleton<NetManager>.instance.m_lanes.m_buffer[laneId].m_flags =
(ushort) ((flags & ~NetLane.Flags.LeftRight) | NetLane.Flags.ForwardRight);
}
else if ((flags & NetLane.Flags.LeftForward) == NetLane.Flags.LeftForward)
{
Singleton<NetManager>.instance.m_lanes.m_buffer[laneId].m_flags =
(ushort) ((flags & ~NetLane.Flags.LeftForward) | NetLane.Flags.LeftRight);
}
else if ((flags & NetLane.Flags.Right) == NetLane.Flags.Right)
{
Singleton<NetManager>.instance.m_lanes.m_buffer[laneId].m_flags =
(ushort) ((flags & ~NetLane.Flags.Right) | NetLane.Flags.LeftForward);
}
else if ((flags & NetLane.Flags.Left) == NetLane.Flags.Left)
{
Singleton<NetManager>.instance.m_lanes.m_buffer[laneId].m_flags =
(ushort) ((flags & ~NetLane.Flags.Left) | NetLane.Flags.Right);
}
else if ((flags & NetLane.Flags.Forward) == NetLane.Flags.Forward)
{
Singleton<NetManager>.instance.m_lanes.m_buffer[laneId].m_flags =
(ushort) ((flags & ~NetLane.Flags.Forward) | NetLane.Flags.Left);
}
}
private void _crosswalkPanel()
{
}
}
}
| |
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
using System.Linq;
using System.Reflection;
namespace AngularWebApi.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. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
//-----------------------------------------------------------------------
// </copyright>
// <summary>Tests for the ProjectProjectExtensions class.</summary>
//-----------------------------------------------------------------------
using System;
using System.IO;
using System.Xml;
using Microsoft.Build.Construction;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using InvalidProjectFileException = Microsoft.Build.Exceptions.InvalidProjectFileException;
namespace Microsoft.Build.UnitTests.OM.Construction
{
/// <summary>
// <summary>Tests for the ProjectExtensionsElement class.</summary>
/// Tests for the class
/// </summary>
[TestClass]
public class ProjectExtensionsElement_Tests
{
/// <summary>
/// Read ProjectExtensions with some child
/// </summary>
[TestMethod]
public void Read()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ProjectExtensions>
<a/>
</ProjectExtensions>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children);
Assert.AreEqual(@"<a xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" />", extensions.Content);
}
/// <summary>
/// Read ProjectExtensions with invalid Condition attribute
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidCondition()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ProjectExtensions Condition='c'/>
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Read project with more than one ProjectExtensions
/// </summary>
[TestMethod]
[ExpectedException(typeof(InvalidProjectFileException))]
public void ReadInvalidDuplicate()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ProjectExtensions/>
<Target Name='t'/>
<ProjectExtensions />
</Project>
";
ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
}
/// <summary>
/// Set valid content
/// </summary>
[TestMethod]
public void SetValid()
{
ProjectExtensionsElement extensions = GetEmptyProjectExtensions();
Helpers.ClearDirtyFlag(extensions.ContainingProject);
extensions.Content = "a<b/>c";
Assert.AreEqual(@"a<b xmlns=""http://schemas.microsoft.com/developer/msbuild/2003"" />c", extensions.Content);
Assert.AreEqual(true, extensions.ContainingProject.HasUnsavedChanges);
}
/// <summary>
/// Set null content
/// </summary>
[TestMethod]
[ExpectedException(typeof(ArgumentNullException))]
public void SetInvalidNull()
{
ProjectExtensionsElement extensions = GetEmptyProjectExtensions();
extensions.Content = null;
}
/// <summary>
/// Delete by ID
/// </summary>
[TestMethod]
public void DeleteById()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ProjectExtensions>
<a>x</a>
<b>y</b>
</ProjectExtensions>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children);
extensions["a"] = String.Empty;
content = extensions["a"];
Assert.AreEqual(String.Empty, content);
extensions["a"] = String.Empty; // make sure it doesn't die or something
Assert.AreEqual("y", extensions["b"]);
}
/// <summary>
/// Get by ID
/// </summary>
[TestMethod]
public void GetById()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ProjectExtensions>
<a>x</a>
<b>y</b>
</ProjectExtensions>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children);
content = extensions["b"];
Assert.AreEqual("y", content);
content = extensions["nonexistent"];
Assert.AreEqual(String.Empty, content);
}
/// <summary>
/// Set by ID on not existing ID
/// </summary>
[TestMethod]
public void SetById()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ProjectExtensions>
<a>x</a>
<b>y</b>
</ProjectExtensions>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children);
extensions["c"] = "z";
Assert.AreEqual("z", extensions["c"]);
}
/// <summary>
/// Set by ID on existing ID
/// </summary>
[TestMethod]
public void SetByIdWhereItAlreadyExists()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ProjectExtensions>
<a>x</a>
<b>y</b>
</ProjectExtensions>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children);
extensions["b"] = "y2";
Assert.AreEqual("y2", extensions["b"]);
}
/// <summary>
/// Helper to get an empty ProjectExtensionsElement object
/// </summary>
private static ProjectExtensionsElement GetEmptyProjectExtensions()
{
string content = @"
<Project xmlns='http://schemas.microsoft.com/developer/msbuild/2003'>
<ProjectExtensions/>
</Project>
";
ProjectRootElement project = ProjectRootElement.Create(XmlReader.Create(new StringReader(content)));
ProjectExtensionsElement extensions = (ProjectExtensionsElement)Helpers.GetFirst(project.Children);
return extensions;
}
}
}
| |
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
namespace Microsoft.NohauLPC3180
{
using System;
using RT = Microsoft.Zelig.Runtime;
using TS = Microsoft.Zelig.Runtime.TypeSystem;
public sealed class Storage : RT.Storage
{
const uint DRAMSize = 1 * 8 * 1024 * 1024;
const uint DRAMBase = 0x80000000 + DRAMSize;
const uint DRAMEnd = DRAMBase + DRAMSize;
const uint DRAMMask = ~(DRAMSize - 1);
const byte ErasedValueByte = (byte)0xFFu;
const ushort ErasedValue = (ushort)0xFFFFu;
const uint ErasedValuePair = 0xFFFFFFFFu;
//
// State
//
//
// Helper Methods
//
public override unsafe void InitializeStorage()
{
EraseSectors( new UIntPtr( DRAMBase ), new UIntPtr( DRAMEnd ) );
}
//--//
public override unsafe bool EraseSectors( UIntPtr addressStart ,
UIntPtr addressEnd )
{
if(ValidateAddress ( addressStart ) &&
ValidateAddressPlus1( addressEnd ) )
{
Memory.Fill( addressStart, addressEnd, 0xFF );
return true;
}
return false;
}
public override unsafe bool WriteByte( UIntPtr address ,
byte val )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
*ptr = val;
return true;
}
return false;
}
public override unsafe bool WriteShort( UIntPtr address ,
ushort val )
{
if(IsOddAddress( address ))
{
return WriteByte( address, (byte) val ) &&
WriteByte( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (byte)(val >> 8) ) ;
}
else
{
if(ValidateAddress( address ))
{
ushort* wordAddress = (ushort*)address.ToPointer();
*wordAddress = val;
return true;
}
return false;
}
}
public override bool WriteWord( UIntPtr address ,
uint val )
{
if(IsOddAddress( address ))
{
return WriteByte ( address, (byte ) val ) &&
WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 1 ), (ushort)(val >> 8) ) &&
WriteByte ( Microsoft.Zelig.AddressMath.Increment( address, 3 ), (byte )(val >> 24) ) ;
}
else
{
return WriteShort( address, (ushort) val ) &&
WriteShort( Microsoft.Zelig.AddressMath.Increment( address, 2 ), (ushort)(val >> 16) ) ;
}
}
public override bool Write( UIntPtr address ,
byte[] buffer ,
uint offset ,
uint numBytes )
{
if(numBytes > 0)
{
if(IsOddAddress( address ))
{
if(WriteByte( address, buffer[offset] ) == false)
{
return false;
}
address = Microsoft.Zelig.AddressMath.Increment( address, 1 );
offset += 1;
numBytes -= 1;
}
while(numBytes >= 2)
{
uint val;
val = (uint)buffer[ offset++ ];
val |= (uint)buffer[ offset++ ] << 8;
if(WriteShort( address, (ushort)val ) == false)
{
return false;
}
address = Microsoft.Zelig.AddressMath.Increment( address, 2 );
numBytes -= 2;
}
if(numBytes != 0)
{
if(WriteByte( address, buffer[offset] ) == false)
{
return false;
}
}
}
return true;
}
//--//
public override unsafe byte ReadByte( UIntPtr address )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
return ptr[0];
}
return ErasedValueByte;
}
public override unsafe ushort ReadShort( UIntPtr address )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
return (ushort)((uint)ptr[0] |
(uint)ptr[1] << 8 );
}
return ErasedValue;
}
public override unsafe uint ReadWord( UIntPtr address )
{
if(ValidateAddress( address ))
{
byte* ptr = (byte*)address.ToPointer();
return ((uint)ptr[0] |
(uint)ptr[1] << 8 |
(uint)ptr[2] << 16 |
(uint)ptr[3] << 24 );
}
return ErasedValuePair;
}
public override void Read( UIntPtr address ,
byte[] buffer ,
uint offset ,
uint numBytes )
{
while(numBytes != 0)
{
buffer[offset++] = ReadByte( address );
address = Microsoft.Zelig.AddressMath.Increment( address, 1 );
numBytes--;
}
}
public override void SubstituteFirmware( UIntPtr addressDestination ,
UIntPtr addressSource ,
uint numBytes )
{
throw new NotImplementedException();
}
public override void RebootDevice()
{
throw new System.NotImplementedException();
}
//--//
[RT.Inline]
static bool ValidateAddress( UIntPtr address )
{
if(Zelig.AddressMath.IsLessThan( address, new UIntPtr( DRAMBase ) ))
{
return false;
}
if(Zelig.AddressMath.IsGreaterThanOrEqual( address, new UIntPtr( DRAMEnd ) ))
{
return false;
}
return true;
}
[RT.Inline]
static bool ValidateAddressPlus1( UIntPtr address )
{
if(Zelig.AddressMath.IsLessThanOrEqual( address, new UIntPtr( DRAMBase ) ))
{
return false;
}
if(Zelig.AddressMath.IsGreaterThan( address, new UIntPtr( DRAMEnd ) ))
{
return false;
}
return true;
}
[RT.Inline]
static bool IsOddAddress( UIntPtr address )
{
return Zelig.AddressMath.IsAlignedTo16bits( address ) == false;
}
}
}
| |
using System;
using System.Collections;
using System.IO;
using Org.BouncyCastle.Asn1;
using Org.BouncyCastle.Asn1.Cms;
using Org.BouncyCastle.Asn1.X509;
using Org.BouncyCastle.Security.Certificates;
using Org.BouncyCastle.Utilities;
using Org.BouncyCastle.X509;
using Org.BouncyCastle.X509.Store;
namespace Org.BouncyCastle.Cms
{
/**
* general class for handling a pkcs7-signature message.
*
* A simple example of usage - note, in the example below the validity of
* the certificate isn't verified, just the fact that one of the certs
* matches the given signer...
*
* <pre>
* IX509Store certs = s.GetCertificates();
* SignerInformationStore signers = s.GetSignerInfos();
*
* foreach (SignerInformation signer in signers.GetSigners())
* {
* ArrayList certList = new ArrayList(certs.GetMatches(signer.SignerID));
* X509Certificate cert = (X509Certificate) certList[0];
*
* if (signer.Verify(cert.GetPublicKey()))
* {
* verified++;
* }
* }
* </pre>
*/
public class CmsSignedData
{
private static readonly CmsSignedHelper Helper = CmsSignedHelper.Instance;
private readonly CmsProcessable signedContent;
private SignedData signedData;
private ContentInfo contentInfo;
private SignerInformationStore signerInfoStore;
private IX509Store attrCertStore;
private IX509Store certificateStore;
private IX509Store crlStore;
private IDictionary hashes;
private CmsSignedData(
CmsSignedData c)
{
this.signedData = c.signedData;
this.contentInfo = c.contentInfo;
this.signedContent = c.signedContent;
this.signerInfoStore = c.signerInfoStore;
}
public CmsSignedData(
byte[] sigBlock)
: this(CmsUtilities.ReadContentInfo(new MemoryStream(sigBlock, false)))
{
}
public CmsSignedData(
CmsProcessable signedContent,
byte[] sigBlock)
: this(signedContent, CmsUtilities.ReadContentInfo(new MemoryStream(sigBlock, false)))
{
}
/**
* Content with detached signature, digests precomputed
*
* @param hashes a map of precomputed digests for content indexed by name of hash.
* @param sigBlock the signature object.
*/
public CmsSignedData(
IDictionary hashes,
byte[] sigBlock)
: this(hashes, CmsUtilities.ReadContentInfo(sigBlock))
{
}
/**
* base constructor - content with detached signature.
*
* @param signedContent the content that was signed.
* @param sigData the signature object.
*/
public CmsSignedData(
CmsProcessable signedContent,
Stream sigData)
: this(signedContent, CmsUtilities.ReadContentInfo(sigData))
{
}
/**
* base constructor - with encapsulated content
*/
public CmsSignedData(
Stream sigData)
: this(CmsUtilities.ReadContentInfo(sigData))
{
}
public CmsSignedData(
CmsProcessable signedContent,
ContentInfo sigData)
{
this.signedContent = signedContent;
this.contentInfo = sigData;
this.signedData = SignedData.GetInstance(contentInfo.Content);
}
public CmsSignedData(
IDictionary hashes,
ContentInfo sigData)
{
this.hashes = hashes;
this.contentInfo = sigData;
this.signedData = SignedData.GetInstance(contentInfo.Content);
}
public CmsSignedData(
ContentInfo sigData)
{
this.contentInfo = sigData;
this.signedData = SignedData.GetInstance(contentInfo.Content);
//
// this can happen if the signed message is sent simply to send a
// certificate chain.
//
if (signedData.EncapContentInfo.Content != null)
{
this.signedContent = new CmsProcessableByteArray(
((Asn1OctetString)(signedData.EncapContentInfo.Content)).GetOctets());
}
// else
// {
// this.signedContent = null;
// }
}
/// <summary>Return the version number for this object.</summary>
public int Version
{
get { return signedData.Version.Value.IntValue; }
}
/**
* return the collection of signers that are associated with the
* signatures for the message.
*/
public SignerInformationStore GetSignerInfos()
{
if (signerInfoStore == null)
{
IList signerInfos = new ArrayList();
Asn1Set s = signedData.SignerInfos;
foreach (object obj in s)
{
SignerInfo info = SignerInfo.GetInstance(obj);
DerObjectIdentifier contentType = signedData.EncapContentInfo.ContentType;
if (hashes == null)
{
signerInfos.Add(new SignerInformation(info, contentType, signedContent, null));
}
else
{
byte[] hash = (byte[]) hashes[info.DigestAlgorithm.ObjectID.Id];
signerInfos.Add(new SignerInformation(info, contentType, null, new BaseDigestCalculator(hash)));
}
}
signerInfoStore = new SignerInformationStore(signerInfos);
}
return signerInfoStore;
}
/**
* return a X509Store containing the attribute certificates, if any, contained
* in this message.
*
* @param type type of store to create
* @return a store of attribute certificates
* @exception NoSuchStoreException if the store type isn't available.
* @exception CmsException if a general exception prevents creation of the X509Store
*/
public IX509Store GetAttributeCertificates(
string type)
{
if (attrCertStore == null)
{
attrCertStore = Helper.CreateAttributeStore(type, signedData.Certificates);
}
return attrCertStore;
}
/**
* return a X509Store containing the public key certificates, if any, contained
* in this message.
*
* @param type type of store to create
* @return a store of public key certificates
* @exception NoSuchStoreException if the store type isn't available.
* @exception CmsException if a general exception prevents creation of the X509Store
*/
public IX509Store GetCertificates(
string type)
{
if (certificateStore == null)
{
certificateStore = Helper.CreateCertificateStore(type, signedData.Certificates);
}
return certificateStore;
}
/**
* return a X509Store containing CRLs, if any, contained
* in this message.
*
* @param type type of store to create
* @return a store of CRLs
* @exception NoSuchStoreException if the store type isn't available.
* @exception CmsException if a general exception prevents creation of the X509Store
*/
public IX509Store GetCrls(
string type)
{
if (crlStore == null)
{
crlStore = Helper.CreateCrlStore(type, signedData.CRLs);
}
return crlStore;
}
[Obsolete("Use 'SignedContentType' property instead.")]
public string SignedContentTypeOid
{
get { return signedData.EncapContentInfo.ContentType.Id; }
}
/// <summary>
/// Return the <c>DerObjectIdentifier</c> associated with the encapsulated
/// content info structure carried in the signed data.
/// </summary>
public DerObjectIdentifier SignedContentType
{
get { return signedData.EncapContentInfo.ContentType; }
}
public CmsProcessable SignedContent
{
get { return signedContent; }
}
/**
* return the ContentInfo
*/
public ContentInfo ContentInfo
{
get { return contentInfo; }
}
/**
* return the ASN.1 encoded representation of this object.
*/
public byte[] GetEncoded()
{
return contentInfo.GetEncoded();
}
/**
* Replace the signerinformation store associated with this
* CmsSignedData object with the new one passed in. You would
* probably only want to do this if you wanted to change the unsigned
* attributes associated with a signer, or perhaps delete one.
*
* @param signedData the signed data object to be used as a base.
* @param signerInformationStore the new signer information store to use.
* @return a new signed data object.
*/
public static CmsSignedData ReplaceSigners(
CmsSignedData signedData,
SignerInformationStore signerInformationStore)
{
//
// copy
//
CmsSignedData cms = new CmsSignedData(signedData);
//
// replace the store
//
cms.signerInfoStore = signerInformationStore;
//
// replace the signers in the SignedData object
//
Asn1EncodableVector digestAlgs = new Asn1EncodableVector();
Asn1EncodableVector vec = new Asn1EncodableVector();
foreach (SignerInformation signer in signerInformationStore.GetSigners())
{
digestAlgs.Add(Helper.FixAlgID(signer.DigestAlgorithmID));
vec.Add(signer.ToSignerInfo());
}
Asn1Set digests = new DerSet(digestAlgs);
Asn1Set signers = new DerSet(vec);
Asn1Sequence sD = (Asn1Sequence)signedData.signedData.ToAsn1Object();
//
// signers are the last item in the sequence.
//
vec = new Asn1EncodableVector(
sD[0], // version
digests);
for (int i = 2; i != sD.Count - 1; i++)
{
vec.Add(sD[i]);
}
vec.Add(signers);
cms.signedData = SignedData.GetInstance(new BerSequence(vec));
//
// replace the contentInfo with the new one
//
cms.contentInfo = new ContentInfo(cms.contentInfo.ContentType, cms.signedData);
return cms;
}
/**
* Replace the certificate and CRL information associated with this
* CmsSignedData object with the new one passed in.
*
* @param signedData the signed data object to be used as a base.
* @param x509Certs the new certificates to be used.
* @param x509Crls the new CRLs to be used.
* @return a new signed data object.
* @exception CmsException if there is an error processing the stores
*/
public static CmsSignedData ReplaceCertificatesAndCrls(
CmsSignedData signedData,
IX509Store x509Certs,
IX509Store x509Crls,
IX509Store x509AttrCerts)
{
if (x509AttrCerts != null)
throw Platform.CreateNotImplementedException("Currently can't replace attribute certificates");
//
// copy
//
CmsSignedData cms = new CmsSignedData(signedData);
//
// replace the certs and crls in the SignedData object
//
Asn1Set certs = null;
try
{
Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList(
CmsUtilities.GetCertificatesFromStore(x509Certs));
if (asn1Set.Count != 0)
{
certs = asn1Set;
}
}
catch (X509StoreException e)
{
throw new CmsException("error getting certificates from store", e);
}
Asn1Set crls = null;
try
{
Asn1Set asn1Set = CmsUtilities.CreateBerSetFromList(
CmsUtilities.GetCrlsFromStore(x509Crls));
if (asn1Set.Count != 0)
{
crls = asn1Set;
}
}
catch (X509StoreException e)
{
throw new CmsException("error getting CRLs from store", e);
}
//
// replace the CMS structure.
//
SignedData old = signedData.signedData;
cms.signedData = new SignedData(
old.DigestAlgorithms,
old.EncapContentInfo,
certs,
crls,
old.SignerInfos);
//
// replace the contentInfo with the new one
//
cms.contentInfo = new ContentInfo(cms.contentInfo.ContentType, cms.signedData);
return cms;
}
}
}
| |
//#define ASTARDEBUG
using UnityEngine;
using System.Collections;
using System.Collections.Generic;
using Pathfinding;
/** AI for following paths.
* This AI is the default movement script which comes with the A* Pathfinding Project.
* It is in no way required by the rest of the system, so feel free to write your own. But I hope this script will make it easier
* to set up movement for the characters in your game. This script is not written for high performance, so I do not recommend using it for large groups of units.
* \n
* \n
* This script will try to follow a target transform, in regular intervals, the path to that target will be recalculated.
* It will on FixedUpdate try to move towards the next point in the path.
* However it will only move in the forward direction, but it will rotate around it's Y-axis
* to make it reach the target.
*
* \section variables Quick overview of the variables
* In the inspector in Unity, you will see a bunch of variables. You can view detailed information further down, but here's a quick overview.\n
* The #repathRate determines how often it will search for new paths, if you have fast moving targets, you might want to set it to a lower value.\n
* The #target variable is where the AI will try to move, it can be a point on the ground where the player has clicked in an RTS for example.
* Or it can be the player object in a zombie game.\n
* The speed is self-explanatory, so is turningSpeed, however #slowdownDistance might require some explanation.
* It is the approximate distance from the target where the AI will start to slow down. Note that this doesn't only affect the end point of the path
* but also any intermediate points, so be sure to set #forwardLook and #pickNextWaypointDist to a higher value than this.\n
* #pickNextWaypointDist is simply determines within what range it will switch to target the next waypoint in the path.\n
* #forwardLook will try to calculate an interpolated target point on the current segment in the path so that it has a distance of #forwardLook from the AI\n
* Below is an image illustrating several variables as well as some internal ones, but which are relevant for understanding how it works.
* Note that the #forwardLook range will not match up exactly with the target point practically, even though that's the goal.
* \shadowimage{aipath_variables.png}
* This script has many movement fallbacks.
* If it finds a NavmeshController, it will use that, otherwise it will look for a character controller, then for a rigidbody and if it hasn't been able to find any
* it will use Transform.Translate which is guaranteed to always work.
*/
[RequireComponent(typeof(Seeker))]
[AddComponentMenu("Pathfinding/AI/AIPath (generic)")]
public class AIPath : MonoBehaviour {
/** Determines how often it will search for new paths.
* If you have fast moving targets or AIs, you might want to set it to a lower value.
* The value is in seconds between path requests.
*/
public float repathRate = 0.5F;
/** Target to move towards.
* The AI will try to follow/move towards this target.
* It can be a point on the ground where the player has clicked in an RTS for example, or it can be the player object in a zombie game.
*/
public Transform target;
/** Enables or disables searching for paths.
* Setting this to false does not stop any active path requests from being calculated or stop it from continuing to follow the current path.
* \see #canMove
*/
public bool canSearch = true;
/** Enables or disables movement.
* \see #canSearch */
public bool canMove = true;
/** Maximum velocity.
* This is the maximum speed in world units per second.
*/
public float speed = 3;
/** Rotation speed.
* Rotation is calculated using Quaternion.SLerp. This variable represents the damping, the higher, the faster it will be able to rotate.
*/
public float turningSpeed = 5;
/** Distance from the target point where the AI will start to slow down.
* Note that this doesn't only affect the end point of the path
* but also any intermediate points, so be sure to set #forwardLook and #pickNextWaypointDist to a higher value than this
*/
public float slowdownDistance = 0.6F;
/** Determines within what range it will switch to target the next waypoint in the path */
public float pickNextWaypointDist = 2;
/** Target point is Interpolated on the current segment in the path so that it has a distance of #forwardLook from the AI.
* See the detailed description of AIPath for an illustrative image */
public float forwardLook = 1;
/** Distance to the end point to consider the end of path to be reached.
* When this has been reached, the AI will not move anymore until the target changes and OnTargetReached will be called.
*/
public float endReachedDistance = 0.2F;
/** Do a closest point on path check when receiving path callback.
* Usually the AI has moved a bit between requesting the path, and getting it back, and there is usually a small gap between the AI
* and the closest node.
* If this option is enabled, it will simulate, when the path callback is received, movement between the closest node and the current
* AI position. This helps to reduce the moments when the AI just get a new path back, and thinks it ought to move backwards to the start of the new path
* even though it really should just proceed forward.
*/
public bool closestOnPathCheck = true;
protected float minMoveScale = 0.05F;
/** Cached Seeker component */
protected Seeker seeker;
/** Cached Transform component */
protected Transform tr;
/** Time when the last path request was sent */
private float lastRepath = -9999;
/** Current path which is followed */
protected Path path;
/** Cached CharacterController component */
protected CharacterController controller;
/** Cached NavmeshController component */
protected NavmeshController navController;
/** Cached Rigidbody component */
protected Rigidbody rigid;
/** Current index in the path which is current target */
protected int currentWaypointIndex = 0;
/** Holds if the end-of-path is reached
* \see TargetReached */
protected bool targetReached = false;
/** Only when the previous path has been returned should be search for a new path */
protected bool canSearchAgain = true;
protected Vector3 lastFoundWaypointPosition;
protected float lastFoundWaypointTime = -9999;
/** Returns if the end-of-path has been reached
* \see targetReached */
public bool TargetReached {
get {
return targetReached;
}
}
/** Holds if the Start function has been run.
* Used to test if coroutines should be started in OnEnable to prevent calculating paths
* in the awake stage (or rather before start on frame 0).
*/
private bool startHasRun = false;
/** Initializes reference variables.
* If you override this function you should in most cases call base.Awake () at the start of it.
* */
protected virtual void Awake () {
seeker = GetComponent<Seeker>();
//This is a simple optimization, cache the transform component lookup
tr = transform;
//Cache some other components (not all are necessarily there)
controller = GetComponent<CharacterController>();
navController = GetComponent<NavmeshController>();
rigid = GetComponent<Rigidbody>();
}
/** Starts searching for paths.
* If you override this function you should in most cases call base.Start () at the start of it.
* \see OnEnable
* \see RepeatTrySearchPath
*/
protected virtual void Start () {
startHasRun = true;
OnEnable ();
}
/** Run at start and when reenabled.
* Starts RepeatTrySearchPath.
*
* \see Start
*/
protected virtual void OnEnable () {
lastRepath = -9999;
canSearchAgain = true;
lastFoundWaypointPosition = GetFeetPosition ();
if (startHasRun) {
//Make sure we receive callbacks when paths complete
seeker.pathCallback += OnPathComplete;
StartCoroutine (RepeatTrySearchPath ());
}
}
public void OnDisable () {
// Abort calculation of path
if (seeker != null && !seeker.IsDone()) seeker.GetCurrentPath().Error();
// Release current path
if (path != null) path.Release (this);
path = null;
//Make sure we receive callbacks when paths complete
seeker.pathCallback -= OnPathComplete;
}
/** Tries to search for a path every #repathRate seconds.
* \see TrySearchPath
*/
protected IEnumerator RepeatTrySearchPath () {
while (true) {
float v = TrySearchPath ();
yield return new WaitForSeconds (v);
}
}
/** Tries to search for a path.
* Will search for a new path if there was a sufficient time since the last repath and both
* #canSearchAgain and #canSearch are true and there is a target.
*
* \returns The time to wait until calling this function again (based on #repathRate)
*/
public float TrySearchPath () {
if (Time.time - lastRepath >= repathRate && canSearchAgain && canSearch && target != null) {
SearchPath ();
return repathRate;
} else {
//StartCoroutine (WaitForRepath ());
float v = repathRate - (Time.time-lastRepath);
return v < 0 ? 0 : v;
}
}
/** Requests a path to the target */
public virtual void SearchPath () {
if (target == null) throw new System.InvalidOperationException ("Target is null");
lastRepath = Time.time;
//This is where we should search to
Vector3 targetPosition = target.position;
canSearchAgain = false;
//Alternative way of requesting the path
//ABPath p = ABPath.Construct (GetFeetPosition(),targetPoint,null);
//seeker.StartPath (p);
//We should search from the current position
seeker.StartPath (GetFeetPosition(), targetPosition);
}
public virtual void OnTargetReached () {
//End of path has been reached
//If you want custom logic for when the AI has reached it's destination
//add it here
//You can also create a new script which inherits from this one
//and override the function in that script
}
/** Called when a requested path has finished calculation.
* A path is first requested by #SearchPath, it is then calculated, probably in the same or the next frame.
* Finally it is returned to the seeker which forwards it to this function.\n
*/
public virtual void OnPathComplete (Path _p) {
ABPath p = _p as ABPath;
if (p == null) throw new System.Exception ("This function only handles ABPaths, do not use special path types");
canSearchAgain = true;
//Claim the new path
p.Claim (this);
// Path couldn't be calculated of some reason.
// More info in p.errorLog (debug string)
if (p.error) {
p.Release (this);
return;
}
//Release the previous path
if (path != null) path.Release (this);
//Replace the old path
path = p;
//Reset some variables
currentWaypointIndex = 0;
targetReached = false;
//The next row can be used to find out if the path could be found or not
//If it couldn't (error == true), then a message has probably been logged to the console
//however it can also be got using p.errorLog
//if (p.error)
if (closestOnPathCheck) {
Vector3 p1 = Time.time - lastFoundWaypointTime < 0.3f ? lastFoundWaypointPosition : p.originalStartPoint;
Vector3 p2 = GetFeetPosition ();
Vector3 dir = p2-p1;
float magn = dir.magnitude;
dir /= magn;
int steps = (int)(magn/pickNextWaypointDist);
for (int i=0;i<=steps;i++) {
CalculateVelocity (p1);
p1 += dir;
}
}
}
public virtual Vector3 GetFeetPosition () {
if (controller != null) {
return tr.position - Vector3.up*controller.height*0.5F;
}
return tr.position;
}
public virtual void Update () {
if (!canMove) { return; }
Vector3 dir = CalculateVelocity (GetFeetPosition());
//Rotate towards targetDirection (filled in by CalculateVelocity)
RotateTowards (targetDirection);
if (navController != null) {
} else if (controller != null) {
controller.SimpleMove (dir);
} else if (rigid != null) {
rigid.AddForce (dir);
} else {
transform.Translate (dir*Time.deltaTime, Space.World);
}
}
/** Point to where the AI is heading.
* Filled in by #CalculateVelocity */
protected Vector3 targetPoint;
/** Relative direction to where the AI is heading.
* Filled in by #CalculateVelocity */
protected Vector3 targetDirection;
protected float XZSqrMagnitude (Vector3 a, Vector3 b) {
float dx = b.x-a.x;
float dz = b.z-a.z;
return dx*dx + dz*dz;
}
/** Calculates desired velocity.
* Finds the target path segment and returns the forward direction, scaled with speed.
* A whole bunch of restrictions on the velocity is applied to make sure it doesn't overshoot, does not look too far ahead,
* and slows down when close to the target.
* /see speed
* /see endReachedDistance
* /see slowdownDistance
* /see CalculateTargetPoint
* /see targetPoint
* /see targetDirection
* /see currentWaypointIndex
*/
protected Vector3 CalculateVelocity (Vector3 currentPosition) {
if (path == null || path.vectorPath == null || path.vectorPath.Count == 0) return Vector3.zero;
List<Vector3> vPath = path.vectorPath;
//Vector3 currentPosition = GetFeetPosition();
if (vPath.Count == 1) {
vPath.Insert (0,currentPosition);
}
if (currentWaypointIndex >= vPath.Count) { currentWaypointIndex = vPath.Count-1; }
if (currentWaypointIndex <= 1) currentWaypointIndex = 1;
while (true) {
if (currentWaypointIndex < vPath.Count-1) {
//There is a "next path segment"
float dist = XZSqrMagnitude (vPath[currentWaypointIndex], currentPosition);
//Mathfx.DistancePointSegmentStrict (vPath[currentWaypointIndex+1],vPath[currentWaypointIndex+2],currentPosition);
if (dist < pickNextWaypointDist*pickNextWaypointDist) {
lastFoundWaypointPosition = currentPosition;
lastFoundWaypointTime = Time.time;
currentWaypointIndex++;
} else {
break;
}
} else {
break;
}
}
Vector3 dir = vPath[currentWaypointIndex] - vPath[currentWaypointIndex-1];
Vector3 targetPosition = CalculateTargetPoint (currentPosition,vPath[currentWaypointIndex-1] , vPath[currentWaypointIndex]);
//vPath[currentWaypointIndex] + Vector3.ClampMagnitude (dir,forwardLook);
dir = targetPosition-currentPosition;
dir.y = 0;
float targetDist = dir.magnitude;
float slowdown = Mathf.Clamp01 (targetDist / slowdownDistance);
this.targetDirection = dir;
this.targetPoint = targetPosition;
if (currentWaypointIndex == vPath.Count-1 && targetDist <= endReachedDistance) {
if (!targetReached) { targetReached = true; OnTargetReached (); }
//Send a move request, this ensures gravity is applied
return Vector3.zero;
}
Vector3 forward = tr.forward;
float dot = Vector3.Dot (dir.normalized,forward);
float sp = speed * Mathf.Max (dot,minMoveScale) * slowdown;
if (Time.deltaTime > 0) {
sp = Mathf.Clamp (sp,0,targetDist/(Time.deltaTime*2));
}
return forward*sp;
}
/** Rotates in the specified direction.
* Rotates around the Y-axis.
* \see turningSpeed
*/
protected virtual void RotateTowards (Vector3 dir) {
if (dir == Vector3.zero) return;
Quaternion rot = tr.rotation;
Quaternion toTarget = Quaternion.LookRotation (dir);
rot = Quaternion.Slerp (rot,toTarget,turningSpeed*Time.deltaTime);
Vector3 euler = rot.eulerAngles;
euler.z = 0;
euler.x = 0;
rot = Quaternion.Euler (euler);
tr.rotation = rot;
}
/** Calculates target point from the current line segment.
* \param p Current position
* \param a Line segment start
* \param b Line segment end
* The returned point will lie somewhere on the line segment.
* \see #forwardLook
* \todo This function uses .magnitude quite a lot, can it be optimized?
*/
protected Vector3 CalculateTargetPoint (Vector3 p, Vector3 a, Vector3 b) {
a.y = p.y;
b.y = p.y;
float magn = (a-b).magnitude;
if (magn == 0) return a;
float closest = AstarMath.Clamp01 (AstarMath.NearestPointFactor (a, b, p));
Vector3 point = (b-a)*closest + a;
float distance = (point-p).magnitude;
float lookAhead = Mathf.Clamp (forwardLook - distance, 0.0F, forwardLook);
float offset = lookAhead / magn;
offset = Mathf.Clamp (offset+closest,0.0F,1.0F);
return (b-a)*offset + a;
}
}
| |
// ==++==
//
// Copyright (c) Microsoft Corporation. All rights reserved.
//
// ==--==
namespace System.Globalization
{
using System;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
using System.Runtime.Versioning;
using System.Diagnostics.Contracts;
//
//
// List of calendar data
// Note the we cache overrides.
// Note that localized names (resource names) aren't available from here.
//
// NOTE: Calendars depend on the locale name that creates it. Only a few
// properties are available without locales using CalendarData.GetCalendar(int)
// StructLayout is needed here otherwise compiler can re-arrange the fields.
// We have to keep this in-[....] with the definition in calendardata.h
//
// WARNING WARNING WARNING
//
// WARNING: Anything changed here also needs to be updated on the native side (object.h see type CalendarDataBaseObject)
// WARNING: The type loader will rearrange class member offsets so the mscorwks!CalendarDataBaseObject
// WARNING: must be manually structured to match the true loaded class layout
//
internal class CalendarData
{
// Max calendars
internal const int MAX_CALENDARS = 23;
// Identity
internal String sNativeName ; // Calendar Name for the locale
// Formats
internal String[] saShortDates ; // Short Data format, default first
internal String[] saYearMonths ; // Year/Month Data format, default first
internal String[] saLongDates ; // Long Data format, default first
internal String sMonthDay ; // Month/Day format
// Calendar Parts Names
internal String[] saEraNames ; // Names of Eras
internal String[] saAbbrevEraNames ; // Abbreviated Era Names
internal String[] saAbbrevEnglishEraNames ; // Abbreviated Era Names in English
internal String[] saDayNames ; // Day Names, null to use locale data, starts on Sunday
internal String[] saAbbrevDayNames ; // Abbrev Day Names, null to use locale data, starts on Sunday
internal String[] saSuperShortDayNames ; // Super short Day of week names
internal String[] saMonthNames ; // Month Names (13)
internal String[] saAbbrevMonthNames ; // Abbrev Month Names (13)
internal String[] saMonthGenitiveNames ; // Genitive Month Names (13)
internal String[] saAbbrevMonthGenitiveNames; // Genitive Abbrev Month Names (13)
internal String[] saLeapYearMonthNames ; // Multiple strings for the month names in a leap year.
// Integers at end to make marshaller happier
internal int iTwoDigitYearMax=2029 ; // Max 2 digit year (for Y2K bug data entry)
internal int iCurrentEra=0 ; // current era # (usually 1)
// Use overrides?
internal bool bUseUserOverrides ; // True if we want user overrides.
// Static invariant for the invariant locale
internal static CalendarData Invariant;
// Private constructor
private CalendarData() {}
// Invariant constructor
static CalendarData()
{
// Set our default/gregorian US calendar data
// Calendar IDs are 1-based, arrays are 0 based.
CalendarData invariant = new CalendarData();
// Set default data for calendar
// Note that we don't load resources since this IS NOT supposed to change (by definition)
invariant.sNativeName = "Gregorian Calendar"; // Calendar Name
// Year
invariant.iTwoDigitYearMax = 2029; // Max 2 digit year (for Y2K bug data entry)
invariant.iCurrentEra = 1; // Current era #
// Formats
invariant.saShortDates = new String[] { "MM/dd/yyyy", "yyyy-MM-dd" }; // short date format
invariant.saLongDates = new String[] { "dddd, dd MMMM yyyy"}; // long date format
invariant.saYearMonths = new String[] { "yyyy MMMM" }; // year month format
invariant.sMonthDay = "MMMM dd"; // Month day pattern
// Calendar Parts Names
invariant.saEraNames = new String[] { "A.D." }; // Era names
invariant.saAbbrevEraNames = new String[] { "AD" }; // Abbreviated Era names
invariant.saAbbrevEnglishEraNames=new String[] { "AD" }; // Abbreviated era names in English
invariant.saDayNames = new String[] { "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" };// day names
invariant.saAbbrevDayNames = new String[] { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" }; // abbreviated day names
invariant.saSuperShortDayNames = new String[] { "Su", "Mo", "Tu", "We", "Th", "Fr", "Sa" }; // The super short day names
invariant.saMonthNames = new String[] { "January", "February", "March", "April", "May", "June",
"July", "August", "September", "October", "November", "December", String.Empty}; // month names
invariant.saAbbrevMonthNames = new String[] { "Jan", "Feb", "Mar", "Apr", "May", "Jun",
"Jul", "Aug", "Sep", "Oct", "Nov", "Dec", String.Empty}; // abbreviated month names
invariant.saMonthGenitiveNames = invariant.saMonthNames; // Genitive month names (same as month names for invariant)
invariant.saAbbrevMonthGenitiveNames=invariant.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
invariant.saLeapYearMonthNames = invariant.saMonthNames; // leap year month names are unused in Gregorian English (invariant)
invariant.bUseUserOverrides = false;
// Calendar was built, go ahead and assign it...
Invariant = invariant;
}
//
// Get a bunch of data for a calendar
//
internal CalendarData(String localeName, int calendarId, bool bUseUserOverrides)
{
// Call nativeGetCalendarData to populate the data
this.bUseUserOverrides = bUseUserOverrides;
if (!nativeGetCalendarData(this, localeName, calendarId))
{
Contract.Assert(false, "[CalendarData] nativeGetCalendarData call isn't expected to fail for calendar " + calendarId + " locale " +localeName);
// Something failed, try invariant for missing parts
// This is really not good, but we don't want the callers to crash.
if (this.sNativeName == null) this.sNativeName = String.Empty; // Calendar Name for the locale.
// Formats
if (this.saShortDates == null) this.saShortDates = Invariant.saShortDates; // Short Data format, default first
if (this.saYearMonths == null) this.saYearMonths = Invariant.saYearMonths; // Year/Month Data format, default first
if (this.saLongDates == null) this.saLongDates = Invariant.saLongDates; // Long Data format, default first
if (this.sMonthDay == null) this.sMonthDay = Invariant.sMonthDay; // Month/Day format
// Calendar Parts Names
if (this.saEraNames == null) this.saEraNames = Invariant.saEraNames; // Names of Eras
if (this.saAbbrevEraNames == null) this.saAbbrevEraNames = Invariant.saAbbrevEraNames; // Abbreviated Era Names
if (this.saAbbrevEnglishEraNames == null) this.saAbbrevEnglishEraNames = Invariant.saAbbrevEnglishEraNames; // Abbreviated Era Names in English
if (this.saDayNames == null) this.saDayNames = Invariant.saDayNames; // Day Names, null to use locale data, starts on Sunday
if (this.saAbbrevDayNames == null) this.saAbbrevDayNames = Invariant.saAbbrevDayNames; // Abbrev Day Names, null to use locale data, starts on Sunday
if (this.saSuperShortDayNames == null) this.saSuperShortDayNames = Invariant.saSuperShortDayNames; // Super short Day of week names
if (this.saMonthNames == null) this.saMonthNames = Invariant.saMonthNames; // Month Names (13)
if (this.saAbbrevMonthNames == null) this.saAbbrevMonthNames = Invariant.saAbbrevMonthNames; // Abbrev Month Names (13)
// Genitive and Leap names can follow the fallback below
}
// Clean up the escaping of the formats
this.saShortDates = CultureData.ReescapeWin32Strings(this.saShortDates);
this.saLongDates = CultureData.ReescapeWin32Strings(this.saLongDates);
this.saYearMonths = CultureData.ReescapeWin32Strings(this.saYearMonths);
this.sMonthDay = CultureData.ReescapeWin32String(this.sMonthDay);
if ((CalendarId)calendarId == CalendarId.TAIWAN)
{
// for Geo----al reasons, the ----ese native name should only be returned when
// for ----ese SKU
if (CultureInfo.IsTaiwanSku)
{
// We got the month/day names from the OS (same as gregorian), but the native name is wrong
this.sNativeName = "\x4e2d\x83ef\x6c11\x570b\x66c6";
}
else
{
this.sNativeName = String.Empty;
}
}
// Check for null genitive names (in case unmanaged side skips it for non-gregorian calendars, etc)
if (this.saMonthGenitiveNames == null || String.IsNullOrEmpty(this.saMonthGenitiveNames[0]))
this.saMonthGenitiveNames = this.saMonthNames; // Genitive month names (same as month names for invariant)
if (this.saAbbrevMonthGenitiveNames == null || String.IsNullOrEmpty(this.saAbbrevMonthGenitiveNames[0]))
this.saAbbrevMonthGenitiveNames = this.saAbbrevMonthNames; // Abbreviated genitive month names (same as abbrev month names for invariant)
if (this.saLeapYearMonthNames == null || String.IsNullOrEmpty(this.saLeapYearMonthNames[0]))
this.saLeapYearMonthNames = this.saMonthNames;
InitializeEraNames(localeName, calendarId);
InitializeAbbreviatedEraNames(localeName, calendarId);
// Abbreviated English Era Names are only used for the Japanese calendar.
if (calendarId == (int)CalendarId.JAPAN)
{
this.saAbbrevEnglishEraNames = JapaneseCalendar.EnglishEraNames();
}
else
{
// For all others just use the an empty string (doesn't matter we'll never ask for it for other calendars)
this.saAbbrevEnglishEraNames = new String[] { "" };
}
// Japanese is the only thing with > 1 era. Its current era # is how many ever
// eras are in the array. (And the others all have 1 string in the array)
this.iCurrentEra = this.saEraNames.Length;
}
private void InitializeEraNames(string localeName, int calendarId)
{
// Note that the saEraNames only include "A.D." We don't have localized names for other calendars available from windows
switch ((CalendarId)calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
{
this.saEraNames = new String[] { "A.D." };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saEraNames = new String[] { "A.D." };
break;
case CalendarId.HEBREW:
this.saEraNames = new String[] { "C.E." };
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saEraNames = new String[] { "\x0780\x07a8\x0796\x07b0\x0783\x07a9" };
}
else
{
this.saEraNames = new String[] { "\x0628\x0639\x062F \x0627\x0644\x0647\x062C\x0631\x0629" };
}
break;
case CalendarId.GREGORIAN_ARABIC:
case CalendarId.GREGORIAN_XLIT_ENGLISH:
case CalendarId.GREGORIAN_XLIT_FRENCH:
// These are all the same:
this.saEraNames = new String[] { "\x0645" };
break;
case CalendarId.GREGORIAN_ME_FRENCH:
this.saEraNames = new String[] { "ap. J.-C." };
break;
case CalendarId.TAIWAN:
// for Geo----al reasons, the ----ese native name should only be returned when
// for ----ese SKU
if (CultureInfo.IsTaiwanSku)
{
//
this.saEraNames = new String[] { "\x4e2d\x83ef\x6c11\x570b" };
}
else
{
this.saEraNames = new String[] { String.Empty };
}
break;
case CalendarId.KOREA:
this.saEraNames = new String[] { "\xb2e8\xae30" };
break;
case CalendarId.THAI:
this.saEraNames = new String[] { "\x0e1e\x002e\x0e28\x002e" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saEraNames = JapaneseCalendar.EraNames();
break;
case CalendarId.PERSIAN:
if (this.saEraNames == null || this.saEraNames.Length == 0 || String.IsNullOrEmpty(this.saEraNames[0]))
{
this.saEraNames = new String[] { "\x0647\x002e\x0634" };
}
break;
default:
// Most calendars are just "A.D."
this.saEraNames = Invariant.saEraNames;
break;
}
}
private void InitializeAbbreviatedEraNames(string localeName, int calendarId)
{
// Note that the saAbbrevEraNames only include "AD" We don't have localized names for other calendars available from windows
switch ((CalendarId)calendarId)
{
// For Localized Gregorian we really expect the data from the OS.
case CalendarId.GREGORIAN:
// Fallback for CoreCLR < Win7 or culture.dll missing
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = new String[] { "AD" };
}
break;
// The rest of the calendars have constant data, so we'll just use that
case CalendarId.GREGORIAN_US:
case CalendarId.JULIAN:
this.saAbbrevEraNames = new String[] { "AD" };
break;
case CalendarId.JAPAN:
case CalendarId.JAPANESELUNISOLAR:
this.saAbbrevEraNames = JapaneseCalendar.AbbrevEraNames();
break;
case CalendarId.HIJRI:
case CalendarId.UMALQURA:
if (localeName == "dv-MV")
{
// Special case for Divehi
this.saAbbrevEraNames = new String[] { "\x0780\x002e" };
}
else
{
this.saAbbrevEraNames = new String[] { "\x0647\x0640" };
}
break;
case CalendarId.TAIWAN:
// Get era name and abbreviate it
this.saAbbrevEraNames = new String[1];
if (this.saEraNames[0].Length == 4)
{
this.saAbbrevEraNames[0] = this.saEraNames[0].Substring(2,2);
}
else
{
this.saAbbrevEraNames[0] = this.saEraNames[0];
}
break;
case CalendarId.PERSIAN:
if (this.saAbbrevEraNames == null || this.saAbbrevEraNames.Length == 0 || String.IsNullOrEmpty(this.saAbbrevEraNames[0]))
{
this.saAbbrevEraNames = this.saEraNames;
}
break;
default:
// Most calendars just use the full name
this.saAbbrevEraNames = this.saEraNames;
break;
}
}
internal static CalendarData GetCalendarData(int calendarId)
{
//
// Get a calendar.
// Unfortunately we depend on the locale in the OS, so we need a locale
// no matter what. So just get the appropriate calendar from the
// appropriate locale here
//
// Get a culture name
//
String culture = CalendarIdToCultureName(calendarId);
// Return our calendar
return CultureInfo.GetCultureInfo(culture).m_cultureData.GetCalendar(calendarId);
}
//
// Helper methods
//
private static String CalendarIdToCultureName(int calendarId)
{
switch (calendarId)
{
case Calendar.CAL_GREGORIAN_US:
return "fa-IR"; // "fa-IR" Iran
case Calendar.CAL_JAPAN:
return "ja-JP"; // "ja-JP" Japan
case Calendar.CAL_TAIWAN:
return "zh-TW"; // zh-TW Taiwan
case Calendar.CAL_KOREA:
return "ko-KR"; // "ko-KR" Korea
case Calendar.CAL_HIJRI:
case Calendar.CAL_GREGORIAN_ARABIC:
case Calendar.CAL_UMALQURA:
return "ar-SA"; // "ar-SA" Saudi Arabia
case Calendar.CAL_THAI:
return "th-TH"; // "th-TH" Thailand
case Calendar.CAL_HEBREW:
return "he-IL"; // "he-IL" Israel
case Calendar.CAL_GREGORIAN_ME_FRENCH:
return "ar-DZ"; // "ar-DZ" Algeria
case Calendar.CAL_GREGORIAN_XLIT_ENGLISH:
case Calendar.CAL_GREGORIAN_XLIT_FRENCH:
return "ar-IQ"; // "ar-IQ"; Iraq
default:
// Default to gregorian en-US
break;
}
return "en-US";
}
internal void FixupWin7MonthDaySemicolonBug()
{
int unescapedCharacterIndex = FindUnescapedCharacter(sMonthDay, ';');
if (unescapedCharacterIndex > 0)
{
sMonthDay = sMonthDay.Substring(0, unescapedCharacterIndex);
}
}
private static int FindUnescapedCharacter(string s, char charToFind)
{
bool inComment = false;
int length = s.Length;
for (int i = 0; i < length; i++)
{
char c = s[i];
switch (c)
{
case '\'':
inComment = !inComment;
break;
case '\\':
i++; // escape sequence -- skip next character
break;
default:
if (!inComment && charToFind == c)
{
return i;
}
break;
}
}
return -1;
}
// Get native two digit year max
[System.Security.SecurityCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetTwoDigitYearMax(int calID);
// Call native side to load our calendar data
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
private static extern bool nativeGetCalendarData(CalendarData data, String localeName, int calendar);
// Call native side to figure out which calendars are allowed
[System.Security.SecuritySafeCritical] // auto-generated
[ResourceExposure(ResourceScope.None)]
[MethodImplAttribute(MethodImplOptions.InternalCall)]
internal static extern int nativeGetCalendars(String localeName, bool useUserOverride, [In, Out] int[] calendars);
}
}
| |
// ********************************************************************************************************
// Product Name: DotSpatial.Projection
// Description: The basic module for MapWindow version 6.0
// ********************************************************************************************************
//
// The Original Code is from MapWindow.dll version 6.0
//
// The Initial Developer of this Original Code is Ted Dunsford. Created 7/24/2009 9:10:23 AM
//
// Contributor(s): (Open source contributors should list themselves and their modifications here).
// Name | Date | Comment
// --------------------|------------|------------------------------------------------------------
// Ted Dunsford | 5/3/2010 | Updated project to DotSpatial.Projection and license to LGPL
// ********************************************************************************************************
using System;
namespace DotSpatial.Projections
{
/// <summary>
/// Contains methods for reprojection.
/// </summary>
public static class Reproject
{
#region Private Variables
private const double EPS = 1E-12;
#endregion
#region Methods
/// <summary>
/// This method reprojects the affine transform coefficients. This is used for projection on the fly,
/// where image transforms can take advantage of an affine projection, but does not have the power of
/// a full projective transform and gets less and less accurate as the image covers larger and larger
/// areas. Since most image layers represent small rectangular areas, this should not be a problem in
/// most cases. the affine array should be ordered as follows:
/// X' = [0] + [1] * Column + [2] * Row
/// Y' = [3] + [4] * Column + [5] * Row
/// </summary>
/// <param name="affine">The array of double affine coefficients.</param>
/// <param name="numRows">The number of rows to use for the lower bounds. Value of 0 or less will be set to 1.</param>
/// <param name="numCols">The number of columns to use to get the right bounds. Values of 0 or less will be set to 1.</param>
/// <param name="source"></param>
/// <param name="dest"></param>
/// <returns>The transformed coefficients</returns>
public static double[] ReprojectAffine(double[] affine, double numRows, double numCols, ProjectionInfo source, ProjectionInfo dest)
{
if (numRows <= 0) numRows = 1;
if (numCols <= 0) numCols = 1;
double[] vertices = new double[6];
// Top left
vertices[0] = affine[0];
vertices[1] = affine[3];
// Top right
vertices[2] = affine[0] + affine[1] * numCols;
vertices[3] = affine[3] + affine[4] * numCols;
// Bottom Left
vertices[4] = affine[0] + affine[2] * numRows;
vertices[5] = affine[3] + affine[5] * numRows;
double[] z = new double[3];
ReprojectPoints(vertices, z, source, dest, 0, 3);
double[] affineResult = new double[6];
affineResult[0] = vertices[0];
affineResult[1] = (vertices[2] - vertices[0]) / numCols;
affineResult[2] = (vertices[4] - vertices[0]) / numRows;
affineResult[3] = vertices[1];
affineResult[4] = (vertices[3] - vertices[1]) / numCols;
affineResult[5] = (vertices[5] - vertices[1]) / numRows;
return affineResult;
}
public static void ReprojectPoints(double[] xy, double[] z, ProjectionInfo source, ProjectionInfo dest, int startIndex, int numPoints)
{
ReprojectPoints(xy, z, source, 1.0, dest, 1.0, null, startIndex, numPoints);
}
public static void ReprojectPoints(double[] xy, double[] z, ProjectionInfo source, double srcZtoMeter, ProjectionInfo dest, double dstZtoMeter, IDatumTransform idt, int startIndex, int numPoints)
{
double toMeter = source.Unit.Meters;
// Geocentric coordinates are centered at the core of the earth. Z is up toward the north pole.
// The X axis goes from the center of the earth through Greenwich.
// The Y axis passes through 90E.
// This section converts from geocentric coordinates to geodetic ones if necessary.
if (source.IsGeocentric)
{
if (z == null)
{
throw new ProjectionException(45);
}
for (int i = startIndex; i < numPoints; i++)
{
if (toMeter != 1)
{
xy[i * 2] *= toMeter;
xy[i * 2 + 1] *= toMeter;
}
}
GeocentricGeodetic g = new GeocentricGeodetic(source.GeographicInfo.Datum.Spheroid);
g.GeocentricToGeodetic(xy, z, startIndex, numPoints);
}
// Transform source points to lam/phi if they are not already
ConvertToLatLon(source, xy, z, srcZtoMeter, startIndex, numPoints);
double fromGreenwich = source.GeographicInfo.Meridian.Longitude * source.GeographicInfo.Unit.Radians;
if (fromGreenwich != 0)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[2 * i] != double.PositiveInfinity)
xy[2 * i] += fromGreenwich;
}
}
// DATUM TRANSFORM IF NEEDED
if (idt == null)
{
if (!source.GeographicInfo.Datum.Matches(dest.GeographicInfo.Datum))
{
DatumTransform(source, dest, xy, z, startIndex, numPoints);
}
}
else
{
idt.Transform(source, dest, xy, z, startIndex, numPoints);
}
// Adjust to new prime meridian if there is one in the destination cs
fromGreenwich = dest.GeographicInfo.Meridian.Longitude * dest.GeographicInfo.Unit.Radians;
if (fromGreenwich != 0)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] != double.PositiveInfinity)
{
xy[i * 2] -= fromGreenwich;
}
}
}
if (dest.IsGeocentric)
{
if (z == null)
{
throw new ProjectionException(45);
}
GeocentricGeodetic g = new GeocentricGeodetic(dest.GeographicInfo.Datum.Spheroid);
g.GeodeticToGeocentric(xy, z, startIndex, numPoints);
double frmMeter = 1 / dest.Unit.Meters;
if (frmMeter != 1)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] != double.PositiveInfinity)
{
xy[i * 2] *= frmMeter;
xy[i * 2 + 1] *= frmMeter;
}
}
}
}
else
{
ConvertToProjected(dest, xy, z, dstZtoMeter, startIndex, numPoints);
}
}
private static void ConvertToProjected(ProjectionInfo dest, double[] xy, double[] z, double dstZtoMeter, int startIndex, int numPoints)
{
double frmMeter = 1 / dest.Unit.Meters;
double frmZMeter = 1 / dstZtoMeter;
bool geoc = dest.Geoc;
double lam0 = dest.Lam0;
double roneEs = 1 / (1 - dest.GeographicInfo.Datum.Spheroid.EccentricitySquared());
bool over = dest.Over;
double x0 = 0;
double y0 = 0;
if (dest.FalseEasting.HasValue) x0 = dest.FalseEasting.Value;
if (dest.FalseNorthing.HasValue) y0 = dest.FalseNorthing.Value;
double a = dest.GeographicInfo.Datum.Spheroid.EquatorialRadius;
for (int i = startIndex; i < numPoints; i++)
{
double lam = xy[2 * i];
double phi = xy[2 * i + 1];
double t = Math.Abs(phi) - Math.PI / 2;
if (t > EPS || Math.Abs(lam) > 10)
{
xy[2 * i] = double.PositiveInfinity;
xy[2 * i + 1] = double.PositiveInfinity;
continue;
}
if (Math.Abs(t) <= EPS)
{
xy[2 * i + 1] = phi < 0 ? -Math.PI / 2 : Math.PI / 2;
}
else if (geoc)
{
xy[2 * i + 1] = Math.Atan(roneEs * Math.Tan(phi));
}
xy[2 * i] -= lam0;
if (!over)
{
xy[2 * i] = Adjlon(xy[2 * i]);
}
}
// break this out because we don't want a chatty call to extension transforms
dest.Transform.Forward(xy, startIndex, numPoints);
if (dstZtoMeter == 1.0)
{
for (int i = startIndex; i < numPoints; i++)
{
xy[2 * i] = frmMeter * (a * xy[2 * i] + x0);
xy[2 * i + 1] = frmMeter * (a * xy[2 * i + 1] + y0);
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
xy[2 * i] = frmMeter * (a * xy[2 * i] + x0);
xy[2 * i + 1] = frmMeter * (a * xy[2 * i + 1] + y0);
z[i] *= frmZMeter;
}
}
}
private static void DatumTransform(ProjectionInfo source, ProjectionInfo dest, double[] xy, double[] z, int startIndex, int numPoints)
{
Spheroid wgs84 = new Spheroid(Proj4Ellipsoid.WGS_1984);
Datum sDatum = source.GeographicInfo.Datum;
Datum dDatum = dest.GeographicInfo.Datum;
/* -------------------------------------------------------------------- */
/* We cannot do any meaningful datum transformation if either */
/* the source or destination are of an unknown datum type */
/* (ie. only a +ellps declaration, no +datum). This is new */
/* behavior for PROJ 4.6.0. */
/* -------------------------------------------------------------------- */
if (sDatum.DatumType == DatumType.Unknown ||
dDatum.DatumType == DatumType.Unknown) return;
/* -------------------------------------------------------------------- */
/* Short cut if the datums are identical. */
/* -------------------------------------------------------------------- */
if (sDatum.Matches(dDatum)) return;
// proj4 actually allows some tollerance here
if (sDatum.DatumType == dDatum.DatumType)
{
if (sDatum.Spheroid.EquatorialRadius == dDatum.Spheroid.EquatorialRadius)
{
if (Math.Abs(sDatum.Spheroid.EccentricitySquared() - dDatum.Spheroid.EccentricitySquared()) < 0.000000000050)
{
// The tolerence is to allow GRS80 and WGS84 to escape without being transformed at all.
return;
}
}
}
double srcA = sDatum.Spheroid.EquatorialRadius;
double srcEs = sDatum.Spheroid.EccentricitySquared();
double dstA = dDatum.Spheroid.EquatorialRadius;
double dstEs = dDatum.Spheroid.EccentricitySquared();
/* -------------------------------------------------------------------- */
/* Create a temporary Z value if one is not provided. */
/* -------------------------------------------------------------------- */
if (z == null)
{
z = new double[xy.Length / 2];
}
/* -------------------------------------------------------------------- */
/* If this datum requires grid shifts, then apply it to geodetic */
/* coordinates. */
/* -------------------------------------------------------------------- */
if (sDatum.DatumType == DatumType.GridShift)
{
// pj_apply_gridshift(pj_param(srcdefn->params,"snadgrids").s, 0,
// point_count, point_offset, x, y, z );
GridShift.Apply(source.GeographicInfo.Datum.NadGrids, false, xy, startIndex, numPoints);
srcA = wgs84.EquatorialRadius;
srcEs = wgs84.EccentricitySquared();
}
if (dDatum.DatumType == DatumType.GridShift)
{
dstA = wgs84.EquatorialRadius;
dstEs = wgs84.EccentricitySquared();
}
/* ==================================================================== */
/* Do we need to go through geocentric coordinates? */
/* ==================================================================== */
if (srcEs != dstEs || srcA != dstA
|| sDatum.DatumType == DatumType.Param3
|| sDatum.DatumType == DatumType.Param7
|| dDatum.DatumType == DatumType.Param3
|| dDatum.DatumType == DatumType.Param7)
{
/* -------------------------------------------------------------------- */
/* Convert to geocentric coordinates. */
/* -------------------------------------------------------------------- */
GeocentricGeodetic gc = new GeocentricGeodetic(sDatum.Spheroid);
gc.GeodeticToGeocentric(xy, z, startIndex, numPoints);
/* -------------------------------------------------------------------- */
/* Convert between datums. */
/* -------------------------------------------------------------------- */
if (sDatum.DatumType == DatumType.Param3 || sDatum.DatumType == DatumType.Param7)
{
PjGeocentricToWgs84(source, xy, z, startIndex, numPoints);
}
if (dDatum.DatumType == DatumType.Param3 || dDatum.DatumType == DatumType.Param7)
{
PjGeocentricFromWgs84(dest, xy, z, startIndex, numPoints);
}
/* -------------------------------------------------------------------- */
/* Convert back to geodetic coordinates. */
/* -------------------------------------------------------------------- */
gc = new GeocentricGeodetic(dDatum.Spheroid);
gc.GeocentricToGeodetic(xy, z, startIndex, numPoints);
}
/* -------------------------------------------------------------------- */
/* Apply grid shift to destination if required. */
/* -------------------------------------------------------------------- */
if (dDatum.DatumType == DatumType.GridShift)
{
// pj_apply_gridshift(pj_param(dstdefn->params,"snadgrids").s, 1,
// point_count, point_offset, x, y, z );
GridShift.Apply(dest.GeographicInfo.Datum.NadGrids, true, xy, startIndex, numPoints);
}
}
private static void ConvertToLatLon(ProjectionInfo source, double[] xy, double[] z, double srcZtoMeter, int startIndex, int numPoints)
{
double toMeter = 1.0;
if (source.Unit != null) toMeter = source.Unit.Meters;
double oneEs = 1 - source.GeographicInfo.Datum.Spheroid.EccentricitySquared();
double ra = 1 / source.GeographicInfo.Datum.Spheroid.EquatorialRadius;
double x0 = 0;
if (source.FalseEasting != null) x0 = source.FalseEasting.Value;
double y0 = 0;
if (source.FalseNorthing != null) y0 = source.FalseNorthing.Value;
if (srcZtoMeter == 1.0)
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] == double.PositiveInfinity || xy[i * 2 + 1] == double.PositiveInfinity)
{
// This might be error worthy, but not sure if we want to throw an exception here
continue;
}
// descale and de-offset
xy[i * 2] = (xy[i * 2] * toMeter - x0) * ra;
xy[i * 2 + 1] = (xy[i * 2 + 1] * toMeter - y0) * ra;
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
if (xy[i * 2] == double.PositiveInfinity || xy[i * 2 + 1] == double.PositiveInfinity)
{
// This might be error worthy, but not sure if we want to throw an exception here
continue;
}
// descale and de-offset
xy[i * 2] = (xy[i * 2] * toMeter - x0) * ra;
xy[i * 2 + 1] = (xy[i * 2 + 1] * toMeter - y0) * ra;
z[i] *= srcZtoMeter;
}
}
if (source.Transform != null)
{
source.Transform.Inverse(xy, startIndex, numPoints);
}
for (int i = startIndex; i < numPoints; i++)
{
double lam0 = source.Lam0;
xy[i * 2] += lam0;
if (!source.Over)
{
xy[i*2] = Adjlon(xy[i*2]);
}
if (source.Geoc && Math.Abs(Math.Abs(xy[i * 2 + 1]) - Math.PI / 2) > EPS)
{
xy[i * 2 + 1] = Math.Atan(oneEs * Math.Tan(xy[i * 2 + 1]));
}
}
}
private static double Adjlon(double lon)
{
if (Math.Abs(lon) <= Math.PI + Math.PI / 72) return (lon);
lon += Math.PI; /* adjust to 0..2pi rad */
lon -= 2 * Math.PI * Math.Floor(lon / (2 * Math.PI)); /* remove integral # of 'revolutions'*/
lon -= Math.PI; /* adjust back to -pi..pi rad */
return (lon);
}
private static void PjGeocentricToWgs84(ProjectionInfo source, double[] xy, double[] zArr, int startIndex, int numPoints)
{
double[] shift = source.GeographicInfo.Datum.ToWGS84;
if (source.GeographicInfo.Datum.DatumType == DatumType.Param3)
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
xy[2 * i] = xy[2 * i] + shift[0]; // dx
xy[2 * i + 1] = xy[2 * i + 1] + shift[1]; // dy
zArr[i] = zArr[i] + shift[2];
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
double x = xy[2 * i];
double y = xy[2 * i + 1];
double z = zArr[i];
xy[2 * i] = shift[6] * (x - shift[5] * y + shift[4] * z) + shift[0];
xy[2 * i + 1] = shift[6] * (shift[5] * x + y - shift[3] * z) + shift[1];
zArr[i] = shift[6] * (-shift[4] * x + shift[3] * y + z) + shift[2];
}
}
}
private static void PjGeocentricFromWgs84(ProjectionInfo dest, double[] xy, double[] zArr, int startIndex, int numPoints)
{
double[] shift = dest.GeographicInfo.Datum.ToWGS84;
if (dest.GeographicInfo.Datum.DatumType == DatumType.Param3)
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
xy[2 * i] = xy[2 * i] - shift[0]; // dx
xy[2 * i + 1] = xy[2 * i + 1] - shift[1]; // dy
zArr[i] = zArr[i] - shift[2];
}
}
else
{
for (int i = startIndex; i < numPoints; i++)
{
if (double.IsNaN(xy[2 * i]) || double.IsNaN(xy[2 * i + 1])) continue;
double x = (xy[2 * i] - shift[0]) / shift[6];
double y = (xy[2 * i + 1] - shift[1]) / shift[6];
double z = (zArr[i] - shift[2]) / shift[6];
xy[2 * i] = x + shift[5] * y - shift[4] * z;
xy[2 * i + 1] = -shift[5] * x + y + shift[3] * z;
zArr[i] = shift[4] * x - shift[3] * y + z;
}
}
}
#endregion
}
}
| |
//
// Copyright (c) 2004-2017 Jaroslaw Kowalski <[email protected]>, 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.Wrappers
{
using System;
using System.ComponentModel;
using System.Threading;
using Common;
using Internal;
/// <summary>
/// Provides asynchronous, buffered execution of target writes.
/// </summary>
/// <seealso href="https://github.com/nlog/nlog/wiki/AsyncWrapper-target">Documentation on NLog Wiki</seealso>
/// <remarks>
/// <p>
/// Asynchronous target wrapper allows the logger code to execute more quickly, by queueing
/// messages and processing them in a separate thread. You should wrap targets
/// that spend a non-trivial amount of time in their Write() method with asynchronous
/// target to speed up logging.
/// </p>
/// <p>
/// Because asynchronous logging is quite a common scenario, NLog supports a
/// shorthand notation for wrapping all targets with AsyncWrapper. Just add async="true" to
/// the <targets/> element in the configuration file.
/// </p>
/// <code lang="XML">
/// <![CDATA[
/// <targets async="true">
/// ... your targets go here ...
/// </targets>
/// ]]></code>
/// </remarks>
/// <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/AsyncWrapper/NLog.config" />
/// <p>
/// The above examples assume just one target and a single rule. See below for
/// a programmatic configuration that's equivalent to the above config file:
/// </p>
/// <code lang="C#" source="examples/targets/Configuration API/AsyncWrapper/Wrapping File/Example.cs" />
/// </example>
[Target("AsyncWrapper", IsWrapper = true)]
public class AsyncTargetWrapper : WrapperTargetBase
{
private readonly object _writeLockObject = new object();
private readonly object _timerLockObject = new object();
private Timer _lazyWriterTimer;
private readonly ReusableAsyncLogEventList _reusableAsyncLogEventList = new ReusableAsyncLogEventList(200);
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
public AsyncTargetWrapper()
: this(null)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="name">Name of the target.</param>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(string name, Target wrappedTarget)
: this(wrappedTarget)
{
this.Name = name;
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
public AsyncTargetWrapper(Target wrappedTarget)
: this(wrappedTarget, 10000, AsyncTargetWrapperOverflowAction.Discard)
{
}
/// <summary>
/// Initializes a new instance of the <see cref="AsyncTargetWrapper" /> class.
/// </summary>
/// <param name="wrappedTarget">The wrapped target.</param>
/// <param name="queueLimit">Maximum number of requests in the queue.</param>
/// <param name="overflowAction">The action to be taken when the queue overflows.</param>
public AsyncTargetWrapper(Target wrappedTarget, int queueLimit, AsyncTargetWrapperOverflowAction overflowAction)
{
this.RequestQueue = new AsyncRequestQueue(10000, AsyncTargetWrapperOverflowAction.Discard);
this.TimeToSleepBetweenBatches = 50;
this.BatchSize = 200;
this.FullBatchSizeWriteLimit = 5;
this.WrappedTarget = wrappedTarget;
this.QueueLimit = queueLimit;
this.OverflowAction = overflowAction;
}
/// <summary>
/// Gets or sets the number of log events that should be processed in a batch
/// by the lazy writer thread.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(200)]
public int BatchSize { get; set; }
/// <summary>
/// Gets or sets the time in milliseconds to sleep between batches.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(50)]
public int TimeToSleepBetweenBatches { get; set; }
/// <summary>
/// Gets or sets the action to be taken when the lazy writer thread request queue count
/// exceeds the set limit.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue("Discard")]
public AsyncTargetWrapperOverflowAction OverflowAction
{
get { return this.RequestQueue.OnOverflow; }
set { this.RequestQueue.OnOverflow = value; }
}
/// <summary>
/// Gets or sets the limit on the number of requests in the lazy writer thread request queue.
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(10000)]
public int QueueLimit
{
get { return this.RequestQueue.RequestLimit; }
set { this.RequestQueue.RequestLimit = value; }
}
/// <summary>
/// Gets or sets the limit of full <see cref="BatchSize"/>s to write before yielding into <see cref="TimeToSleepBetweenBatches"/>
/// Performance is better when writing many small batches, than writing a single large batch
/// </summary>
/// <docgen category='Buffering Options' order='100' />
[DefaultValue(5)]
public int FullBatchSizeWriteLimit { get; set; }
/// <summary>
/// Gets the queue of lazy writer thread requests.
/// </summary>
internal AsyncRequestQueue RequestQueue { get; private set; }
/// <summary>
/// Schedules a flush of pending events in the queue (if any), followed by flushing the WrappedTarget.
/// </summary>
/// <param name="asyncContinuation">The asynchronous continuation.</param>
protected override void FlushAsync(AsyncContinuation asyncContinuation)
{
if (_flushEventsInQueueDelegate == null)
_flushEventsInQueueDelegate = FlushEventsInQueue;
ThreadPool.QueueUserWorkItem(_flushEventsInQueueDelegate, asyncContinuation);
}
private WaitCallback _flushEventsInQueueDelegate;
/// <summary>
/// Initializes the target by starting the lazy writer timer.
/// </summary>
protected override void InitializeTarget()
{
base.InitializeTarget();
if (!OptimizeBufferReuse && WrappedTarget != null && WrappedTarget.OptimizeBufferReuse)
OptimizeBufferReuse = GetType() == typeof(AsyncTargetWrapper); // TODO NLog 5 - Manual Opt-Out
this.RequestQueue.Clear();
InternalLogger.Trace("AsyncWrapper '{0}': start timer", this.Name);
this._lazyWriterTimer = new Timer(this.ProcessPendingEvents, null, Timeout.Infinite, Timeout.Infinite);
this.StartLazyWriterTimer();
}
/// <summary>
/// Shuts down the lazy writer timer.
/// </summary>
protected override void CloseTarget()
{
this.StopLazyWriterThread();
if (Monitor.TryEnter(this._writeLockObject, 500))
{
try
{
WriteEventsInQueue(int.MaxValue, "Closing Target");
}
finally
{
Monitor.Exit(this._writeLockObject);
}
}
base.CloseTarget();
}
/// <summary>
/// Starts the lazy writer thread which periodically writes
/// queued log messages.
/// </summary>
protected virtual void StartLazyWriterTimer()
{
lock (this._timerLockObject)
{
if (this._lazyWriterTimer != null)
{
if (this.TimeToSleepBetweenBatches <= 0)
{
InternalLogger.Trace("AsyncWrapper '{0}': Throttled timer scheduled", this.Name);
this._lazyWriterTimer.Change(1, Timeout.Infinite);
}
else
{
this._lazyWriterTimer.Change(this.TimeToSleepBetweenBatches, Timeout.Infinite);
}
}
}
}
/// <summary>
/// Attempts to start an instant timer-worker-thread which can write
/// queued log messages.
/// </summary>
/// <returns>Returns true when scheduled a timer-worker-thread</returns>
protected virtual bool StartInstantWriterTimer()
{
bool lockTaken = false;
try
{
lockTaken = Monitor.TryEnter(this._writeLockObject);
if (lockTaken)
{
// Lock taken means no timer-worker-thread is active writing, schedule timer now
lock (this._timerLockObject)
{
if (this._lazyWriterTimer != null)
{
// Not optimal to shedule timer-worker-thread while holding lock,
// as the newly scheduled timer-worker-thread will hammer into the writeLockObject
this._lazyWriterTimer.Change(0, Timeout.Infinite);
return true;
}
}
}
return false;
}
finally
{
// If not able to take lock, then it means timer-worker-thread is already active,
// and timer-worker-thread will check RequestQueue after leaving writeLockObject
if (lockTaken)
Monitor.Exit(this._writeLockObject);
}
}
/// <summary>
/// Stops the lazy writer thread.
/// </summary>
protected virtual void StopLazyWriterThread()
{
lock (this._timerLockObject)
{
var currentTimer = this._lazyWriterTimer;
if (currentTimer != null)
{
this._lazyWriterTimer = null;
currentTimer.WaitForDispose(TimeSpan.FromSeconds(1));
}
}
}
/// <summary>
/// Adds the log event to asynchronous queue to be processed by
/// the lazy writer thread.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <remarks>
/// The <see cref="Target.PrecalculateVolatileLayouts"/> is called
/// to ensure that the log event can be processed in another thread.
/// </remarks>
protected override void Write(AsyncLogEventInfo logEvent)
{
this.MergeEventProperties(logEvent.LogEvent);
this.PrecalculateVolatileLayouts(logEvent.LogEvent);
bool queueWasEmpty = this.RequestQueue.Enqueue(logEvent);
if (queueWasEmpty && this.TimeToSleepBetweenBatches <= 0)
StartInstantWriterTimer();
}
/// <summary>
/// Write to queue without locking <see cref="Target.SyncRoot"/>
/// </summary>
/// <param name="logEvent"></param>
protected override void WriteAsyncThreadSafe(AsyncLogEventInfo logEvent)
{
try
{
this.Write(logEvent);
}
catch (Exception exception)
{
if (exception.MustBeRethrown())
{
throw;
}
logEvent.Continuation(exception);
}
}
private void ProcessPendingEvents(object state)
{
if (this._lazyWriterTimer == null)
return;
bool wroteFullBatchSize = false;
try
{
lock (this._writeLockObject)
{
int count = WriteEventsInQueue(this.BatchSize, "Timer");
if (count == this.BatchSize)
wroteFullBatchSize = true;
if (wroteFullBatchSize && this.TimeToSleepBetweenBatches <= 0)
this.StartInstantWriterTimer(); // Found full batch, fast schedule to take next batch (within lock to avoid pile up)
}
}
catch (Exception exception)
{
wroteFullBatchSize = false; // Something went wrong, lets throttle retry
InternalLogger.Error(exception, "AsyncWrapper '{0}': Error in lazy writer timer procedure.", this.Name);
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
}
finally
{
if (this.TimeToSleepBetweenBatches <= 0)
{
// If queue was not empty, then more might have arrived while writing the first batch
// Uses throttled timer here, so we can process in batches (faster)
if (!wroteFullBatchSize && this.RequestQueue.RequestCount > 0)
this.StartLazyWriterTimer(); // Queue was checked as empty, but now we have more
}
else
{
this.StartLazyWriterTimer();
}
}
}
private void FlushEventsInQueue(object state)
{
try
{
var asyncContinuation = state as AsyncContinuation;
lock (this._writeLockObject)
{
WriteEventsInQueue(int.MaxValue, "Flush Async");
if (asyncContinuation != null)
base.FlushAsync(asyncContinuation);
}
if (this.TimeToSleepBetweenBatches <= 0 && this.RequestQueue.RequestCount > 0)
this.StartLazyWriterTimer(); // Queue was checked as empty, but now we have more
}
catch (Exception exception)
{
InternalLogger.Error(exception, "AsyncWrapper '{0}': Error in flush procedure.", this.Name);
if (exception.MustBeRethrownImmediately())
{
throw; // Throwing exceptions here will crash the entire application (.NET 2.0 behavior)
}
}
}
private int WriteEventsInQueue(int batchSize, string reason)
{
if (this.WrappedTarget == null)
{
InternalLogger.Error("AsyncWrapper '{0}': WrappedTarget is NULL", this.Name);
return 0;
}
int count = 0;
for (int i = 0; i < this.FullBatchSizeWriteLimit; ++i)
{
if (!this.OptimizeBufferReuse || batchSize == int.MaxValue)
{
var logEvents = this.RequestQueue.DequeueBatch(batchSize);
if (logEvents.Length > 0)
{
if (reason != null)
InternalLogger.Trace("AsyncWrapper '{0}': writing {1} events ({2})", this.Name, logEvents.Length, reason);
this.WrappedTarget.WriteAsyncLogEvents(logEvents);
}
count = logEvents.Length;
}
else
{
using (var targetList = this._reusableAsyncLogEventList.Allocate())
{
var logEvents = targetList.Result;
this.RequestQueue.DequeueBatch(batchSize, logEvents);
if (logEvents.Count > 0)
{
if (reason != null)
InternalLogger.Trace("AsyncWrapper '{0}': writing {1} events ({2})", this.Name, logEvents.Count, reason);
this.WrappedTarget.WriteAsyncLogEvents(logEvents);
}
count = logEvents.Count;
}
}
if (count < batchSize)
break;
}
return count;
}
}
}
| |
using System;
/// <summary>
/// Convert.ToUInt64(String,Int32)
/// </summary>
public class ConvertToUInt6418
{
public static int Main()
{
ConvertToUInt6418 convertToUInt6418 = new ConvertToUInt6418();
TestLibrary.TestFramework.BeginTestCase("ConvertToUInt6418");
if (convertToUInt6418.RunTests())
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("PASS");
return 100;
}
else
{
TestLibrary.TestFramework.EndTestCase();
TestLibrary.TestFramework.LogInformation("FAIL");
return 0;
}
}
public bool RunTests()
{
bool retVal = true;
TestLibrary.TestFramework.LogInformation("[Positive]");
retVal = PosTest1() && retVal;
retVal = PosTest2() && retVal;
retVal = PosTest3() && retVal;
retVal = PosTest4() && retVal;
TestLibrary.TestFramework.LogInformation("[Negative]");
retVal = NegTest1() && retVal;
retVal = NegTest2() && retVal;
retVal = NegTest3() && retVal;
retVal = NegTest4() && retVal;
retVal = NegTest5() && retVal;
retVal = NegTest6() && retVal;
retVal = NegTest7() && retVal;
retVal = NegTest8() && retVal;
return retVal;
}
#region PositiveTest
public bool PosTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest1: Convert to UInt64 from string 1");
try
{
string strVal = "1111";
ulong ulongVal1 = Convert.ToUInt64(strVal, 2);
ulong ulongVal2 = Convert.ToUInt64(strVal, 8);
ulong ulongVal3 = Convert.ToUInt64(strVal, 10);
ulong ulongVal4 = Convert.ToUInt64(strVal, 16);
if (ulongVal1 != (UInt64)(1 * Math.Pow(2, 3) + 1 * Math.Pow(2, 2) + 1 * Math.Pow(2, 1) + 1 * Math.Pow(2, 0)) ||
ulongVal2 != (UInt64)(1 * Math.Pow(8, 3) + 1 * Math.Pow(8, 2) + 1 * Math.Pow(8, 1) + 1 * Math.Pow(8, 0)) ||
ulongVal3 != (UInt64)(1 * Math.Pow(10, 3) + 1 * Math.Pow(10, 2) + 1 * Math.Pow(10, 1) + 1 * Math.Pow(10, 0)) ||
ulongVal4 != (UInt64)(1 * Math.Pow(16, 3) + 1 * Math.Pow(16, 2) + 1 * Math.Pow(16, 1) + 1 * Math.Pow(16, 0))
)
{
TestLibrary.TestFramework.LogError("001", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest2: Convert to UInt64 from string 2");
try
{
ulong sourceVal = (UInt64)TestLibrary.Generator.GetInt64(-55);
string strVal = "+" + sourceVal.ToString();
ulong ulongVal = Convert.ToUInt64(strVal, 10);
if (ulongVal != sourceVal)
{
TestLibrary.TestFramework.LogError("003", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest3: Convert to UInt64 from string 3");
try
{
string strVal = null;
ulong ulongVal1 = Convert.ToUInt64(strVal, 2);
ulong ulongVal2 = Convert.ToUInt64(strVal, 8);
ulong ulongVal3 = Convert.ToUInt64(strVal, 10);
ulong ulongVal4 = Convert.ToUInt64(strVal, 16);
if (ulongVal1 != 0 || ulongVal2 != 0 || ulongVal3 != 0 || ulongVal4 != 0)
{
TestLibrary.TestFramework.LogError("005", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool PosTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("PosTest4: Convert to UInt64 from string 4");
try
{
string strVal = "0xff";
ulong ulongVal = Convert.ToUInt64(strVal, 16);
if (ulongVal != (UInt64)(15 * Math.Pow(16, 1) + 15 * Math.Pow(16, 0)))
{
TestLibrary.TestFramework.LogError("007", "The ExpectResult is not the ActualResult");
retVal = false;
}
}
catch (Exception e)
{
TestLibrary.TestFramework.LogError("008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region NegativeTest
public bool NegTest1()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest1: the parameter of fromBase is not 2, 8, 10, or 16");
try
{
string strVal = "1111";
ulong ulongVal = Convert.ToUInt64(strVal, 100);
TestLibrary.TestFramework.LogError("N001", "the parameter of fromBase is not 2, 8, 10, or 16 but not throw exception");
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N002", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest2()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest2: the string represents a non-base 10 signed number and is prefixed with a negative sign");
try
{
string strVal = "-0";
ulong ulongVal = Convert.ToUInt64(strVal, 2);
TestLibrary.TestFramework.LogError("N003", "the string represents a non-base 10 signed number and is prefixed with a negative sign but not throw exception");
retVal = false;
}
catch (ArgumentException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N004", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest3()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest3: the string contains a character that is not a valid digit in the base specified by fromBase param 1");
try
{
string strVal = "1234";
ulong ulongVal = Convert.ToUInt64(strVal, 2);
TestLibrary.TestFramework.LogError("N005", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N006", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest4()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest4: the string contains a character that is not a valid digit in the base specified by fromBase param 2");
try
{
string strVal = "9999";
ulong ulongVal = Convert.ToUInt64(strVal, 8);
TestLibrary.TestFramework.LogError("N007", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N008", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest5()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest5: the string contains a character that is not a valid digit in the base specified by fromBase param 3");
try
{
string strVal = "abcd";
ulong ulongVal = Convert.ToUInt64(strVal, 10);
TestLibrary.TestFramework.LogError("N009", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N010", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest6()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest6: the string contains a character that is not a valid digit in the base specified by fromBase param 4");
try
{
string strVal = "gh";
ulong ulongVal = Convert.ToUInt64(strVal, 16);
TestLibrary.TestFramework.LogError("N011", "the string contains a character that is not a valid digit in the base specified by fromBase param but not throw exception");
retVal = false;
}
catch (FormatException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N012", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest7()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest7: the string represents base 10 number is less than UInt64.minValue");
try
{
int intVal = this.GetInt32(1, Int32.MaxValue);
string strVal = "-" + intVal.ToString();
ulong ulongVal = Convert.ToUInt64(strVal, 10);
TestLibrary.TestFramework.LogError("N013", "the string represent base 10 number is less than UInt64.minValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N014", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
public bool NegTest8()
{
bool retVal = true;
TestLibrary.TestFramework.BeginScenario("NegTest8: the string represents base 10 number is greater than UInt64.maxValue");
try
{
string strVal = UInt64.MaxValue.ToString() + "1";
ulong ulongVal = Convert.ToUInt64(strVal, 10);
TestLibrary.TestFramework.LogError("N015", "the string represent base 10 number is greater than UInt64.maxValue but not throw exception");
retVal = false;
}
catch (OverflowException) { }
catch (Exception e)
{
TestLibrary.TestFramework.LogError("N016", "Unexpect exception:" + e);
retVal = false;
}
return retVal;
}
#endregion
#region HelpMethod
private Int32 GetInt32(Int32 minValue, Int32 maxValue)
{
try
{
if (minValue == maxValue)
{
return minValue;
}
if (minValue < maxValue)
{
return minValue + TestLibrary.Generator.GetInt32(-55) % (maxValue - minValue);
}
}
catch
{
throw;
}
return minValue;
}
#endregion
}
| |
/*
* 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.IO;
using System.Reflection;
using System.Net;
using System.Text;
using OpenSim.Server.Base;
using OpenSim.Server.Handlers.Base;
using OpenSim.Services.Interfaces;
using OpenSim.Framework;
using OpenSim.Framework.Servers.HttpServer;
using GridRegion = OpenSim.Services.Interfaces.GridRegion;
using OpenMetaverse;
using OpenMetaverse.StructuredData;
using Nini.Config;
using log4net;
namespace OpenSim.Server.Handlers.Neighbour
{
public class NeighbourGetHandler : BaseStreamHandler
{
// TODO: unused: private ISimulationService m_SimulationService;
// TODO: unused: private IAuthenticationService m_AuthenticationService;
public NeighbourGetHandler(INeighbourService service, IAuthenticationService authentication) :
base("GET", "/region")
{
// TODO: unused: m_SimulationService = service;
// TODO: unused: m_AuthenticationService = authentication;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// Not implemented yet
Console.WriteLine("--- Get region --- " + path);
httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
return new byte[] { };
}
}
public class NeighbourPostHandler : BaseStreamHandler
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private INeighbourService m_NeighbourService;
private IAuthenticationService m_AuthenticationService;
// TODO: unused: private bool m_AllowForeignGuests;
public NeighbourPostHandler(INeighbourService service, IAuthenticationService authentication) :
base("POST", "/region")
{
m_NeighbourService = service;
m_AuthenticationService = authentication;
// TODO: unused: m_AllowForeignGuests = foreignGuests;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
byte[] result = new byte[0];
UUID regionID;
string action;
ulong regionHandle;
if (RestHandlerUtils.GetParams(path, out regionID, out regionHandle, out action))
{
m_log.InfoFormat("[RegionPostHandler]: Invalid parameters for neighbour message {0}", path);
httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
httpResponse.StatusDescription = "Invalid parameters for neighbour message " + path;
return result;
}
if (m_AuthenticationService != null)
{
// Authentication
string authority = string.Empty;
string authToken = string.Empty;
if (!RestHandlerUtils.GetAuthentication(httpRequest, out authority, out authToken))
{
m_log.InfoFormat("[RegionPostHandler]: Authentication failed for neighbour message {0}", path);
httpResponse.StatusCode = (int)HttpStatusCode.Unauthorized;
return result;
}
// TODO: Rethink this
//if (!m_AuthenticationService.VerifyKey(regionID, authToken))
//{
// m_log.InfoFormat("[RegionPostHandler]: Authentication failed for neighbour message {0}", path);
// httpResponse.StatusCode = (int)HttpStatusCode.Forbidden;
// return result;
//}
m_log.DebugFormat("[RegionPostHandler]: Authentication succeeded for {0}", regionID);
}
OSDMap args = Util.GetOSDMap(request, (int)httpRequest.ContentLength);
if (args == null)
{
httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
httpResponse.StatusDescription = "Unable to retrieve data";
m_log.DebugFormat("[RegionPostHandler]: Unable to retrieve data for post {0}", path);
return result;
}
// retrieve the regionhandle
ulong regionhandle = 0;
if (args["destination_handle"] != null)
UInt64.TryParse(args["destination_handle"].AsString(), out regionhandle);
RegionInfo aRegion = new RegionInfo();
try
{
aRegion.UnpackRegionInfoData(args);
}
catch (Exception ex)
{
m_log.InfoFormat("[RegionPostHandler]: exception on unpacking region info {0}", ex.Message);
httpResponse.StatusCode = (int)HttpStatusCode.BadRequest;
httpResponse.StatusDescription = "Problems with data deserialization";
return result;
}
// Finally!
GridRegion thisRegion = m_NeighbourService.HelloNeighbour(regionhandle, aRegion);
OSDMap resp = new OSDMap(1);
if (thisRegion != null)
resp["success"] = OSD.FromBoolean(true);
else
resp["success"] = OSD.FromBoolean(false);
httpResponse.StatusCode = (int)HttpStatusCode.OK;
return Util.UTF8.GetBytes(OSDParser.SerializeJsonString(resp));
}
}
public class NeighbourPutHandler : BaseStreamHandler
{
// TODO: unused: private ISimulationService m_SimulationService;
// TODO: unused: private IAuthenticationService m_AuthenticationService;
public NeighbourPutHandler(INeighbourService service, IAuthenticationService authentication) :
base("PUT", "/region")
{
// TODO: unused: m_SimulationService = service;
// TODO: unused: m_AuthenticationService = authentication;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// Not implemented yet
httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
return new byte[] { };
}
}
public class NeighbourDeleteHandler : BaseStreamHandler
{
// TODO: unused: private ISimulationService m_SimulationService;
// TODO: unused: private IAuthenticationService m_AuthenticationService;
public NeighbourDeleteHandler(INeighbourService service, IAuthenticationService authentication) :
base("DELETE", "/region")
{
// TODO: unused: m_SimulationService = service;
// TODO: unused: m_AuthenticationService = authentication;
}
public override byte[] Handle(string path, Stream request,
OSHttpRequest httpRequest, OSHttpResponse httpResponse)
{
// Not implemented yet
httpResponse.StatusCode = (int)HttpStatusCode.NotImplemented;
return new byte[] { };
}
}
}
| |
/*
* 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.Reflection;
using System.Timers;
using log4net;
using Nini.Config;
using OpenMetaverse;
using OpenSim.Data;
using OpenSim.Framework;
using OpenSim.Services.Interfaces;
namespace OpenSim.Groups
{
public class HGGroupsService : GroupsService
{
private static readonly ILog m_log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);
private IOfflineIMService m_OfflineIM;
private IUserAccountService m_UserAccounts;
private string m_HomeURI;
public HGGroupsService(IConfigSource config, IOfflineIMService im, IUserAccountService users, string homeURI)
: base(config, string.Empty)
{
m_OfflineIM = im;
m_UserAccounts = users;
m_HomeURI = homeURI;
if (!m_HomeURI.EndsWith("/"))
m_HomeURI += "/";
}
#region HG specific operations
public bool CreateGroupProxy(string RequestingAgentID, string agentID, string accessToken, UUID groupID, string serviceLocation, string name, out string reason)
{
reason = string.Empty;
Uri uri = null;
try
{
uri = new Uri(serviceLocation);
}
catch (UriFormatException)
{
reason = "Bad location for group proxy";
return false;
}
// Check if it already exists
GroupData grec = m_Database.RetrieveGroup(groupID);
if (grec == null ||
(grec != null && grec.Data["Location"] != string.Empty && grec.Data["Location"].ToLower() != serviceLocation.ToLower()))
{
// Create the group
grec = new GroupData();
grec.GroupID = groupID;
grec.Data = new Dictionary<string, string>();
grec.Data["Name"] = name + " @ " + uri.Authority;
grec.Data["Location"] = serviceLocation;
grec.Data["Charter"] = string.Empty;
grec.Data["InsigniaID"] = UUID.Zero.ToString();
grec.Data["FounderID"] = UUID.Zero.ToString();
grec.Data["MembershipFee"] = "0";
grec.Data["OpenEnrollment"] = "0";
grec.Data["ShowInList"] = "0";
grec.Data["AllowPublish"] = "0";
grec.Data["MaturePublish"] = "0";
grec.Data["OwnerRoleID"] = UUID.Zero.ToString();
if (!m_Database.StoreGroup(grec))
return false;
}
if (grec.Data["Location"] == string.Empty)
{
reason = "Cannot add proxy membership to non-proxy group";
return false;
}
UUID uid = UUID.Zero;
string url = string.Empty, first = string.Empty, last = string.Empty, tmp = string.Empty;
Util.ParseUniversalUserIdentifier(RequestingAgentID, out uid, out url, out first, out last, out tmp);
string fromName = first + "." + last + "@" + url;
// Invite to group again
InviteToGroup(fromName, groupID, new UUID(agentID), grec.Data["Name"]);
// Stick the proxy membership in the DB already
// we'll delete it if the agent declines the invitation
MembershipData membership = new MembershipData();
membership.PrincipalID = agentID;
membership.GroupID = groupID;
membership.Data = new Dictionary<string, string>();
membership.Data["SelectedRoleID"] = UUID.Zero.ToString();
membership.Data["Contribution"] = "0";
membership.Data["ListInProfile"] = "1";
membership.Data["AcceptNotices"] = "1";
membership.Data["AccessToken"] = accessToken;
m_Database.StoreMember(membership);
return true;
}
public void RemoveAgentFromGroup(string RequestingAgentID, string AgentID, UUID GroupID, string token)
{
// check the token
MembershipData membership = m_Database.RetrieveMember(GroupID, AgentID);
if (membership != null)
{
if (token != string.Empty && token.Equals(membership.Data["AccessToken"]))
RemoveAgentFromGroup(RequestingAgentID, AgentID, GroupID);
else
m_log.DebugFormat("[Groups.HGGroupsService]: access token {0} did not match stored one {1}", token, membership.Data["AccessToken"]);
}
else
m_log.DebugFormat("[Groups.HGGroupsService]: membership not found for {0}", AgentID);
}
public ExtendedGroupRecord GetGroupRecord(string RequestingAgentID, UUID GroupID, string groupName, string token)
{
// check the token
if (!VerifyToken(GroupID, RequestingAgentID, token))
return null;
ExtendedGroupRecord grec;
if (GroupID == UUID.Zero)
grec = GetGroupRecord(RequestingAgentID, groupName);
else
grec = GetGroupRecord(RequestingAgentID, GroupID);
if (grec != null)
FillFounderUUI(grec);
return grec;
}
public List<ExtendedGroupMembersData> GetGroupMembers(string RequestingAgentID, UUID GroupID, string token)
{
if (!VerifyToken(GroupID, RequestingAgentID, token))
return new List<ExtendedGroupMembersData>();
List<ExtendedGroupMembersData> members = GetGroupMembers(RequestingAgentID, GroupID);
// convert UUIDs to UUIs
members.ForEach(delegate (ExtendedGroupMembersData m)
{
if (m.AgentID.ToString().Length == 36) // UUID
{
UserAccount account = m_UserAccounts.GetUserAccount(UUID.Zero, new UUID(m.AgentID));
if (account != null)
m.AgentID = Util.UniversalIdentifier(account.PrincipalID, account.FirstName, account.LastName, m_HomeURI);
}
});
return members;
}
public List<GroupRolesData> GetGroupRoles(string RequestingAgentID, UUID GroupID, string token)
{
if (!VerifyToken(GroupID, RequestingAgentID, token))
return new List<GroupRolesData>();
return GetGroupRoles(RequestingAgentID, GroupID);
}
public List<ExtendedGroupRoleMembersData> GetGroupRoleMembers(string RequestingAgentID, UUID GroupID, string token)
{
if (!VerifyToken(GroupID, RequestingAgentID, token))
return new List<ExtendedGroupRoleMembersData>();
List<ExtendedGroupRoleMembersData> rolemembers = GetGroupRoleMembers(RequestingAgentID, GroupID);
// convert UUIDs to UUIs
rolemembers.ForEach(delegate(ExtendedGroupRoleMembersData m)
{
if (m.MemberID.ToString().Length == 36) // UUID
{
UserAccount account = m_UserAccounts.GetUserAccount(UUID.Zero, new UUID(m.MemberID));
if (account != null)
m.MemberID = Util.UniversalIdentifier(account.PrincipalID, account.FirstName, account.LastName, m_HomeURI);
}
});
return rolemembers;
}
public bool AddNotice(string RequestingAgentID, UUID groupID, UUID noticeID, string fromName, string subject, string message,
bool hasAttachment, byte attType, string attName, UUID attItemID, string attOwnerID)
{
// check that the group proxy exists
ExtendedGroupRecord grec = GetGroupRecord(RequestingAgentID, groupID);
if (grec == null)
{
m_log.DebugFormat("[Groups.HGGroupsService]: attempt at adding notice to non-existent group proxy");
return false;
}
// check that the group is remote
if (grec.ServiceLocation == string.Empty)
{
m_log.DebugFormat("[Groups.HGGroupsService]: attempt at adding notice to local (non-proxy) group");
return false;
}
// check that there isn't already a notice with the same ID
if (GetGroupNotice(RequestingAgentID, noticeID) != null)
{
m_log.DebugFormat("[Groups.HGGroupsService]: a notice with the same ID already exists", grec.ServiceLocation);
return false;
}
// This has good intentions (security) but it will potentially DDS the origin...
// We'll need to send a proof along with the message. Maybe encrypt the message
// using key pairs
//
//// check that the notice actually exists in the origin
//GroupsServiceHGConnector c = new GroupsServiceHGConnector(grec.ServiceLocation);
//if (!c.VerifyNotice(noticeID, groupID))
//{
// m_log.DebugFormat("[Groups.HGGroupsService]: notice does not exist at origin {0}", grec.ServiceLocation);
// return false;
//}
// ok, we're good!
return _AddNotice(groupID, noticeID, fromName, subject, message, hasAttachment, attType, attName, attItemID, attOwnerID);
}
public bool VerifyNotice(UUID noticeID, UUID groupID)
{
GroupNoticeInfo notice = GetGroupNotice(string.Empty, noticeID);
if (notice == null)
return false;
if (notice.GroupID != groupID)
return false;
return true;
}
#endregion
private void InviteToGroup(string fromName, UUID groupID, UUID invitedAgentID, string groupName)
{
// Todo: Security check, probably also want to send some kind of notification
UUID InviteID = UUID.Random();
if (AddAgentToGroupInvite(InviteID, groupID, invitedAgentID.ToString()))
{
Guid inviteUUID = InviteID.Guid;
GridInstantMessage msg = new GridInstantMessage();
msg.imSessionID = inviteUUID;
// msg.fromAgentID = agentID.Guid;
msg.fromAgentID = groupID.Guid;
msg.toAgentID = invitedAgentID.Guid;
//msg.timestamp = (uint)Util.UnixTimeSinceEpoch();
msg.timestamp = 0;
msg.fromAgentName = fromName;
msg.message = string.Format("Please confirm your acceptance to join group {0}.", groupName);
msg.dialog = (byte)OpenMetaverse.InstantMessageDialog.GroupInvitation;
msg.fromGroup = true;
msg.offline = (byte)0;
msg.ParentEstateID = 0;
msg.Position = Vector3.Zero;
msg.RegionID = UUID.Zero.Guid;
msg.binaryBucket = new byte[20];
string reason = string.Empty;
m_OfflineIM.StoreMessage(msg, out reason);
}
}
private bool AddAgentToGroupInvite(UUID inviteID, UUID groupID, string agentID)
{
// Check whether the invitee is already a member of the group
MembershipData m = m_Database.RetrieveMember(groupID, agentID);
if (m != null)
return false;
// Check whether there are pending invitations and delete them
InvitationData invite = m_Database.RetrieveInvitation(groupID, agentID);
if (invite != null)
m_Database.DeleteInvite(invite.InviteID);
invite = new InvitationData();
invite.InviteID = inviteID;
invite.PrincipalID = agentID;
invite.GroupID = groupID;
invite.RoleID = UUID.Zero;
invite.Data = new Dictionary<string, string>();
return m_Database.StoreInvitation(invite);
}
private void FillFounderUUI(ExtendedGroupRecord grec)
{
UserAccount account = m_UserAccounts.GetUserAccount(UUID.Zero, grec.FounderID);
if (account != null)
grec.FounderUUI = Util.UniversalIdentifier(account.PrincipalID, account.FirstName, account.LastName, m_HomeURI);
}
private bool VerifyToken(UUID groupID, string agentID, string token)
{
// check the token
MembershipData membership = m_Database.RetrieveMember(groupID, agentID);
if (membership != null)
{
if (token != string.Empty && token.Equals(membership.Data["AccessToken"]))
return true;
else
m_log.DebugFormat("[Groups.HGGroupsService]: access token {0} did not match stored one {1}", token, membership.Data["AccessToken"]);
}
else
m_log.DebugFormat("[Groups.HGGroupsService]: membership not found for {0}", agentID);
return false;
}
}
}
| |
using System;
using System.IO;
using NAudio.Wave.SampleProviders;
using NAudio.Utils;
// ReSharper disable once CheckNamespace
namespace NAudio.Wave
{
/// <summary>
/// This class writes WAV data to a .wav file on disk
/// </summary>
public class WaveFileWriter : Stream
{
private Stream outStream;
private readonly BinaryWriter writer;
private long dataSizePos;
private long factSampleCountPos;
private long dataChunkSize;
private readonly WaveFormat format;
private readonly string filename;
/// <summary>
/// Creates a 16 bit Wave File from an ISampleProvider
/// BEWARE: the source provider must not return data indefinitely
/// </summary>
/// <param name="filename">The filename to write to</param>
/// <param name="sourceProvider">The source sample provider</param>
public static void CreateWaveFile16(string filename, ISampleProvider sourceProvider)
{
CreateWaveFile(filename, new SampleToWaveProvider16(sourceProvider));
}
/// <summary>
/// Creates a Wave file by reading all the data from a WaveProvider
/// BEWARE: the WaveProvider MUST return 0 from its Read method when it is finished,
/// or the Wave File will grow indefinitely.
/// </summary>
/// <param name="filename">The filename to use</param>
/// <param name="sourceProvider">The source WaveProvider</param>
public static void CreateWaveFile(string filename, IWaveProvider sourceProvider)
{
using (var writer = new WaveFileWriter(filename, sourceProvider.WaveFormat))
{
var buffer = new byte[sourceProvider.WaveFormat.AverageBytesPerSecond * 4];
while (true)
{
int bytesRead = sourceProvider.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
// end of source provider
break;
}
// Write will throw exception if WAV file becomes too large
writer.Write(buffer, 0, bytesRead);
}
}
}
/// <summary>
/// Writes to a stream by reading all the data from a WaveProvider
/// BEWARE: the WaveProvider MUST return 0 from its Read method when it is finished,
/// or the Wave File will grow indefinitely.
/// </summary>
/// <param name="outStream">The stream the method will output to</param>
/// <param name="sourceProvider">The source WaveProvider</param>
public static void WriteWavFileToStream(Stream outStream, IWaveProvider sourceProvider)
{
using (var writer = new WaveFileWriter(new IgnoreDisposeStream(outStream), sourceProvider.WaveFormat))
{
var buffer = new byte[sourceProvider.WaveFormat.AverageBytesPerSecond * 4];
while(true)
{
var bytesRead = sourceProvider.Read(buffer, 0, buffer.Length);
if (bytesRead == 0)
{
// end of source provider
outStream.Flush();
break;
}
writer.Write(buffer, 0, bytesRead);
}
}
}
/// <summary>
/// WaveFileWriter that actually writes to a stream
/// </summary>
/// <param name="outStream">Stream to be written to</param>
/// <param name="format">Wave format to use</param>
public WaveFileWriter(Stream outStream, WaveFormat format)
{
this.outStream = outStream;
this.format = format;
writer = new BinaryWriter(outStream, System.Text.Encoding.UTF8);
writer.Write(System.Text.Encoding.UTF8.GetBytes("RIFF"));
writer.Write((int)0); // placeholder
writer.Write(System.Text.Encoding.UTF8.GetBytes("WAVE"));
writer.Write(System.Text.Encoding.UTF8.GetBytes("fmt "));
format.Serialize(writer);
CreateFactChunk();
WriteDataChunkHeader();
}
/// <summary>
/// Creates a new WaveFileWriter
/// </summary>
/// <param name="filename">The filename to write to</param>
/// <param name="format">The Wave Format of the output data</param>
public WaveFileWriter(string filename, WaveFormat format)
: this(new FileStream(filename, FileMode.Create, FileAccess.Write, FileShare.Read), format)
{
this.filename = filename;
}
private void WriteDataChunkHeader()
{
writer.Write(System.Text.Encoding.UTF8.GetBytes("data"));
dataSizePos = outStream.Position;
writer.Write((int)0); // placeholder
}
private void CreateFactChunk()
{
if (HasFactChunk())
{
writer.Write(System.Text.Encoding.UTF8.GetBytes("fact"));
writer.Write((int)4);
factSampleCountPos = outStream.Position;
writer.Write((int)0); // number of samples
}
}
private bool HasFactChunk()
{
return format.Encoding != WaveFormatEncoding.Pcm &&
format.BitsPerSample != 0;
}
/// <summary>
/// The wave file name or null if not applicable
/// </summary>
public string Filename
{
get { return filename; }
}
/// <summary>
/// Number of bytes of audio in the data chunk
/// </summary>
public override long Length
{
get { return dataChunkSize; }
}
/// <summary>
/// WaveFormat of this wave file
/// </summary>
public WaveFormat WaveFormat
{
get { return format; }
}
/// <summary>
/// Returns false: Cannot read from a WaveFileWriter
/// </summary>
public override bool CanRead
{
get { return false; }
}
/// <summary>
/// Returns true: Can write to a WaveFileWriter
/// </summary>
public override bool CanWrite
{
get { return true; }
}
/// <summary>
/// Returns false: Cannot seek within a WaveFileWriter
/// </summary>
public override bool CanSeek
{
get { return false; }
}
/// <summary>
/// Read is not supported for a WaveFileWriter
/// </summary>
public override int Read(byte[] buffer, int offset, int count)
{
throw new InvalidOperationException("Cannot read from a WaveFileWriter");
}
/// <summary>
/// Seek is not supported for a WaveFileWriter
/// </summary>
public override long Seek(long offset, SeekOrigin origin)
{
throw new InvalidOperationException("Cannot seek within a WaveFileWriter");
}
/// <summary>
/// SetLength is not supported for WaveFileWriter
/// </summary>
/// <param name="value"></param>
public override void SetLength(long value)
{
throw new InvalidOperationException("Cannot set length of a WaveFileWriter");
}
/// <summary>
/// Gets the Position in the WaveFile (i.e. number of bytes written so far)
/// </summary>
public override long Position
{
get { return dataChunkSize; }
set { throw new InvalidOperationException("Repositioning a WaveFileWriter is not supported"); }
}
/// <summary>
/// Appends bytes to the WaveFile (assumes they are already in the correct format)
/// </summary>
/// <param name="data">the buffer containing the wave data</param>
/// <param name="offset">the offset from which to start writing</param>
/// <param name="count">the number of bytes to write</param>
[Obsolete("Use Write instead")]
public void WriteData(byte[] data, int offset, int count)
{
Write(data, offset, count);
}
/// <summary>
/// Appends bytes to the WaveFile (assumes they are already in the correct format)
/// </summary>
/// <param name="data">the buffer containing the wave data</param>
/// <param name="offset">the offset from which to start writing</param>
/// <param name="count">the number of bytes to write</param>
public override void Write(byte[] data, int offset, int count)
{
if (outStream.Length + count > UInt32.MaxValue)
throw new ArgumentException("WAV file too large", "count");
outStream.Write(data, offset, count);
dataChunkSize += count;
}
private readonly byte[] value24 = new byte[3]; // keep this around to save us creating it every time
/// <summary>
/// Writes a single sample to the Wave file
/// </summary>
/// <param name="sample">the sample to write (assumed floating point with 1.0f as max value)</param>
public void WriteSample(float sample)
{
if (WaveFormat.BitsPerSample == 16)
{
writer.Write((Int16)(Int16.MaxValue * sample));
dataChunkSize += 2;
}
else if (WaveFormat.BitsPerSample == 24)
{
var value = BitConverter.GetBytes((Int32)(Int32.MaxValue * sample));
value24[0] = value[1];
value24[1] = value[2];
value24[2] = value[3];
writer.Write(value24);
dataChunkSize += 3;
}
else if (WaveFormat.BitsPerSample == 32 && WaveFormat.Encoding == WaveFormatEncoding.Extensible)
{
writer.Write(UInt16.MaxValue * (Int32)sample);
dataChunkSize += 4;
}
else if (WaveFormat.Encoding == WaveFormatEncoding.IeeeFloat)
{
writer.Write(sample);
dataChunkSize += 4;
}
else
{
throw new InvalidOperationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported");
}
}
/// <summary>
/// Writes 32 bit floating point samples to the Wave file
/// They will be converted to the appropriate bit depth depending on the WaveFormat of the WAV file
/// </summary>
/// <param name="samples">The buffer containing the floating point samples</param>
/// <param name="offset">The offset from which to start writing</param>
/// <param name="count">The number of floating point samples to write</param>
public void WriteSamples(float[] samples, int offset, int count)
{
for (int n = 0; n < count; n++)
{
WriteSample(samples[offset + n]);
}
}
/// <summary>
/// Writes 16 bit samples to the Wave file
/// </summary>
/// <param name="samples">The buffer containing the 16 bit samples</param>
/// <param name="offset">The offset from which to start writing</param>
/// <param name="count">The number of 16 bit samples to write</param>
[Obsolete("Use WriteSamples instead")]
public void WriteData(short[] samples, int offset, int count)
{
WriteSamples(samples, offset, count);
}
/// <summary>
/// Writes 16 bit samples to the Wave file
/// </summary>
/// <param name="samples">The buffer containing the 16 bit samples</param>
/// <param name="offset">The offset from which to start writing</param>
/// <param name="count">The number of 16 bit samples to write</param>
public void WriteSamples(short[] samples, int offset, int count)
{
// 16 bit PCM data
if (WaveFormat.BitsPerSample == 16)
{
for (int sample = 0; sample < count; sample++)
{
writer.Write(samples[sample + offset]);
}
dataChunkSize += (count * 2);
}
// 24 bit PCM data
else if (WaveFormat.BitsPerSample == 24)
{
byte[] value;
for (int sample = 0; sample < count; sample++)
{
value = BitConverter.GetBytes(UInt16.MaxValue * (Int32)samples[sample + offset]);
value24[0] = value[1];
value24[1] = value[2];
value24[2] = value[3];
writer.Write(value24);
}
dataChunkSize += (count * 3);
}
// 32 bit PCM data
else if (WaveFormat.BitsPerSample == 32 && WaveFormat.Encoding == WaveFormatEncoding.Extensible)
{
for (int sample = 0; sample < count; sample++)
{
writer.Write(UInt16.MaxValue * (Int32)samples[sample + offset]);
}
dataChunkSize += (count * 4);
}
// IEEE float data
else if (WaveFormat.BitsPerSample == 32 && WaveFormat.Encoding == WaveFormatEncoding.IeeeFloat)
{
for (int sample = 0; sample < count; sample++)
{
writer.Write((float)samples[sample + offset] / (float)(Int16.MaxValue + 1));
}
dataChunkSize += (count * 4);
}
else
{
throw new InvalidOperationException("Only 16, 24 or 32 bit PCM or IEEE float audio data supported");
}
}
/// <summary>
/// Ensures data is written to disk
/// Also updates header, so that WAV file will be valid up to the point currently written
/// </summary>
public override void Flush()
{
var pos = writer.BaseStream.Position;
UpdateHeader(writer);
writer.BaseStream.Position = pos;
}
#region IDisposable Members
/// <summary>
/// Actually performs the close,making sure the header contains the correct data
/// </summary>
/// <param name="disposing">True if called from <see>Dispose</see></param>
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (outStream != null)
{
try
{
UpdateHeader(writer);
}
finally
{
// in a finally block as we don't want the FileStream to run its disposer in
// the GC thread if the code above caused an IOException (e.g. due to disk full)
outStream.Close(); // will close the underlying base stream
outStream = null;
}
}
}
}
/// <summary>
/// Updates the header with file size information
/// </summary>
protected virtual void UpdateHeader(BinaryWriter writer)
{
writer.Flush();
UpdateRiffChunk(writer);
UpdateFactChunk(writer);
UpdateDataChunk(writer);
}
private void UpdateDataChunk(BinaryWriter writer)
{
writer.Seek((int)dataSizePos, SeekOrigin.Begin);
writer.Write((UInt32)dataChunkSize);
}
private void UpdateRiffChunk(BinaryWriter writer)
{
writer.Seek(4, SeekOrigin.Begin);
writer.Write((UInt32)(outStream.Length - 8));
}
private void UpdateFactChunk(BinaryWriter writer)
{
if (HasFactChunk())
{
int bitsPerSample = (format.BitsPerSample * format.Channels);
if (bitsPerSample != 0)
{
writer.Seek((int)factSampleCountPos, SeekOrigin.Begin);
writer.Write((int)((dataChunkSize * 8) / bitsPerSample));
}
}
}
/// <summary>
/// Finaliser - should only be called if the user forgot to close this WaveFileWriter
/// </summary>
~WaveFileWriter()
{
System.Diagnostics.Debug.Assert(false, "WaveFileWriter was not disposed");
Dispose(false);
}
#endregion
}
}
| |
/* ====================================================================
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 TestCases.OpenXml4Net.OPC.Compliance
{
using System;
using NPOI.OpenXml4Net.OPC;
using NUnit.Framework;
using NPOI.OpenXml4Net.Exceptions;
/**
* Test part name Open Packaging Convention compliance.
*
* (Open Packaging Convention 8.1.1 Part names) :
*
* The part name grammar is defined as follows:
*
* part_name = 1*( "/" segment )
*
* segment = 1*( pchar )
*
* pchar is defined in RFC 3986.
*
* The part name grammar implies the following constraints. The package
* implementer shall neither create any part that violates these constraints nor
* retrieve any data from a package as a part if the purported part name
* violates these constraints.
*
* A part name shall not be empty. [M1.1]
*
* A part name shall not have empty segments. [M1.3]
*
* A part name shall start with a forward slash ("/") character. [M1.4]
*
* A part name shall not have a forward slash as the last character. [M1.5]
*
* A segment shall not hold any characters other than pchar characters. [M1.6]
*
* Part segments have the following additional constraints. The package
* implementer shall neither create any part with a part name comprised of a
* segment that violates these constraints nor retrieve any data from a package
* as a part if the purported part name contains a segment that violates these
* constraints.
*
* A segment shall not contain percent-encoded forward slash ("/"), or backward
* slash ("\") characters. [M1.7]
*
* A segment shall not contain percent-encoded unreserved characters. [M1.8]
*
* A segment shall not end with a dot (".") character. [M1.9]
*
* A segment shall include at least one non-dot character. [M1.10]
*
* A package implementer shall neither create nor recognize a part with a part
* name derived from another part name by appending segments to it. [M1.11]
*
* Part name equivalence is determined by comparing part names as
* case-insensitive ASCII strings. [M1.12]
*
* @author Julien Chable
*/
[TestFixture]
public class TestOPCCompliancePartName
{
/**
* Test some common invalid names.
*
* A segment shall not contain percent-encoded unreserved characters. [M1.8]
*/
[Test]
public void TestInvalidPartNames()
{
String[] invalidNames = { "/", "/xml./doc.xml", "[Content_Types].xml", "//xml/." };
foreach (String s in invalidNames)
{
Uri uri = null;
try
{
uri = new Uri(s,UriKind.Relative);
}
catch (UriFormatException e)
{
Assert.IsTrue(s.Equals("[Content_Types].xml"));
continue;
}
Assert.IsFalse(
PackagingUriHelper.IsValidPartName(uri), "This part name SHOULD NOT be valid: " + s);
}
}
/**
* Test some common valid names.
*/
[Test]
public void TestValidPartNames()
{
String[] validNames = { "/xml/item1.xml", "/document.xml",
"/a/%D1%86.xml" };
foreach (String s in validNames)
Assert.IsTrue(
PackagingUriHelper.IsValidPartName(new Uri(s,UriKind.RelativeOrAbsolute)),
"This part name SHOULD be valid: " + s);
}
/**
* A part name shall not be empty. [M1.1]
*/
[Test]
public void TestEmptyPartNameFailure()
{
try
{
PackagingUriHelper.CreatePartName(new Uri("",UriKind.Relative));
Assert.Fail("A part name shall not be empty. [M1.1]");
}
catch (InvalidFormatException e)
{
// Normal behaviour
}
}
/**
* A part name shall not have empty segments. [M1.3]
*
* A segment shall not end with a dot ('.') character. [M1.9]
*
* A segment shall include at least one non-dot character. [M1.10]
*/
[Test]
public void TestPartNameWithInvalidSegmentsFailure()
{
String[] invalidNames = { "//document.xml", "//word/document.xml",
"/word//document.rels", "/word//rels//document.rels",
"/xml./doc.xml", "/document.", "/./document.xml",
"/word/./doc.rels", "/%2F/document.xml" };
foreach (String s in invalidNames)
Assert.IsFalse(
PackagingUriHelper.IsValidPartName(new Uri(s,UriKind.RelativeOrAbsolute)),
"A part name shall not have empty segments. [M1.3]");
}
/**
* A segment shall not hold any characters other than ipchar (RFC 3987) characters.
* [M1.6].
*/
[Test]
public void TestPartNameWithNonPCharCharacters()
{
String[] validNames = { "/doc&.xml" };
try
{
foreach (String s in validNames)
Assert.IsTrue(
PackagingUriHelper
.IsValidPartName(new Uri(s, UriKind.RelativeOrAbsolute)),
"A segment shall not contain non pchar characters [M1.6] : "
+ s);
}
catch (UriFormatException e)
{
Assert.Fail(e.Message);
}
}
/**
* A segment shall not contain percent-encoded unreserved characters [M1.8].
*/
[Test]
public void TestPartNameWithUnreservedEncodedCharactersFailure()
{
String[] invalidNames = { "/a/docum%65nt.xml" };
try
{
foreach (String s in invalidNames)
Assert.IsFalse(
PackagingUriHelper
.IsValidPartName(new Uri(s, UriKind.RelativeOrAbsolute)),
"A segment shall not contain percent-encoded unreserved characters [M1.8] : "
+ s);
}
catch (UriFormatException e)
{
Assert.Fail(e.Message);
}
}
/**
* A part name shall start with a forward slash ('/') character. [M1.4]
*/
[Test]
public void TestPartNameStartsWithAForwardSlashFailure()
{
try
{
PackagingUriHelper.CreatePartName(new Uri("document.xml", UriKind.RelativeOrAbsolute));
Assert.Fail("A part name shall start with a forward slash ('/') character. [M1.4]");
}
catch (InvalidFormatException e)
{
// Normal behaviour
}
}
/**
* A part name shall not have a forward slash as the last character. [M1.5]
*/
[Test]
public void TestPartNameEndsWithAForwardSlashFailure()
{
try
{
PackagingUriHelper.CreatePartName(new Uri("/document.xml/", UriKind.Relative));
Assert.Fail("A part name shall not have a forward slash as the last character. [M1.5]");
}
catch (InvalidFormatException e)
{
// Normal behaviour
}
}
/**
* Part name equivalence is determined by comparing part names as
* case-insensitive ASCII strings. [M1.12]
*/
[Test]
public void TestPartNameComparaison()
{
String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" };
String[] partName2 = { "/WORD/DocUment.XML", "/docProps/core.xml", "/rels/.rels" };
for (int i = 0; i < partName1.Length || i < partName2.Length; ++i)
{
PackagePartName p1 = PackagingUriHelper.CreatePartName(partName1[i]);
PackagePartName p2 = PackagingUriHelper.CreatePartName(partName2[i]);
Assert.IsTrue(p1.Equals(p2));
Assert.IsTrue(p1.CompareTo(p2) == 0);
Assert.IsTrue(p1.GetHashCode() == p2.GetHashCode());
}
}
/**
* Part name equivalence is determined by comparing part names as
* case-insensitive ASCII strings. [M1.12].
*
* All the comparisons MUST FAIL !
*/
[Test]
public void TestPartNameComparaisonFailure()
{
String[] partName1 = { "/word/document.xml", "/docProps/core.xml", "/rels/.rels" };
String[] partName2 = { "/WORD/DocUment.XML2", "/docProp/core.xml", "/rels/rels" };
for (int i = 0; i < partName1.Length || i < partName2.Length; ++i)
{
PackagePartName p1 = PackagingUriHelper.CreatePartName(partName1[i]);
PackagePartName p2 = PackagingUriHelper.CreatePartName(partName2[i]);
Assert.IsFalse(p1.Equals(p2));
Assert.IsFalse(p1.CompareTo(p2) == 0);
Assert.IsFalse(p1.GetHashCode() == p2.GetHashCode());
}
}
}
}
| |
using System;
namespace Es.ToolsCommon
{
public static class XxHashEx
{
private static readonly bool IsLittle = BitConverter.IsLittleEndian;
private static unsafe ulong LoadULong(byte* source)
{
if (IsLittle)
{
return ((ulong) source[0] << 56)
| ((ulong) source[1] << 48)
| ((ulong) source[2] << 40)
| ((ulong) source[3] << 32)
| ((ulong) source[4] << 24)
| ((ulong) source[5] << 16)
| ((ulong) source[6] << 8)
| source[7];
}
return source[0]
| ((ulong) source[1] << 8)
| ((ulong) source[2] << 16)
| ((ulong) source[3] << 24)
| ((ulong) source[4] << 32)
| ((ulong) source[5] << 40)
| ((ulong) source[6] << 48)
| ((ulong) source[7] << 56);
}
private static unsafe uint LoadUInt(byte* source)
{
if (IsLittle)
{
return ((uint) source[0] << 24)
| ((uint) source[1] << 16)
| ((uint) source[2] << 8)
| source[3];
}
return source[0]
| ((uint) source[1] << 8)
| ((uint) source[2] << 16)
| ((uint) source[3] << 24);
}
public static unsafe ulong Hash(this string s, ulong seed = 0)
{
fixed (char* c = s)
{
var len = (ulong) s.Length*2;
var p = (byte*) c;
var bEnd = p + len;
ulong h64;
if (len >= 32)
{
var limit = bEnd - 32;
var v1 = seed + PRIME64_1 + PRIME64_2;
var v2 = seed + PRIME64_2;
var v3 = seed + 0;
var v4 = seed - PRIME64_1;
do
{
v1 += LoadULong(p)*PRIME64_2;
p += 8;
v1 = (v1 << 31) | (v1 >> (64 - 31));
v1 *= PRIME64_1;
v2 += LoadULong(p)*PRIME64_2;
p += 8;
v2 = (v2 << 31) | (v2 >> (64 - 31));
v2 *= PRIME64_1;
v3 += LoadULong(p)*PRIME64_2;
p += 8;
v3 = (v3 << 31) | (v3 >> (64 - 31));
v3 *= PRIME64_1;
v4 += LoadULong(p)*PRIME64_2;
p += 8;
v4 = (v4 << 31) | (v4 >> (64 - 31));
v4 *= PRIME64_1;
} while (p <= limit);
h64 = ((v1 << 1) | (v1 >> (64 - 1))) + ((v2 << 7) | (v2 >> (64 - 7))) +
((v3 << 12) | (v3 >> (64 - 12))) + ((v4 << 18) | (v4 >> (64 - 18)));
v1 *= PRIME64_2;
v1 = (v1 << 31) | (v1 >> (64 - 31));
v1 *= PRIME64_1;
h64 ^= v1;
h64 = h64*PRIME64_1 + PRIME64_4;
v2 *= PRIME64_2;
v2 = (v2 << 31) | (v2 >> (64 - 31));
v2 *= PRIME64_1;
h64 ^= v2;
h64 = h64*PRIME64_1 + PRIME64_4;
v3 *= PRIME64_2;
v3 = (v3 << 31) | (v3 >> (64 - 31));
v3 *= PRIME64_1;
h64 ^= v3;
h64 = h64*PRIME64_1 + PRIME64_4;
v4 *= PRIME64_2;
v4 = (v4 << 31) | (v4 >> (64 - 31));
v4 *= PRIME64_1;
h64 ^= v4;
h64 = h64*PRIME64_1 + PRIME64_4;
}
else
{
h64 = seed + PRIME64_5;
}
h64 += len;
while (p + 8 <= bEnd)
{
var k1 = LoadULong(p);
k1 *= PRIME64_2;
k1 = (k1 << 31) | (k1 >> (64 - 31));
k1 *= PRIME64_1;
h64 ^= k1;
h64 = ((h64 << 27) | (h64 >> (64 - 27)))*PRIME64_1 + PRIME64_4;
p += 8;
}
if (p + 4 <= bEnd)
{
h64 ^= LoadUInt(p)*PRIME64_1;
h64 = ((h64 << 23) | (h64 >> (64 - 23)))*PRIME64_2 + PRIME64_3;
p += 4;
}
while (p < bEnd)
{
h64 ^= *p*PRIME64_5;
h64 = ((h64 << 11) | (h64 >> (64 - 11)))*PRIME64_1;
p++;
}
h64 ^= h64 >> 33;
h64 *= PRIME64_2;
h64 ^= h64 >> 29;
h64 *= PRIME64_3;
h64 ^= h64 >> 32;
return h64;
}
}
public static unsafe ulong Hash(this byte[] b, int offset=0, int length=0, ulong seed = 0)
{
var len = (ulong)length;
if (len == 0)
len = (ulong)b.Length;
fixed (byte* bp = &b[offset])
{
var p = bp;
var bEnd = p + len;
ulong h64;
if (len >= 32)
{
var limit = bEnd - 32;
var v1 = seed + PRIME64_1 + PRIME64_2;
var v2 = seed + PRIME64_2;
var v3 = seed + 0;
var v4 = seed - PRIME64_1;
do
{
v1 += LoadULong(p) * PRIME64_2;
p += 8;
v1 = (v1 << 31) | (v1 >> (64 - 31));
v1 *= PRIME64_1;
v2 += LoadULong(p) * PRIME64_2;
p += 8;
v2 = (v2 << 31) | (v2 >> (64 - 31));
v2 *= PRIME64_1;
v3 += LoadULong(p) * PRIME64_2;
p += 8;
v3 = (v3 << 31) | (v3 >> (64 - 31));
v3 *= PRIME64_1;
v4 += LoadULong(p) * PRIME64_2;
p += 8;
v4 = (v4 << 31) | (v4 >> (64 - 31));
v4 *= PRIME64_1;
} while (p <= limit);
h64 = ((v1 << 1) | (v1 >> (64 - 1))) + ((v2 << 7) | (v2 >> (64 - 7))) +
((v3 << 12) | (v3 >> (64 - 12))) + ((v4 << 18) | (v4 >> (64 - 18)));
v1 *= PRIME64_2;
v1 = (v1 << 31) | (v1 >> (64 - 31));
v1 *= PRIME64_1;
h64 ^= v1;
h64 = h64 * PRIME64_1 + PRIME64_4;
v2 *= PRIME64_2;
v2 = (v2 << 31) | (v2 >> (64 - 31));
v2 *= PRIME64_1;
h64 ^= v2;
h64 = h64 * PRIME64_1 + PRIME64_4;
v3 *= PRIME64_2;
v3 = (v3 << 31) | (v3 >> (64 - 31));
v3 *= PRIME64_1;
h64 ^= v3;
h64 = h64 * PRIME64_1 + PRIME64_4;
v4 *= PRIME64_2;
v4 = (v4 << 31) | (v4 >> (64 - 31));
v4 *= PRIME64_1;
h64 ^= v4;
h64 = h64 * PRIME64_1 + PRIME64_4;
}
else
{
h64 = seed + PRIME64_5;
}
h64 += len;
while (p + 8 <= bEnd)
{
var k1 = LoadULong(p);
k1 *= PRIME64_2;
k1 = (k1 << 31) | (k1 >> (64 - 31));
k1 *= PRIME64_1;
h64 ^= k1;
h64 = ((h64 << 27) | (h64 >> (64 - 27))) * PRIME64_1 + PRIME64_4;
p += 8;
}
if (p + 4 <= bEnd)
{
h64 ^= LoadUInt(p) * PRIME64_1;
h64 = ((h64 << 23) | (h64 >> (64 - 23))) * PRIME64_2 + PRIME64_3;
p += 4;
}
while (p < bEnd)
{
h64 ^= *p * PRIME64_5;
h64 = ((h64 << 11) | (h64 >> (64 - 11))) * PRIME64_1;
p++;
}
h64 ^= h64 >> 33;
h64 *= PRIME64_2;
h64 ^= h64 >> 29;
h64 *= PRIME64_3;
h64 ^= h64 >> 32;
return h64;
}
}
// ReSharper disable InconsistentNaming
private const ulong PRIME64_1 = 11400714785074694791UL;
private const ulong PRIME64_2 = 14029467366897019727UL;
private const ulong PRIME64_3 = 1609587929392839161UL;
private const ulong PRIME64_4 = 9650029242287828579UL;
private const ulong PRIME64_5 = 2870177450012600261UL;
// ReSharper restore InconsistentNaming
}
}
| |
// Generated by SharpKit.QooxDoo.Generator
using System;
using System.Collections.Generic;
using SharpKit.Html;
using SharpKit.JavaScript;
namespace qx.ui.virtualx.cell
{
/// <summary>
/// <para>EXPERIMENTAL!</para>
/// <para>Themeable Cell renderer.</para>
/// <para>This cell renderer can be styled by an appearance theme.</para>
/// </summary>
[JsType(JsMode.Prototype, Name = "qx.ui.virtual.cell.Cell", OmitOptionalParameters = true, Export = false)]
public partial class Cell : qx.ui.virtualx.cell.Abstract
{
#region Properties
/// <summary>
/// <para>The appearance ID. This ID is used to identify the appearance theme
/// entry to use for this cell.</para>
/// </summary>
[JsProperty(Name = "appearance", NativeField = true)]
public string Appearance { get; set; }
/// <summary>
/// <para>The cell’s background color</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "backgroundColor", NativeField = true)]
public string BackgroundColor { get; set; }
/// <summary>
/// <para>The cell’s font. The value is either a font name defined in the font
/// theme or an instance of <see cref="qx.bom.Font"/>.</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "font", NativeField = true)]
public string Font { get; set; }
/// <summary>
/// <para>The ‘padding’ property is a shorthand property for setting ‘paddingTop’,
/// ‘paddingRight’, ‘paddingBottom’ and ‘paddingLeft’ at the same time.</para>
/// <para>If four values are specified they apply to top, right, bottom and left
/// respectively. If there is only one value, it applies to all sides, if
/// there are two or three, the missing values are taken from the opposite
/// side.</para>
/// </summary>
[JsProperty(Name = "padding", NativeField = true)]
public object Padding { get; set; }
/// <summary>
/// <para>Padding of the widget (bottom)</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "paddingBottom", NativeField = true)]
public double PaddingBottom { get; set; }
/// <summary>
/// <para>Padding of the widget (left)</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "paddingLeft", NativeField = true)]
public double PaddingLeft { get; set; }
/// <summary>
/// <para>Padding of the widget (right)</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "paddingRight", NativeField = true)]
public double PaddingRight { get; set; }
/// <summary>
/// <para>Padding of the widget (top)</para>
/// </summary>
[JsProperty(Name = "paddingTop", NativeField = true)]
public double PaddingTop { get; set; }
/// <summary>
/// <para>The text alignment of the cell’s content</para>
/// </summary>
/// <remarks>
/// Possible values: "left","center","right","justify"
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "textAlign", NativeField = true)]
public object TextAlign { get; set; }
/// <summary>
/// <para>The cell’s text color</para>
/// </summary>
/// <remarks>
/// Allow nulls: true
/// </remarks>
[JsProperty(Name = "textColor", NativeField = true)]
public string TextColor { get; set; }
#endregion Properties
#region Methods
public Cell() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property appearance.</para>
/// </summary>
[JsMethod(Name = "getAppearance")]
public string GetAppearance() { throw new NotImplementedException(); }
/// <summary>
/// <para>Get the element attributes for the cell</para>
/// </summary>
/// <param name="value">The cell’s data value</param>
/// <param name="states">A map containing the cell’s state names as map keys.</param>
/// <returns>Compiled string of cell attributes. e.g. ‘tabIndex=“1” readonly=“false”’</returns>
[JsMethod(Name = "getAttributes")]
public string GetAttributes(object value, object states) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property backgroundColor.</para>
/// </summary>
[JsMethod(Name = "getBackgroundColor")]
public string GetBackgroundColor() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns all relevant properties of the cell:
/// <list type="bullet">
/// <item>classes (String): Space separated class names</item>
/// <item>style (String): CSS styles</item>
/// <item>attributes (String): Space separated attributes</item>
/// <item>content (String): HTML fragment of the innerHTML of the cell</item>
/// <item>insets (Array): insets (padding + border) of the cell as
/// two-dimensional array.</item>
/// </list></para>
/// </summary>
/// <param name="data">Data needed for the cell to render.</param>
/// <param name="states">The states set on the cell (e.g. selected, focused, editable).</param>
/// <returns>Cell properties (see above.)</returns>
[JsMethod(Name = "getCellProperties")]
public object GetCellProperties(object data, object states) { throw new NotImplementedException(); }
/// <summary>
/// <para>Get cell’S HTML content</para>
/// </summary>
/// <param name="value">The cell’s data value</param>
/// <param name="states">A map containing the cell’s state names as map keys.</param>
/// <returns>The cell’s content as HTML fragment.</returns>
[JsMethod(Name = "getContent")]
public string GetContent(object value, object states) { throw new NotImplementedException(); }
/// <summary>
/// <para>Get the css classes for the cell</para>
/// </summary>
/// <param name="value">The cell’s data value</param>
/// <param name="states">A map containing the cell’s state names as map keys.</param>
/// <returns>Space separated list of CSS classes</returns>
[JsMethod(Name = "getCssClasses")]
public string GetCssClasses(object value, object states) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property font.</para>
/// </summary>
[JsMethod(Name = "getFont")]
public string GetFont() { throw new NotImplementedException(); }
/// <summary>
/// <para>Get the cell’s insets. Insets are the sum of the cell’s padding and
/// border width.</para>
/// </summary>
/// <param name="value">The cell’s data value</param>
/// <param name="states">A map containing the cell’s state names as map keys.</param>
/// <returns>An array containing the sum of horizontal insets at index 0 and the sum of vertical insets at index 1.</returns>
[JsMethod(Name = "getInsets")]
public double GetInsets(object value, object states) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property paddingBottom.</para>
/// </summary>
[JsMethod(Name = "getPaddingBottom")]
public double GetPaddingBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property paddingLeft.</para>
/// </summary>
[JsMethod(Name = "getPaddingLeft")]
public double GetPaddingLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property paddingRight.</para>
/// </summary>
[JsMethod(Name = "getPaddingRight")]
public double GetPaddingRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property paddingTop.</para>
/// </summary>
[JsMethod(Name = "getPaddingTop")]
public double GetPaddingTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Get the CSS styles for the cell</para>
/// </summary>
/// <param name="value">The cell’s data value</param>
/// <param name="states">A map containing the cell’s state names as map keys.</param>
/// <returns>Compiled string of CSS styles. e.g. ‘color=“red; padding: 10px’</returns>
[JsMethod(Name = "getStyles")]
public string GetStyles(object value, object states) { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property textAlign.</para>
/// </summary>
[JsMethod(Name = "getTextAlign")]
public object GetTextAlign() { throw new NotImplementedException(); }
/// <summary>
/// <para>Returns the (computed) value of the property textColor.</para>
/// </summary>
[JsMethod(Name = "getTextColor")]
public string GetTextColor() { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property appearance
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property appearance.</param>
[JsMethod(Name = "initAppearance")]
public void InitAppearance(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property backgroundColor
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property backgroundColor.</param>
[JsMethod(Name = "initBackgroundColor")]
public void InitBackgroundColor(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property font
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property font.</param>
[JsMethod(Name = "initFont")]
public void InitFont(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property paddingBottom
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property paddingBottom.</param>
[JsMethod(Name = "initPaddingBottom")]
public void InitPaddingBottom(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property paddingLeft
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property paddingLeft.</param>
[JsMethod(Name = "initPaddingLeft")]
public void InitPaddingLeft(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property paddingRight
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property paddingRight.</param>
[JsMethod(Name = "initPaddingRight")]
public void InitPaddingRight(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property paddingTop
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property paddingTop.</param>
[JsMethod(Name = "initPaddingTop")]
public void InitPaddingTop(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property textAlign
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property textAlign.</param>
[JsMethod(Name = "initTextAlign")]
public void InitTextAlign(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Calls the apply method and dispatches the change event of the property textColor
/// with the default value defined by the class developer. This function can
/// only be called from the constructor of a class.</para>
/// </summary>
/// <param name="value">Initial value for property textColor.</param>
[JsMethod(Name = "initTextColor")]
public void InitTextColor(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property appearance.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetAppearance")]
public void ResetAppearance() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property backgroundColor.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetBackgroundColor")]
public void ResetBackgroundColor() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property font.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetFont")]
public void ResetFont() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property padding.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetPadding")]
public void ResetPadding() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property paddingBottom.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetPaddingBottom")]
public void ResetPaddingBottom() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property paddingLeft.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetPaddingLeft")]
public void ResetPaddingLeft() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property paddingRight.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetPaddingRight")]
public void ResetPaddingRight() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property paddingTop.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetPaddingTop")]
public void ResetPaddingTop() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property textAlign.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetTextAlign")]
public void ResetTextAlign() { throw new NotImplementedException(); }
/// <summary>
/// <para>Resets the user value of the property textColor.</para>
/// <para>The computed value falls back to the next available value e.g. appearance, init or
/// inheritance value depeneding on the property configuration and value availability.</para>
/// </summary>
[JsMethod(Name = "resetTextColor")]
public void ResetTextColor() { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property appearance.</para>
/// </summary>
/// <param name="value">New value for property appearance.</param>
[JsMethod(Name = "setAppearance")]
public void SetAppearance(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property backgroundColor.</para>
/// </summary>
/// <param name="value">New value for property backgroundColor.</param>
[JsMethod(Name = "setBackgroundColor")]
public void SetBackgroundColor(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property font.</para>
/// </summary>
/// <param name="value">New value for property font.</param>
[JsMethod(Name = "setFont")]
public void SetFont(string value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the values of the property group padding.</para>
/// <para>This setter supports a shorthand mode compatible with the way margins and paddins are set in CSS.</para>
/// </summary>
/// <param name="paddingTop">Sets the value of the property #paddingTop.</param>
/// <param name="paddingRight">Sets the value of the property #paddingRight.</param>
/// <param name="paddingBottom">Sets the value of the property #paddingBottom.</param>
/// <param name="paddingLeft">Sets the value of the property #paddingLeft.</param>
[JsMethod(Name = "setPadding")]
public void SetPadding(object paddingTop, object paddingRight, object paddingBottom, object paddingLeft) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property paddingBottom.</para>
/// </summary>
/// <param name="value">New value for property paddingBottom.</param>
[JsMethod(Name = "setPaddingBottom")]
public void SetPaddingBottom(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property paddingLeft.</para>
/// </summary>
/// <param name="value">New value for property paddingLeft.</param>
[JsMethod(Name = "setPaddingLeft")]
public void SetPaddingLeft(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property paddingRight.</para>
/// </summary>
/// <param name="value">New value for property paddingRight.</param>
[JsMethod(Name = "setPaddingRight")]
public void SetPaddingRight(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property paddingTop.</para>
/// </summary>
/// <param name="value">New value for property paddingTop.</param>
[JsMethod(Name = "setPaddingTop")]
public void SetPaddingTop(double value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property textAlign.</para>
/// </summary>
/// <param name="value">New value for property textAlign.</param>
[JsMethod(Name = "setTextAlign")]
public void SetTextAlign(object value) { throw new NotImplementedException(); }
/// <summary>
/// <para>Sets the user value of the property textColor.</para>
/// </summary>
/// <param name="value">New value for property textColor.</param>
[JsMethod(Name = "setTextColor")]
public void SetTextColor(string value) { throw new NotImplementedException(); }
#endregion Methods
}
}
| |
// PlantUML Studio
// Copyright 2016 Matthew Hamilton - [email protected]
// Copyright 2010 Omar Al Zabir - http://omaralzabir.com/ (original author)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using PlantUmlStudio.Configuration;
using PlantUmlStudio.Core;
using PlantUmlStudio.Core.InputOutput;
using PlantUmlStudio.Properties;
using PlantUmlStudio.ViewModel.Notifications;
using SharpEssentials.Collections;
using SharpEssentials.Concurrency;
using SharpEssentials.InputOutput;
using SharpEssentials.Controls.Mvvm;
using SharpEssentials.Controls.Mvvm.Commands;
using SharpEssentials.Observable;
namespace PlantUmlStudio.ViewModel
{
/// <summary>
/// Manages diagram previews.
/// </summary>
public class DiagramExplorerViewModel : ViewModelBase, IDiagramExplorer
{
public DiagramExplorerViewModel(INotifications notifications,
IDiagramIOService diagramIO,
Func<Diagram, PreviewDiagramViewModel> previewDiagramFactory,
ISettings settings,
TaskScheduler uiScheduler) : this()
{
_notifications = notifications;
_diagramIO = diagramIO;
_previewDiagramFactory = previewDiagramFactory;
_settings = settings;
_uiScheduler = uiScheduler;
_diagramIO.DiagramFileDeleted += diagramIO_DiagramFileDeleted;
_diagramIO.DiagramFileAdded += diagramIO_DiagramFileAdded;
}
/// <summary>
/// Handles initialization that does not use injected dependencies.
/// </summary>
protected DiagramExplorerViewModel()
{
_previewDiagrams = Property.New(this, p => PreviewDiagrams);
_previewDiagrams.Value = new ObservableCollection<PreviewDiagramViewModel>();
_currentPreviewDiagram = Property.New(this, p => p.CurrentPreviewDiagram);
_diagramLocation = Property.New(this, p => p.DiagramLocation)
.AlsoChanges(p => p.IsDiagramLocationValid);
_isLoadingDiagrams = Property.New(this, p => p.IsLoadingDiagrams);
LoadDiagramsCommand = Command.For(this)
.DependsOn(p => p.IsDiagramLocationValid)
.ExecutesAsync<DirectoryInfo>(LoadDiagramsAsync);
AddNewDiagramCommand = new AsyncRelayCommand<Uri>(AddNewDiagramAsync);
RequestOpenPreviewCommand = new RelayCommand<PreviewDiagramViewModel>(RequestOpenPreview, p => p != null);
OpenDiagramCommand = new AsyncRelayCommand<Uri>(async uri =>
{
try { await OpenDiagramAsync(uri); }
catch (Exception e) { _notifications.Notify(new ExceptionNotification(e)); }
});
DeleteDiagramCommand = new AsyncRelayCommand<PreviewDiagramViewModel>(DeleteDiagramAsync, preview => preview != null);
_cancelLoadDiagramsCommand = Property.New(this, p => p.CancelLoadDiagramsCommand);
PropertyChanged += OnPropertyChanged;
}
private async void OnPropertyChanged(object sender, PropertyChangedEventArgs e)
{
if (e.PropertyName == nameof(DiagramLocation))
await LoadDiagramsAsync(DiagramLocation);
}
/// <summary>
/// The code used for new diagrams.
/// </summary>
public string NewDiagramTemplate { get; set; }
/// <summary>
/// The diagram file extension.
/// </summary>
public string FileExtension { get; set; }
/// <see cref="IDiagramExplorer.DiagramLocation"/>
public DirectoryInfo DiagramLocation
{
get { return _diagramLocation.Value; }
set
{
if (_diagramLocation.TrySetValue(value))
{
if (IsDiagramLocationValid)
{
_settings.LastDiagramLocation = value;
_diagramIO.StartMonitoring(value);
}
else
{
_diagramIO.StopMonitoring();
}
}
}
}
/// <summary>
/// Whether the current diagram location is valid.
/// </summary>
public bool IsDiagramLocationValid => DiagramLocation != null && DiagramLocation.Exists;
/// <summary>
/// The currently selected preview diagram.
/// </summary>
public PreviewDiagramViewModel CurrentPreviewDiagram
{
get { return _currentPreviewDiagram.Value; }
set { _currentPreviewDiagram.Value = value; }
}
/// <see cref="IDiagramExplorer.PreviewDiagrams"/>
public ICollection<PreviewDiagramViewModel> PreviewDiagrams => _previewDiagrams.Value;
/// <summary>
/// Opens a preview for editing.
/// </summary>
public ICommand RequestOpenPreviewCommand { get; }
private void RequestOpenPreview(PreviewDiagramViewModel preview)
{
OnOpenPreviewRequested(preview);
}
/// <see cref="IDiagramExplorer.OpenPreviewRequested"/>
public event EventHandler<OpenPreviewRequestedEventArgs> OpenPreviewRequested;
private void OnOpenPreviewRequested(PreviewDiagramViewModel preview)
{
OpenPreviewRequested?.Invoke(this, new OpenPreviewRequestedEventArgs(preview));
}
/// <see cref="IDiagramExplorer.DiagramDeleted"/>
public event EventHandler<DiagramDeletedEventArgs> DiagramDeleted;
private void OnDiagramDeleted(Diagram deletedDiagram)
{
DiagramDeleted?.Invoke(this, new DiagramDeletedEventArgs(deletedDiagram));
}
/// <summary>
/// Adds a new diagram with a given URI.
/// </summary>
public ICommand AddNewDiagramCommand { get; }
private async Task AddNewDiagramAsync(Uri newDiagramUri)
{
string newFilePath = newDiagramUri.LocalPath;
if (String.IsNullOrEmpty(Path.GetExtension(newFilePath)))
newFilePath += FileExtension;
var newDiagram = new Diagram
{
File = new FileInfo(newFilePath),
Content = String.Format(NewDiagramTemplate, Path.GetFileNameWithoutExtension(newFilePath) + ".png")
};
_diagramLocation.Value = new DirectoryInfo(Path.GetDirectoryName(newFilePath));
var progress = _notifications.StartProgress(false);
try
{
await _diagramIO.SaveAsync(newDiagram, false);
var refreshedDiagram = await _diagramIO.ReadAsync(newDiagram.File);
var preview = PreviewDiagrams.SingleOrDefault(p => FileComparer.Equals(p.Diagram.File, refreshedDiagram.File));
if (preview == null)
{
preview = _previewDiagramFactory(refreshedDiagram);
PreviewDiagrams.Add(preview);
}
CurrentPreviewDiagram = preview;
OnOpenPreviewRequested(preview);
progress.Report(ProgressUpdate.Completed(string.Empty));
}
catch (Exception e)
{
progress.Report(ProgressUpdate.Failed(e));
}
}
/// <summary>
/// Whether diagrams are currently being loaded.
/// </summary>
public bool IsLoadingDiagrams
{
get { return _isLoadingDiagrams.Value; }
private set { _isLoadingDiagrams.Value = value; }
}
/// <summary>
/// Command that loads diagrams from the current diagram location.
/// </summary>
public IAsyncCommand LoadDiagramsCommand { get; }
private async Task LoadDiagramsAsync(DirectoryInfo directory)
{
PreviewDiagrams.Clear();
if (directory == null || !directory.Exists)
return;
using (var cts = new CancellationTokenSource())
{
IsLoadingDiagrams = true;
var progress = _notifications.StartProgress();
progress.Report(new ProgressUpdate { PercentComplete = 0, Message = Resources.Progress_LoadingDiagrams });
CancelLoadDiagramsCommand = new CancelTaskCommand(cts);
// Capture diagrams as they are read for a more responsive UI.
var readProgress = new Progress<ReadDiagramsProgress>(p =>
p.Diagram.Apply(d => PreviewDiagrams.Add(_previewDiagramFactory(d))));
// Report progress to UI by passing up progress data.
progress.Wrap(readProgress, p => new ProgressUpdate
{
PercentComplete = (int?)(p.ProcessedDiagramCount / (double)p.TotalDiagramCount * 100),
Message = String.Format(Resources.Progress_LoadingFile, p.ProcessedDiagramCount, p.TotalDiagramCount)
});
try
{
await _diagramIO.ReadDiagramsAsync(directory, readProgress, cts.Token);
progress.Report(ProgressUpdate.Completed(Resources.Progress_DiagramsLoaded));
}
catch (OperationCanceledException)
{
progress.Report(ProgressUpdate.Completed(Resources.Progress_DiagramLoadCanceled));
}
catch (Exception e)
{
progress.Report(ProgressUpdate.Failed(e));
}
finally
{
CancelLoadDiagramsCommand = null;
IsLoadingDiagrams = false;
}
}
}
/// <summary>
/// Cancels loading of diagrams.
/// </summary>
public ICommand CancelLoadDiagramsCommand
{
get { return _cancelLoadDiagramsCommand.Value; }
private set { _cancelLoadDiagramsCommand.Value = value; }
}
/// <summary>
/// Command to delete a diagram.
/// </summary>
public IAsyncCommand DeleteDiagramCommand { get; }
private async Task DeleteDiagramAsync(PreviewDiagramViewModel preview)
{
try
{
await _diagramIO.DeleteAsync(preview.Diagram);
PreviewDiagrams.Remove(preview);
}
catch (Exception e)
{
_notifications.Notify(new ExceptionNotification(e));
}
}
/// <summary>
/// Command to open a diagram.
/// </summary>
public IAsyncCommand OpenDiagramCommand { get; }
/// <see cref="IDiagramExplorer.OpenDiagramAsync"/>
public async Task<Diagram> OpenDiagramAsync(Uri diagramPath)
{
var fileToOpen = new FileInfo(diagramPath.LocalPath);
Diagram diagram;
var preview = PreviewDiagrams.SingleOrDefault(p => FileComparer.Equals(p.Diagram.File, fileToOpen));
if (preview == null)
{
diagram = await _diagramIO.ReadAsync(fileToOpen);
preview = _previewDiagramFactory(diagram);
}
else
{
diagram = preview.Diagram;
}
OnOpenPreviewRequested(preview);
return diagram;
}
/// <summary>
/// Asynchronously opens a sequence of diagrams.
/// </summary>
/// <param name="diagramFiles">The diagram files to open</param>
/// <returns>A task representing the open operation</returns>
public async Task OpenDiagramFilesAsync(IEnumerable<FileInfo> diagramFiles)
{
await diagramFiles.Select(file => OpenDiagramAsync(new Uri(file.FullName))).ToList();
}
void diagramIO_DiagramFileDeleted(object sender, DiagramFileDeletedEventArgs e)
{
Task.Factory.StartNew(() =>
PreviewDiagrams.FirstOrNone(pd => FileComparer.Equals(pd.Diagram.File, e.DeletedDiagramFile)).Apply(existingPreview =>
{
OnDiagramDeleted(existingPreview.Diagram);
PreviewDiagrams.Remove(existingPreview);
}), CancellationToken.None, TaskCreationOptions.None, _uiScheduler);
}
void diagramIO_DiagramFileAdded(object sender, DiagramFileAddedEventArgs e)
{
Task.Factory.StartNew(async () =>
{
// Make sure a preview doesn't already exist for the file and make sure the current directory still matches.
bool previewExists = PreviewDiagrams.Select(pd => pd.Diagram.File).Contains(e.NewDiagramFile, FileComparer);
if (!previewExists && e.NewDiagramFile.Directory?.FullName.Trim('\\') == DiagramLocation.FullName.Trim('\\'))
{
var newlyAddedDiagram = await _diagramIO.ReadAsync(e.NewDiagramFile);
if (newlyAddedDiagram != null)
PreviewDiagrams.Add(_previewDiagramFactory(newlyAddedDiagram));
}
}, CancellationToken.None, TaskCreationOptions.None, _uiScheduler);
}
/// <summary>
/// Contains current task progress information.
/// </summary>
private readonly INotifications _notifications;
private readonly Property<PreviewDiagramViewModel> _currentPreviewDiagram;
private readonly Property<ICollection<PreviewDiagramViewModel>> _previewDiagrams;
private readonly Property<DirectoryInfo> _diagramLocation;
private readonly Property<ICommand> _cancelLoadDiagramsCommand;
private readonly Property<bool> _isLoadingDiagrams;
private readonly IDiagramIOService _diagramIO;
private readonly Func<Diagram, PreviewDiagramViewModel> _previewDiagramFactory;
private readonly ISettings _settings;
private readonly TaskScheduler _uiScheduler;
private static readonly IEqualityComparer<FileInfo> FileComparer = FileSystemInfoPathEqualityComparer.Instance;
}
}
| |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Runtime.InteropServices;
using Avalonia.Controls;
using Avalonia.Controls.Platform;
using Avalonia.Input;
using Avalonia.Input.Raw;
using Avalonia.OpenGL;
using Avalonia.OpenGL.Angle;
using Avalonia.OpenGL.Egl;
using Avalonia.OpenGL.Surfaces;
using Avalonia.Platform;
using Avalonia.Rendering;
using Avalonia.Win32.Input;
using Avalonia.Win32.Interop;
using Avalonia.Win32.OpenGl;
using Avalonia.Win32.WinRT;
using Avalonia.Win32.WinRT.Composition;
using static Avalonia.Win32.Interop.UnmanagedMethods;
namespace Avalonia.Win32
{
/// <summary>
/// Window implementation for Win32 platform.
/// </summary>
public partial class WindowImpl : IWindowImpl, EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo,
ITopLevelImplWithNativeControlHost
{
private static readonly List<WindowImpl> s_instances = new List<WindowImpl>();
private static readonly IntPtr DefaultCursor = LoadCursor(
IntPtr.Zero, new IntPtr((int)UnmanagedMethods.Cursor.IDC_ARROW));
private static readonly Dictionary<WindowEdge, HitTestValues> s_edgeLookup =
new Dictionary<WindowEdge, HitTestValues>
{
{ WindowEdge.East, HitTestValues.HTRIGHT },
{ WindowEdge.North, HitTestValues.HTTOP },
{ WindowEdge.NorthEast, HitTestValues.HTTOPRIGHT },
{ WindowEdge.NorthWest, HitTestValues.HTTOPLEFT },
{ WindowEdge.South, HitTestValues.HTBOTTOM },
{ WindowEdge.SouthEast, HitTestValues.HTBOTTOMRIGHT },
{ WindowEdge.SouthWest, HitTestValues.HTBOTTOMLEFT },
{ WindowEdge.West, HitTestValues.HTLEFT }
};
private SavedWindowInfo _savedWindowInfo;
private bool _isFullScreenActive;
private bool _isClientAreaExtended;
private Thickness _extendedMargins;
private Thickness _offScreenMargin;
private double _extendTitleBarHint = -1;
private bool _isUsingComposition;
private IBlurHost _blurHost;
private PlatformResizeReason _resizeReason;
#if USE_MANAGED_DRAG
private readonly ManagedWindowResizeDragHelper _managedDrag;
#endif
private const WindowStyles WindowStateMask = (WindowStyles.WS_MAXIMIZE | WindowStyles.WS_MINIMIZE);
private readonly TouchDevice _touchDevice;
private readonly MouseDevice _mouseDevice;
private readonly ManagedDeferredRendererLock _rendererLock;
private readonly FramebufferManager _framebuffer;
private readonly IGlPlatformSurface _gl;
private Win32NativeControlHost _nativeControlHost;
private WndProc _wndProcDelegate;
private string _className;
private IntPtr _hwnd;
private bool _multitouch;
private IInputRoot _owner;
private WindowProperties _windowProperties;
private bool _trackingMouse;
private bool _topmost;
private double _scaling = 1;
private WindowState _showWindowState;
private WindowState _lastWindowState;
private OleDropTarget _dropTarget;
private Size _minSize;
private Size _maxSize;
private POINT _maxTrackSize;
private WindowImpl _parent;
private ExtendClientAreaChromeHints _extendChromeHints = ExtendClientAreaChromeHints.Default;
private bool _isCloseRequested;
private bool _shown;
private bool _hiddenWindowIsParent;
public WindowImpl()
{
_touchDevice = new TouchDevice();
_mouseDevice = new WindowsMouseDevice();
#if USE_MANAGED_DRAG
_managedDrag = new ManagedWindowResizeDragHelper(this, capture =>
{
if (capture)
UnmanagedMethods.SetCapture(Handle.Handle);
else
UnmanagedMethods.ReleaseCapture();
});
#endif
_windowProperties = new WindowProperties
{
ShowInTaskbar = false,
IsResizable = true,
Decorations = SystemDecorations.Full
};
_rendererLock = new ManagedDeferredRendererLock();
var glPlatform = AvaloniaLocator.Current.GetService<IPlatformOpenGlInterface>();
var compositionConnector = AvaloniaLocator.Current.GetService<WinUICompositorConnection>();
_isUsingComposition = compositionConnector is { } &&
glPlatform is EglPlatformOpenGlInterface egl &&
egl.Display is AngleWin32EglDisplay angleDisplay &&
angleDisplay.PlatformApi == AngleOptions.PlatformApi.DirectX11;
CreateWindow();
_framebuffer = new FramebufferManager(_hwnd);
if (glPlatform != null)
{
if (_isUsingComposition)
{
var cgl = new WinUiCompositedWindowSurface(compositionConnector, this);
_blurHost = cgl;
_gl = cgl;
_isUsingComposition = true;
}
else
{
if (glPlatform is EglPlatformOpenGlInterface egl2)
_gl = new EglGlPlatformSurface(egl2, this);
else if (glPlatform is WglPlatformOpenGlInterface wgl)
_gl = new WglGlPlatformSurface(wgl.PrimaryContext, this);
}
}
Screen = new ScreenImpl();
_nativeControlHost = new Win32NativeControlHost(this);
s_instances.Add(this);
}
public Action Activated { get; set; }
public Func<bool> Closing { get; set; }
public Action Closed { get; set; }
public Action Deactivated { get; set; }
public Action<RawInputEventArgs> Input { get; set; }
public Action<Rect> Paint { get; set; }
public Action<Size, PlatformResizeReason> Resized { get; set; }
public Action<double> ScalingChanged { get; set; }
public Action<PixelPoint> PositionChanged { get; set; }
public Action<WindowState> WindowStateChanged { get; set; }
public Action LostFocus { get; set; }
public Action<WindowTransparencyLevel> TransparencyLevelChanged { get; set; }
public Thickness BorderThickness
{
get
{
if (HasFullDecorations)
{
var style = GetStyle();
var exStyle = GetExtendedStyle();
var padding = new RECT();
if (AdjustWindowRectEx(ref padding, (uint)style, false, (uint)exStyle))
{
return new Thickness(-padding.left, -padding.top, padding.right, padding.bottom);
}
else
{
throw new Win32Exception();
}
}
else
{
return new Thickness();
}
}
}
public double RenderScaling => _scaling;
public double DesktopScaling => RenderScaling;
public Size ClientSize
{
get
{
GetClientRect(_hwnd, out var rect);
return new Size(rect.right, rect.bottom) / RenderScaling;
}
}
public Size? FrameSize
{
get
{
if (DwmIsCompositionEnabled(out var compositionEnabled) != 0 || !compositionEnabled)
{
GetWindowRect(_hwnd, out var rcWindow);
return new Size(rcWindow.Width, rcWindow.Height) / RenderScaling;
}
DwmGetWindowAttribute(_hwnd, (int)DwmWindowAttribute.DWMWA_EXTENDED_FRAME_BOUNDS, out var rect, Marshal.SizeOf(typeof(RECT)));
return new Size(rect.Width, rect.Height) / RenderScaling;
}
}
public IScreenImpl Screen { get; }
public IPlatformHandle Handle { get; private set; }
public virtual Size MaxAutoSizeHint => new Size(_maxTrackSize.X / RenderScaling, _maxTrackSize.Y / RenderScaling);
public IMouseDevice MouseDevice => _mouseDevice;
public WindowState WindowState
{
get
{
if(_isFullScreenActive)
{
return WindowState.FullScreen;
}
var placement = default(WINDOWPLACEMENT);
GetWindowPlacement(_hwnd, ref placement);
return placement.ShowCmd switch
{
ShowWindowCommand.Maximize => WindowState.Maximized,
ShowWindowCommand.Minimize => WindowState.Minimized,
_ => WindowState.Normal
};
}
set
{
if (IsWindowVisible(_hwnd))
{
ShowWindow(value, true);
}
_showWindowState = value;
}
}
public WindowTransparencyLevel TransparencyLevel { get; private set; }
protected IntPtr Hwnd => _hwnd;
public void SetTransparencyLevelHint (WindowTransparencyLevel transparencyLevel)
{
TransparencyLevel = EnableBlur(transparencyLevel);
}
private WindowTransparencyLevel EnableBlur(WindowTransparencyLevel transparencyLevel)
{
if (Win32Platform.WindowsVersion.Major >= 6)
{
if (DwmIsCompositionEnabled(out var compositionEnabled) != 0 || !compositionEnabled)
{
return WindowTransparencyLevel.None;
}
else if (Win32Platform.WindowsVersion.Major >= 10)
{
return Win10EnableBlur(transparencyLevel);
}
else if (Win32Platform.WindowsVersion.Minor >= 2)
{
return Win8xEnableBlur(transparencyLevel);
}
else
{
return Win7EnableBlur(transparencyLevel);
}
}
else
{
return WindowTransparencyLevel.None;
}
}
private WindowTransparencyLevel Win7EnableBlur(WindowTransparencyLevel transparencyLevel)
{
if (transparencyLevel == WindowTransparencyLevel.AcrylicBlur)
{
transparencyLevel = WindowTransparencyLevel.Blur;
}
var blurInfo = new DWM_BLURBEHIND(false);
if (transparencyLevel == WindowTransparencyLevel.Blur)
{
blurInfo = new DWM_BLURBEHIND(true);
}
DwmEnableBlurBehindWindow(_hwnd, ref blurInfo);
if (transparencyLevel == WindowTransparencyLevel.Transparent)
{
return WindowTransparencyLevel.None;
}
else
{
return transparencyLevel;
}
}
private WindowTransparencyLevel Win8xEnableBlur(WindowTransparencyLevel transparencyLevel)
{
var accent = new AccentPolicy();
var accentStructSize = Marshal.SizeOf(accent);
if (transparencyLevel == WindowTransparencyLevel.AcrylicBlur)
{
transparencyLevel = WindowTransparencyLevel.Blur;
}
if (transparencyLevel == WindowTransparencyLevel.Transparent)
{
accent.AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND;
}
else
{
accent.AccentState = AccentState.ACCENT_DISABLED;
}
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
Marshal.StructureToPtr(accent, accentPtr, false);
var data = new WindowCompositionAttributeData();
data.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY;
data.SizeOfData = accentStructSize;
data.Data = accentPtr;
SetWindowCompositionAttribute(_hwnd, ref data);
Marshal.FreeHGlobal(accentPtr);
if (transparencyLevel >= WindowTransparencyLevel.Blur)
{
Win7EnableBlur(transparencyLevel);
}
return transparencyLevel;
}
private WindowTransparencyLevel Win10EnableBlur(WindowTransparencyLevel transparencyLevel)
{
if (_isUsingComposition)
{
_blurHost?.SetBlur(transparencyLevel >= WindowTransparencyLevel.Blur);
return transparencyLevel;
}
else
{
bool canUseAcrylic = Win32Platform.WindowsVersion.Major > 10 || Win32Platform.WindowsVersion.Build >= 19628;
var accent = new AccentPolicy();
var accentStructSize = Marshal.SizeOf(accent);
if (transparencyLevel == WindowTransparencyLevel.AcrylicBlur && !canUseAcrylic)
{
transparencyLevel = WindowTransparencyLevel.Blur;
}
switch (transparencyLevel)
{
default:
case WindowTransparencyLevel.None:
accent.AccentState = AccentState.ACCENT_DISABLED;
break;
case WindowTransparencyLevel.Transparent:
accent.AccentState = AccentState.ACCENT_ENABLE_TRANSPARENTGRADIENT;
break;
case WindowTransparencyLevel.Blur:
accent.AccentState = AccentState.ACCENT_ENABLE_BLURBEHIND;
break;
case WindowTransparencyLevel.AcrylicBlur:
case (WindowTransparencyLevel.AcrylicBlur + 1): // hack-force acrylic.
accent.AccentState = AccentState.ACCENT_ENABLE_ACRYLIC;
transparencyLevel = WindowTransparencyLevel.AcrylicBlur;
break;
}
accent.AccentFlags = 2;
accent.GradientColor = 0x01000000;
var accentPtr = Marshal.AllocHGlobal(accentStructSize);
Marshal.StructureToPtr(accent, accentPtr, false);
var data = new WindowCompositionAttributeData();
data.Attribute = WindowCompositionAttribute.WCA_ACCENT_POLICY;
data.SizeOfData = accentStructSize;
data.Data = accentPtr;
SetWindowCompositionAttribute(_hwnd, ref data);
Marshal.FreeHGlobal(accentPtr);
return transparencyLevel;
}
}
public IEnumerable<object> Surfaces => new object[] { Handle, _gl, _framebuffer };
public PixelPoint Position
{
get
{
GetWindowRect(_hwnd, out var rc);
return new PixelPoint(rc.left, rc.top);
}
set
{
SetWindowPos(
Handle.Handle,
IntPtr.Zero,
value.X,
value.Y,
0,
0,
SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_NOZORDER);
}
}
private bool HasFullDecorations => _windowProperties.Decorations == SystemDecorations.Full;
public void Move(PixelPoint point) => Position = point;
public void SetMinMaxSize(Size minSize, Size maxSize)
{
_minSize = minSize;
_maxSize = maxSize;
}
public IRenderer CreateRenderer(IRenderRoot root)
{
var loop = AvaloniaLocator.Current.GetService<IRenderLoop>();
var customRendererFactory = AvaloniaLocator.Current.GetService<IRendererFactory>();
if (customRendererFactory != null)
return customRendererFactory.Create(root, loop);
return Win32Platform.UseDeferredRendering
? _isUsingComposition
? new DeferredRenderer(root, loop)
{
RenderOnlyOnRenderThread = true
}
: (IRenderer)new DeferredRenderer(root, loop, rendererLock: _rendererLock)
: new ImmediateRenderer(root);
}
public void Resize(Size value, PlatformResizeReason reason)
{
int requestedClientWidth = (int)(value.Width * RenderScaling);
int requestedClientHeight = (int)(value.Height * RenderScaling);
GetClientRect(_hwnd, out var clientRect);
// do comparison after scaling to avoid rounding issues
if (requestedClientWidth != clientRect.Width || requestedClientHeight != clientRect.Height)
{
GetWindowRect(_hwnd, out var windowRect);
using var scope = SetResizeReason(reason);
SetWindowPos(
_hwnd,
IntPtr.Zero,
0,
0,
requestedClientWidth + (_isClientAreaExtended ? 0 : windowRect.Width - clientRect.Width),
requestedClientHeight + (_isClientAreaExtended ? 0 : windowRect.Height - clientRect.Height),
SetWindowPosFlags.SWP_RESIZE);
}
}
public void Activate()
{
SetActiveWindow(_hwnd);
}
public IPopupImpl CreatePopup() => Win32Platform.UseOverlayPopups ? null : new PopupImpl(this);
public void Dispose()
{
(_gl as IDisposable)?.Dispose();
if (_dropTarget != null)
{
OleContext.Current?.UnregisterDragDrop(Handle);
_dropTarget = null;
}
if (_hwnd != IntPtr.Zero)
{
// Detect if we are being closed programmatically - this would mean that WM_CLOSE was not called
// and we didn't prepare this window for destruction.
if (!_isCloseRequested)
{
BeforeCloseCleanup(true);
}
DestroyWindow(_hwnd);
_hwnd = IntPtr.Zero;
}
if (_className != null)
{
UnregisterClass(_className, GetModuleHandle(null));
_className = null;
}
_framebuffer.Dispose();
}
public void Invalidate(Rect rect)
{
var scaling = RenderScaling;
var r = new RECT
{
left = (int)Math.Floor(rect.X * scaling),
top = (int)Math.Floor(rect.Y * scaling),
right = (int)Math.Ceiling(rect.Right * scaling),
bottom = (int)Math.Ceiling(rect.Bottom * scaling),
};
InvalidateRect(_hwnd, ref r, false);
}
public Point PointToClient(PixelPoint point)
{
var p = new POINT { X = point.X, Y = point.Y };
UnmanagedMethods.ScreenToClient(_hwnd, ref p);
return new Point(p.X, p.Y) / RenderScaling;
}
public PixelPoint PointToScreen(Point point)
{
point *= RenderScaling;
var p = new POINT { X = (int)point.X, Y = (int)point.Y };
ClientToScreen(_hwnd, ref p);
return new PixelPoint(p.X, p.Y);
}
public void SetInputRoot(IInputRoot inputRoot)
{
_owner = inputRoot;
CreateDropTarget();
}
public void Hide()
{
UnmanagedMethods.ShowWindow(_hwnd, ShowWindowCommand.Hide);
_shown = false;
}
public virtual void Show(bool activate, bool isDialog)
{
SetParent(_parent);
ShowWindow(_showWindowState, activate);
}
public Action GotInputWhenDisabled { get; set; }
public void SetParent(IWindowImpl parent)
{
_parent = (WindowImpl)parent;
var parentHwnd = _parent?._hwnd ?? IntPtr.Zero;
if (parentHwnd == IntPtr.Zero && !_windowProperties.ShowInTaskbar)
{
parentHwnd = OffscreenParentWindow.Handle;
_hiddenWindowIsParent = true;
}
SetWindowLongPtr(_hwnd, (int)WindowLongParam.GWL_HWNDPARENT, parentHwnd);
}
public void SetEnabled(bool enable) => EnableWindow(_hwnd, enable);
public void BeginMoveDrag(PointerPressedEventArgs e)
{
_mouseDevice.Capture(null);
DefWindowProc(_hwnd, (int)WindowsMessage.WM_NCLBUTTONDOWN,
new IntPtr((int)HitTestValues.HTCAPTION), IntPtr.Zero);
e.Pointer.Capture(null);
}
public void BeginResizeDrag(WindowEdge edge, PointerPressedEventArgs e)
{
#if USE_MANAGED_DRAG
_managedDrag.BeginResizeDrag(edge, ScreenToClient(MouseDevice.Position.ToPoint(_scaling)));
#else
_mouseDevice.Capture(null);
DefWindowProc(_hwnd, (int)WindowsMessage.WM_NCLBUTTONDOWN,
new IntPtr((int)s_edgeLookup[edge]), IntPtr.Zero);
#endif
}
public void SetTitle(string title)
{
SetWindowText(_hwnd, title);
}
public void SetCursor(ICursorImpl cursor)
{
var impl = cursor as CursorImpl;
if (cursor is null || impl is object)
{
var hCursor = impl?.Handle ?? DefaultCursor;
SetClassLong(_hwnd, ClassLongIndex.GCLP_HCURSOR, hCursor);
if (_owner.IsPointerOver)
{
UnmanagedMethods.SetCursor(hCursor);
}
}
}
public void SetIcon(IWindowIconImpl icon)
{
var impl = (IconImpl)icon;
var hIcon = impl?.HIcon ?? IntPtr.Zero;
PostMessage(_hwnd, (int)WindowsMessage.WM_SETICON,
new IntPtr((int)Icons.ICON_BIG), hIcon);
}
public void ShowTaskbarIcon(bool value)
{
var newWindowProperties = _windowProperties;
newWindowProperties.ShowInTaskbar = value;
UpdateWindowProperties(newWindowProperties);
}
public void CanResize(bool value)
{
var newWindowProperties = _windowProperties;
newWindowProperties.IsResizable = value;
UpdateWindowProperties(newWindowProperties);
}
public void SetSystemDecorations(SystemDecorations value)
{
var newWindowProperties = _windowProperties;
newWindowProperties.Decorations = value;
UpdateWindowProperties(newWindowProperties);
}
public void SetTopmost(bool value)
{
if (value == _topmost)
{
return;
}
IntPtr hWndInsertAfter = value ? WindowPosZOrder.HWND_TOPMOST : WindowPosZOrder.HWND_NOTOPMOST;
SetWindowPos(_hwnd,
hWndInsertAfter,
0, 0, 0, 0,
SetWindowPosFlags.SWP_NOMOVE | SetWindowPosFlags.SWP_NOSIZE | SetWindowPosFlags.SWP_NOACTIVATE);
_topmost = value;
}
protected virtual IntPtr CreateWindowOverride(ushort atom)
{
return CreateWindowEx(
_isUsingComposition ? (int)WindowStyles.WS_EX_NOREDIRECTIONBITMAP : 0,
atom,
null,
(int)WindowStyles.WS_OVERLAPPEDWINDOW | (int) WindowStyles.WS_CLIPCHILDREN,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
CW_USEDEFAULT,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero,
IntPtr.Zero);
}
private void CreateWindow()
{
// Ensure that the delegate doesn't get garbage collected by storing it as a field.
_wndProcDelegate = WndProc;
_className = $"Avalonia-{Guid.NewGuid().ToString()}";
// Unique DC helps with performance when using Gpu based rendering
const ClassStyles windowClassStyle = ClassStyles.CS_OWNDC | ClassStyles.CS_HREDRAW | ClassStyles.CS_VREDRAW;
var wndClassEx = new WNDCLASSEX
{
cbSize = Marshal.SizeOf<WNDCLASSEX>(),
style = (int)windowClassStyle,
lpfnWndProc = _wndProcDelegate,
hInstance = GetModuleHandle(null),
hCursor = DefaultCursor,
hbrBackground = IntPtr.Zero,
lpszClassName = _className
};
ushort atom = RegisterClassEx(ref wndClassEx);
if (atom == 0)
{
throw new Win32Exception();
}
_hwnd = CreateWindowOverride(atom);
if (_hwnd == IntPtr.Zero)
{
throw new Win32Exception();
}
Handle = new PlatformHandle(_hwnd, PlatformConstants.WindowHandleType);
_multitouch = Win32Platform.Options.EnableMultitouch ?? true;
if (_multitouch)
{
RegisterTouchWindow(_hwnd, 0);
}
if (ShCoreAvailable && Win32Platform.WindowsVersion > PlatformConstants.Windows8)
{
var monitor = MonitorFromWindow(
_hwnd,
MONITOR.MONITOR_DEFAULTTONEAREST);
if (GetDpiForMonitor(
monitor,
MONITOR_DPI_TYPE.MDT_EFFECTIVE_DPI,
out var dpix,
out var dpiy) == 0)
{
_scaling = dpix / 96.0;
}
}
}
private void CreateDropTarget()
{
var odt = new OleDropTarget(this, _owner);
if (OleContext.Current?.RegisterDragDrop(Handle, odt) ?? false)
{
_dropTarget = odt;
}
}
/// <summary>
/// Ported from https://github.com/chromium/chromium/blob/master/ui/views/win/fullscreen_handler.cc
/// Method must only be called from inside UpdateWindowProperties.
/// </summary>
/// <param name="fullscreen"></param>
private void SetFullScreen(bool fullscreen)
{
if (fullscreen)
{
GetWindowRect(_hwnd, out var windowRect);
_savedWindowInfo.WindowRect = windowRect;
var current = GetStyle();
var currentEx = GetExtendedStyle();
_savedWindowInfo.Style = current;
_savedWindowInfo.ExStyle = currentEx;
// Set new window style and size.
SetStyle(current & ~(WindowStyles.WS_CAPTION | WindowStyles.WS_THICKFRAME), false);
SetExtendedStyle(currentEx & ~(WindowStyles.WS_EX_DLGMODALFRAME | WindowStyles.WS_EX_WINDOWEDGE | WindowStyles.WS_EX_CLIENTEDGE | WindowStyles.WS_EX_STATICEDGE), false);
// On expand, if we're given a window_rect, grow to it, otherwise do
// not resize.
MONITORINFO monitor_info = MONITORINFO.Create();
GetMonitorInfo(MonitorFromWindow(_hwnd, MONITOR.MONITOR_DEFAULTTONEAREST), ref monitor_info);
var window_rect = monitor_info.rcMonitor.ToPixelRect();
SetWindowPos(_hwnd, IntPtr.Zero, window_rect.X, window_rect.Y,
window_rect.Width, window_rect.Height,
SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_FRAMECHANGED);
_isFullScreenActive = true;
}
else
{
// Reset original window style and size. The multiple window size/moves
// here are ugly, but if SetWindowPos() doesn't redraw, the taskbar won't be
// repainted. Better-looking methods welcome.
_isFullScreenActive = false;
var windowStates = GetWindowStateStyles();
SetStyle((_savedWindowInfo.Style & ~WindowStateMask) | windowStates, false);
SetExtendedStyle(_savedWindowInfo.ExStyle, false);
// On restore, resize to the previous saved rect size.
var new_rect = _savedWindowInfo.WindowRect.ToPixelRect();
SetWindowPos(_hwnd, IntPtr.Zero, new_rect.X, new_rect.Y, new_rect.Width,
new_rect.Height,
SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE | SetWindowPosFlags.SWP_FRAMECHANGED);
UpdateWindowProperties(_windowProperties, true);
}
TaskBarList.MarkFullscreen(_hwnd, fullscreen);
ExtendClientArea();
}
private MARGINS UpdateExtendMargins()
{
RECT borderThickness = new RECT();
RECT borderCaptionThickness = new RECT();
AdjustWindowRectEx(ref borderCaptionThickness, (uint)(GetStyle()), false, 0);
AdjustWindowRectEx(ref borderThickness, (uint)(GetStyle() & ~WindowStyles.WS_CAPTION), false, 0);
borderThickness.left *= -1;
borderThickness.top *= -1;
borderCaptionThickness.left *= -1;
borderCaptionThickness.top *= -1;
bool wantsTitleBar = _extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.SystemChrome) || _extendTitleBarHint == -1;
if (!wantsTitleBar)
{
borderCaptionThickness.top = 1;
}
MARGINS margins = new MARGINS();
margins.cxLeftWidth = 1;
margins.cxRightWidth = 1;
margins.cyBottomHeight = 1;
if (_extendTitleBarHint != -1)
{
borderCaptionThickness.top = (int)(_extendTitleBarHint * RenderScaling);
}
margins.cyTopHeight = _extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.SystemChrome) && !_extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.PreferSystemChrome) ? borderCaptionThickness.top : 1;
if (WindowState == WindowState.Maximized)
{
_extendedMargins = new Thickness(0, (borderCaptionThickness.top - borderThickness.top) / RenderScaling, 0, 0);
_offScreenMargin = new Thickness(borderThickness.left / RenderScaling, borderThickness.top / RenderScaling, borderThickness.right / RenderScaling, borderThickness.bottom / RenderScaling);
}
else
{
_extendedMargins = new Thickness(0, (borderCaptionThickness.top) / RenderScaling, 0, 0);
_offScreenMargin = new Thickness();
}
return margins;
}
private void ExtendClientArea()
{
if (!_shown)
{
return;
}
if (DwmIsCompositionEnabled(out bool compositionEnabled) < 0 || !compositionEnabled)
{
_isClientAreaExtended = false;
return;
}
GetClientRect(_hwnd, out var rcClient);
GetWindowRect(_hwnd, out var rcWindow);
// Inform the application of the frame change.
SetWindowPos(_hwnd,
IntPtr.Zero,
rcWindow.left, rcWindow.top,
rcClient.Width, rcClient.Height,
SetWindowPosFlags.SWP_FRAMECHANGED | SetWindowPosFlags.SWP_NOACTIVATE);
if (_isClientAreaExtended && WindowState != WindowState.FullScreen)
{
var margins = UpdateExtendMargins();
DwmExtendFrameIntoClientArea(_hwnd, ref margins);
}
else
{
var margins = new MARGINS();
DwmExtendFrameIntoClientArea(_hwnd, ref margins);
_offScreenMargin = new Thickness();
_extendedMargins = new Thickness();
Resize(new Size(rcWindow.Width/ RenderScaling, rcWindow.Height / RenderScaling), PlatformResizeReason.Layout);
}
if(!_isClientAreaExtended || (_extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.SystemChrome) &&
!_extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.PreferSystemChrome)))
{
EnableCloseButton(_hwnd);
}
else
{
DisableCloseButton(_hwnd);
}
ExtendClientAreaToDecorationsChanged?.Invoke(_isClientAreaExtended);
}
private void ShowWindow(WindowState state, bool activate)
{
_shown = true;
if (_isClientAreaExtended)
{
ExtendClientArea();
}
ShowWindowCommand? command;
var newWindowProperties = _windowProperties;
switch (state)
{
case WindowState.Minimized:
newWindowProperties.IsFullScreen = false;
command = activate ? ShowWindowCommand.Minimize : ShowWindowCommand.ShowMinNoActive;
break;
case WindowState.Maximized:
newWindowProperties.IsFullScreen = false;
command = ShowWindowCommand.Maximize;
break;
case WindowState.Normal:
newWindowProperties.IsFullScreen = false;
command = IsWindowVisible(_hwnd) ? ShowWindowCommand.Restore :
activate ? ShowWindowCommand.Normal : ShowWindowCommand.ShowNoActivate;
break;
case WindowState.FullScreen:
newWindowProperties.IsFullScreen = true;
command = IsWindowVisible(_hwnd) ? (ShowWindowCommand?)null : ShowWindowCommand.Restore;
break;
default:
throw new ArgumentException("Invalid WindowState.");
}
UpdateWindowProperties(newWindowProperties);
if (command.HasValue)
{
UnmanagedMethods.ShowWindow(_hwnd, command.Value);
}
if (state == WindowState.Maximized)
{
MaximizeWithoutCoveringTaskbar();
}
if (!Design.IsDesignMode && activate)
{
SetFocus(_hwnd);
}
}
private void BeforeCloseCleanup(bool isDisposing)
{
// Based on https://github.com/dotnet/wpf/blob/master/src/Microsoft.DotNet.Wpf/src/PresentationFramework/System/Windows/Window.cs#L4270-L4337
// We need to enable parent window before destroying child window to prevent OS from activating a random window behind us (or last active window).
// This is described here: https://docs.microsoft.com/en-us/windows/win32/api/winuser/nf-winuser-enablewindow#remarks
// We need to verify if parent is still alive (perhaps it got destroyed somehow).
if (_parent != null && IsWindow(_parent._hwnd))
{
var wasActive = GetActiveWindow() == _hwnd;
// We can only set enabled state if we are not disposing - generally Dispose happens after enabled state has been set.
// Ignoring this would cause us to enable a window that might be disabled.
if (!isDisposing)
{
// Our window closed callback will set enabled state to a correct value after child window gets destroyed.
_parent.SetEnabled(true);
}
// We also need to activate our parent window since again OS might try to activate a window behind if it is not set.
if (wasActive)
{
SetActiveWindow(_parent._hwnd);
}
}
}
private void MaximizeWithoutCoveringTaskbar()
{
IntPtr monitor = MonitorFromWindow(_hwnd, MONITOR.MONITOR_DEFAULTTONEAREST);
if (monitor != IntPtr.Zero)
{
var monitorInfo = MONITORINFO.Create();
if (GetMonitorInfo(monitor, ref monitorInfo))
{
var x = monitorInfo.rcWork.left;
var y = monitorInfo.rcWork.top;
var cx = Math.Abs(monitorInfo.rcWork.right - x);
var cy = Math.Abs(monitorInfo.rcWork.bottom - y);
SetWindowPos(_hwnd, WindowPosZOrder.HWND_NOTOPMOST, x, y, cx, cy, SetWindowPosFlags.SWP_SHOWWINDOW);
}
}
}
private WindowStyles GetWindowStateStyles()
{
return GetStyle() & WindowStateMask;
}
private WindowStyles GetStyle()
{
if (_isFullScreenActive)
{
return _savedWindowInfo.Style;
}
else
{
return (WindowStyles)GetWindowLong(_hwnd, (int)WindowLongParam.GWL_STYLE);
}
}
private WindowStyles GetExtendedStyle()
{
if (_isFullScreenActive)
{
return _savedWindowInfo.ExStyle;
}
else
{
return (WindowStyles)GetWindowLong(_hwnd, (int)WindowLongParam.GWL_EXSTYLE);
}
}
private void SetStyle(WindowStyles style, bool save = true)
{
if (save)
{
_savedWindowInfo.Style = style;
}
if (!_isFullScreenActive)
{
SetWindowLong(_hwnd, (int)WindowLongParam.GWL_STYLE, (uint)style);
}
}
private void SetExtendedStyle(WindowStyles style, bool save = true)
{
if (save)
{
_savedWindowInfo.ExStyle = style;
}
if (!_isFullScreenActive)
{
SetWindowLong(_hwnd, (int)WindowLongParam.GWL_EXSTYLE, (uint)style);
}
}
private void UpdateWindowProperties(WindowProperties newProperties, bool forceChanges = false)
{
var oldProperties = _windowProperties;
// Calling SetWindowPos will cause events to be sent and we need to respond
// according to the new values already.
_windowProperties = newProperties;
if ((oldProperties.ShowInTaskbar != newProperties.ShowInTaskbar) || forceChanges)
{
var exStyle = GetExtendedStyle();
if (newProperties.ShowInTaskbar)
{
exStyle |= WindowStyles.WS_EX_APPWINDOW;
if (_hiddenWindowIsParent)
{
// Can't enable the taskbar icon by clearing the parent window unless the window
// is hidden. Hide the window and show it again with the same activation state
// when we've finished. Interestingly it seems to work fine the other way.
var shown = IsWindowVisible(_hwnd);
var activated = GetActiveWindow() == _hwnd;
if (shown)
Hide();
_hiddenWindowIsParent = false;
SetParent(null);
if (shown)
Show(activated, false);
}
}
else
{
// To hide a non-owned window's taskbar icon we need to parent it to a hidden window.
if (_parent is null)
{
SetWindowLongPtr(_hwnd, (int)WindowLongParam.GWL_HWNDPARENT, OffscreenParentWindow.Handle);
_hiddenWindowIsParent = true;
}
exStyle &= ~WindowStyles.WS_EX_APPWINDOW;
}
SetExtendedStyle(exStyle);
}
WindowStyles style;
if ((oldProperties.IsResizable != newProperties.IsResizable) || forceChanges)
{
style = GetStyle();
if (newProperties.IsResizable)
{
style |= WindowStyles.WS_SIZEFRAME;
style |= WindowStyles.WS_MAXIMIZEBOX;
}
else
{
style &= ~WindowStyles.WS_SIZEFRAME;
style &= ~WindowStyles.WS_MAXIMIZEBOX;
}
SetStyle(style);
}
if (oldProperties.IsFullScreen != newProperties.IsFullScreen)
{
SetFullScreen(newProperties.IsFullScreen);
}
if ((oldProperties.Decorations != newProperties.Decorations) || forceChanges)
{
style = GetStyle();
const WindowStyles fullDecorationFlags = WindowStyles.WS_CAPTION | WindowStyles.WS_SYSMENU;
if (newProperties.Decorations == SystemDecorations.Full)
{
style |= fullDecorationFlags;
}
else
{
style &= ~fullDecorationFlags;
}
SetStyle(style);
if (!_isFullScreenActive)
{
var margin = newProperties.Decorations == SystemDecorations.BorderOnly ? 1 : 0;
var margins = new MARGINS
{
cyBottomHeight = margin,
cxRightWidth = margin,
cxLeftWidth = margin,
cyTopHeight = margin
};
DwmExtendFrameIntoClientArea(_hwnd, ref margins);
GetClientRect(_hwnd, out var oldClientRect);
var oldClientRectOrigin = new POINT();
ClientToScreen(_hwnd, ref oldClientRectOrigin);
oldClientRect.Offset(oldClientRectOrigin);
var newRect = oldClientRect;
if (newProperties.Decorations == SystemDecorations.Full)
{
AdjustWindowRectEx(ref newRect, (uint)style, false, (uint)GetExtendedStyle());
}
SetWindowPos(_hwnd, IntPtr.Zero, newRect.left, newRect.top, newRect.Width, newRect.Height,
SetWindowPosFlags.SWP_NOZORDER | SetWindowPosFlags.SWP_NOACTIVATE |
SetWindowPosFlags.SWP_FRAMECHANGED);
}
}
}
private const int MF_BYCOMMAND = 0x0;
private const int MF_BYPOSITION = 0x400;
private const int MF_REMOVE = 0x1000;
private const int MF_ENABLED = 0x0;
private const int MF_GRAYED = 0x1;
private const int MF_DISABLED = 0x2;
private const int SC_CLOSE = 0xF060;
void DisableCloseButton(IntPtr hwnd)
{
EnableMenuItem(GetSystemMenu(hwnd, false), SC_CLOSE,
MF_BYCOMMAND | MF_DISABLED | MF_GRAYED);
}
void EnableCloseButton(IntPtr hwnd)
{
EnableMenuItem(GetSystemMenu(hwnd, false), SC_CLOSE,
MF_BYCOMMAND | MF_ENABLED);
}
#if USE_MANAGED_DRAG
private Point ScreenToClient(Point point)
{
var p = new UnmanagedMethods.POINT { X = (int)point.X, Y = (int)point.Y };
UnmanagedMethods.ScreenToClient(_hwnd, ref p);
return new Point(p.X, p.Y);
}
#endif
PixelSize EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo.Size
{
get
{
GetClientRect(_hwnd, out var rect);
return new PixelSize(
Math.Max(1, rect.right - rect.left),
Math.Max(1, rect.bottom - rect.top));
}
}
double EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo.Scaling => RenderScaling;
IntPtr EglGlPlatformSurface.IEglWindowGlPlatformSurfaceInfo.Handle => Handle.Handle;
public void SetExtendClientAreaToDecorationsHint(bool hint)
{
_isClientAreaExtended = hint;
ExtendClientArea();
}
public void SetExtendClientAreaChromeHints(ExtendClientAreaChromeHints hints)
{
_extendChromeHints = hints;
ExtendClientArea();
}
/// <inheritdoc/>
public void SetExtendClientAreaTitleBarHeightHint(double titleBarHeight)
{
_extendTitleBarHint = titleBarHeight;
ExtendClientArea();
}
/// <inheritdoc/>
public bool IsClientAreaExtendedToDecorations => _isClientAreaExtended;
/// <inheritdoc/>
public Action<bool> ExtendClientAreaToDecorationsChanged { get; set; }
/// <inheritdoc/>
public bool NeedsManagedDecorations => _isClientAreaExtended && _extendChromeHints.HasAllFlags(ExtendClientAreaChromeHints.PreferSystemChrome);
/// <inheritdoc/>
public Thickness ExtendedMargins => _extendedMargins;
/// <inheritdoc/>
public Thickness OffScreenMargin => _offScreenMargin;
/// <inheritdoc/>
public AcrylicPlatformCompensationLevels AcrylicCompensationLevels { get; } = new AcrylicPlatformCompensationLevels(1, 0.8, 0);
private ResizeReasonScope SetResizeReason(PlatformResizeReason reason)
{
var old = _resizeReason;
_resizeReason = reason;
return new ResizeReasonScope(this, old);
}
private struct SavedWindowInfo
{
public WindowStyles Style { get; set; }
public WindowStyles ExStyle { get; set; }
public RECT WindowRect { get; set; }
};
private struct WindowProperties
{
public bool ShowInTaskbar;
public bool IsResizable;
public SystemDecorations Decorations;
public bool IsFullScreen;
}
private struct ResizeReasonScope : IDisposable
{
private readonly WindowImpl _owner;
private readonly PlatformResizeReason _restore;
public ResizeReasonScope(WindowImpl owner, PlatformResizeReason restore)
{
_owner = owner;
_restore = restore;
}
public void Dispose() => _owner._resizeReason = _restore;
}
}
}
| |
/*
*
* (c) Copyright Ascensio System Limited 2010-2021
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
* http://www.apache.org/licenses/LICENSE-2.0
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.ServiceModel.Syndication;
using System.Text;
using System.Web;
using System.Web.Services;
using System.Xml;
using ASC.Core;
using ASC.Core.Tenants;
using ASC.Core.Users;
using ASC.Feed;
using ASC.Feed.Data;
using ASC.Web.Core;
using ASC.Web.Core.Helpers;
using ASC.Web.Studio.Utility;
namespace ASC.Web.Studio.Services.WhatsNew
{
[WebService(Namespace = "http://www.teamlab.com/")]
[WebServiceBinding(ConformsTo = WsiProfiles.None)]
public class feed : IHttpHandler
{
public const string HandlerBasePath = "~/services/whatsnew/";
public const string HandlerPath = "~/services/whatsnew/feed.ashx";
private const string TitleParam = "c";
private const string ProductParam = "pid";
public void ProcessRequest(HttpContext context)
{
if (!ProcessAuthorization(context))
{
AccessDenied(context);
return;
}
var productId = ParseGuid(context.Request[ProductParam]);
var product = WebItemManager.Instance[productId.GetValueOrDefault()];
var products = WebItemManager.Instance.GetItemsAll<IProduct>().ToDictionary(p => p.GetSysName());
var lastModified = GetLastModified(context);
var feeds = FeedAggregateDataProvider.GetFeeds(new FeedApiFilter
{
Product = product != null ? product.GetSysName() : null,
From = lastModified ?? DateTime.UtcNow.AddDays(-14),
To = DateTime.UtcNow,
OnlyNew = true
})
.OrderByDescending(f => f.CreatedDate)
.Take(100)
.Select(f => f.ToFeedMin())
.ToList();
if (lastModified != null && feeds.Count == 0)
{
context.Response.StatusCode = (int)HttpStatusCode.NotModified;
context.Response.StatusDescription = "Not Modified";
}
var feedItems = feeds.Select(f =>
{
var item = new SyndicationItem(
HttpUtility.HtmlDecode((products.ContainsKey(f.Product) ? products[f.Product].Name + ": " : string.Empty) + f.Title),
string.Empty,
new Uri(CommonLinkUtility.GetFullAbsolutePath(f.ItemUrl)),
f.Id,
new DateTimeOffset(TenantUtil.DateTimeToUtc(f.CreatedDate)))
{
PublishDate = f.CreatedDate,
};
if (f.Author != null && f.Author.UserInfo != null)
{
var u = f.Author.UserInfo;
item.Authors.Add(new SyndicationPerson(u.Email, u.DisplayUserName(false), CommonLinkUtility.GetUserProfile(u.ID)));
}
return item;
});
var lastUpdate = DateTime.UtcNow;
if (feeds.Count > 0)
{
lastUpdate = feeds.Max(x => x.ModifiedDate);
}
var feed = new SyndicationFeed(
CoreContext.TenantManager.GetCurrentTenant().Name,
string.Empty,
new Uri(context.Request.GetUrlRewriter(), VirtualPathUtility.ToAbsolute("~/Feed.aspx")),
TenantProvider.CurrentTenantID.ToString(),
new DateTimeOffset(lastUpdate),
feedItems);
var rssFormatter = new Atom10FeedFormatter(feed);
var settings = new XmlWriterSettings
{
CheckCharacters = false,
ConformanceLevel = ConformanceLevel.Document,
Encoding = Encoding.UTF8,
Indent = true,
};
using (var writer = XmlWriter.Create(context.Response.Output, settings))
{
rssFormatter.WriteTo(writer);
}
context.Response.Charset = Encoding.UTF8.WebName;
context.Response.ContentType = "application/atom+xml";
context.Response.AddHeader("ETag", DateTime.UtcNow.ToString("yyyyMMddHHmmss"));
context.Response.AddHeader("Last-Modified", DateTime.UtcNow.ToString("R"));
}
public static string RenderRssMeta(string title, string productId)
{
var urlparams = new Dictionary<string, string>();
if (!String.IsNullOrEmpty(productId))
{
urlparams.Add(ProductParam, productId);
}
if (!String.IsNullOrEmpty(title))
{
urlparams.Add(TitleParam, title);
}
var queryString = new StringBuilder("?");
foreach (var urlparam in urlparams)
{
queryString.AppendFormat("{0}={1}&", HttpUtility.UrlEncode(urlparam.Key), HttpUtility.UrlEncode(urlparam.Value));
}
return string.Format(@"<link rel=""alternate"" type=""application/atom+xml"" title=""{0}"" href=""{1}"" />",
title, CommonLinkUtility.GetFullAbsolutePath(HandlerPath) + queryString.ToString().TrimEnd('&'));
}
private static bool ProcessAuthorization(HttpContext context)
{
if (!SecurityContext.IsAuthenticated)
{
try
{
var cookiesKey = CookiesManager.GetCookies(CookiesType.AuthKey);
if (!SecurityContext.AuthenticateMe(cookiesKey))
{
throw new UnauthorizedAccessException();
}
}
catch (Exception)
{
return AuthorizationHelper.ProcessBasicAuthorization(context);
}
}
return SecurityContext.IsAuthenticated;
}
private static void AccessDenied(HttpContext context)
{
context.Response.StatusCode = (int)HttpStatusCode.Unauthorized;
context.Response.StatusDescription = "Access Denied";
string realm = String.Format("Basic Realm=\"{0}\"", context.Request.GetUrlRewriter().Host);
context.Response.AppendHeader("WWW-Authenticate", realm);
context.Response.Write("401 Access Denied");
}
private static Guid? ParseGuid(string guid)
{
try
{
return new Guid(guid);
}
catch
{
return null;
}
}
private DateTime? GetLastModified(HttpContext context)
{
if (context.Request.Headers["If-Modified-Since"] != null)
{
try
{
return DateTime.ParseExact(context.Request.Headers["If-Modified-Since"], "R", null);
}
catch { }
}
if (context.Request.Headers["If-None-Match"] != null)
{
try
{
return DateTime.ParseExact(context.Request.Headers["If-None-Match"], "yyyyMMddHHmmss", null);
}
catch { }
}
return null;
}
public bool IsReusable
{
get { return false; }
}
}
}
| |
/*
* Copyright (c) 2009, Stefan Simek
*
* 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;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.Reflection.Emit;
namespace TriAxis.RunSharp
{
using Operands;
partial class CodeGen
{
#region Assignment
public void Assign(Operand target, Operand value)
{
Assign(target, value, false);
}
public void Assign(Operand target, Operand value, bool allowExplicitConversion)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.Assign(value, allowExplicitConversion).Emit(this);
}
public void AssignAdd(Operand target, Operand value)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.AssignAdd(value).Emit(this);
}
public void AssignSubtract(Operand target, Operand value)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.AssignSubtract(value).Emit(this);
}
public void AssignMultiply(Operand target, Operand value)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.AssignMultiply(value).Emit(this);
}
public void AssignDivide(Operand target, Operand value)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.AssignDivide(value).Emit(this);
}
public void AssignModulus(Operand target, Operand value)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.AssignModulus(value).Emit(this);
}
public void AssignAnd(Operand target, Operand value)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.AssignAnd(value).Emit(this);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Checked, OK")]
public void AssignOr(Operand target, Operand value)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.AssignOr(value).Emit(this);
}
public void AssignXor(Operand target, Operand value)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.AssignXor(value).Emit(this);
}
public void AssignLeftShift(Operand target, Operand value)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.AssignLeftShift(value).Emit(this);
}
public void AssignRightShift(Operand target, Operand value)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.AssignRightShift(value).Emit(this);
}
public void Increment(Operand target)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.Increment().Emit(this);
}
public void Decrement(Operand target)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.Decrement().Emit(this);
}
#endregion
#region Constructor chaining
public void InvokeThis(params Operand[] args)
{
if (cg == null)
throw new InvalidOperationException(Properties.Messages.ErrConstructorOnlyCall);
if (chainCalled)
throw new InvalidOperationException(Properties.Messages.ErrConstructorAlreadyChained);
ApplicableFunction other = TypeInfo.FindConstructor(cg.Type, args);
il.Emit(OpCodes.Ldarg_0);
other.EmitArgs(this, args);
il.Emit(OpCodes.Call, (ConstructorInfo)other.Method.Member);
chainCalled = true;
}
public void InvokeBase(params Operand[] args)
{
if (cg == null)
throw new InvalidOperationException(Properties.Messages.ErrConstructorOnlyCall);
if (chainCalled)
throw new InvalidOperationException(Properties.Messages.ErrConstructorAlreadyChained);
if (cg.Type.TypeBuilder.IsValueType)
throw new InvalidOperationException(Properties.Messages.ErrStructNoBaseCtor);
ApplicableFunction other = TypeInfo.FindConstructor(cg.Type.BaseType, args);
if (other == null)
throw new InvalidOperationException(Properties.Messages.ErrMissingConstructor);
il.Emit(OpCodes.Ldarg_0);
other.EmitArgs(this, args);
il.Emit(OpCodes.Call, (ConstructorInfo)other.Method.Member);
chainCalled = true;
// when the chain continues to base, we also need to call the common constructor
il.Emit(OpCodes.Ldarg_0);
il.Emit(OpCodes.Call, cg.Type.CommonConstructor().GetMethodBuilder());
}
#endregion
void BeforeStatement()
{
if (!reachable)
throw new InvalidOperationException(Properties.Messages.ErrCodeNotReachable);
if (cg != null && !chainCalled && !cg.Type.TypeBuilder.IsValueType)
InvokeBase();
}
void DoInvoke(Operand invocation)
{
BeforeStatement();
invocation.EmitGet(this);
if (invocation.Type != typeof(void))
il.Emit(OpCodes.Pop);
}
#region Invocation
public void Invoke<T>(string method)
{
Invoke(typeof(T), method);
}
public void Invoke(Type target, string method)
{
Invoke(target, method, Operand.EmptyArray);
}
public void Invoke<T>(string method, params Operand[] args)
{
Invoke(typeof(T), method, args);
}
public void Invoke(Type target, string method, params Operand[] args)
{
DoInvoke(Static.Invoke(target, method, args));
}
public void Invoke(Operand target, string method)
{
Invoke(target, method, Operand.EmptyArray);
}
public void Invoke(Operand target, string method, params Operand[] args)
{
if ((object)target == null)
throw new ArgumentNullException("target");
DoInvoke(target.Invoke(method, args));
}
public void InvokeDelegate(Operand targetDelegate)
{
InvokeDelegate(targetDelegate, Operand.EmptyArray);
}
public void InvokeDelegate(Operand targetDelegate, params Operand[] args)
{
if ((object)targetDelegate == null)
throw new ArgumentNullException("targetDelegate");
DoInvoke(targetDelegate.InvokeDelegate(args));
}
public void WriteLine(params Operand[] args)
{
Invoke(typeof(Console), "WriteLine", args);
}
#endregion
#region Event subscription
public void SubscribeEvent(Operand target, string eventName, Operand handler)
{
if ((object)target == null)
throw new ArgumentNullException("target");
if ((object)handler == null)
throw new ArgumentNullException("handler");
IMemberInfo evt = TypeInfo.FindEvent(target.Type, eventName, target.IsStaticTarget);
MethodInfo mi = ((EventInfo)evt.Member).GetAddMethod();
if (!target.IsStaticTarget)
target.EmitGet(this);
handler.EmitGet(this);
EmitCallHelper(mi, target);
}
public void UnsubscribeEvent(Operand target, string eventName, Operand handler)
{
if ((object)target == null)
throw new ArgumentNullException("target");
if ((object)handler == null)
throw new ArgumentNullException("handler");
IMemberInfo evt = TypeInfo.FindEvent(target.Type, eventName, target.IsStaticTarget);
MethodInfo mi = ((EventInfo)evt.Member).GetRemoveMethod();
if (!target.IsStaticTarget)
target.EmitGet(this);
handler.EmitGet(this);
EmitCallHelper(mi, target);
}
#endregion
public void InitObj(Operand target)
{
if ((object)target == null)
throw new ArgumentNullException("target");
BeforeStatement();
target.EmitAddressOf(this);
il.Emit(OpCodes.Initobj, target.Type);
}
#region Flow Control
interface IBreakable
{
Label GetBreakTarget();
}
interface IContinuable
{
Label GetContinueTarget();
}
public void Break()
{
BeforeStatement();
bool useLeave = false;
foreach (Block blk in blocks)
{
ExceptionBlock xb = blk as ExceptionBlock;
if (xb != null)
{
if (xb.IsFinally)
throw new InvalidOperationException(Properties.Messages.ErrInvalidFinallyBranch);
useLeave = true;
}
IBreakable brkBlock = blk as IBreakable;
if (brkBlock != null)
{
il.Emit(useLeave ? OpCodes.Leave : OpCodes.Br, brkBlock.GetBreakTarget());
reachable = false;
return;
}
}
throw new InvalidOperationException(Properties.Messages.ErrInvalidBreak);
}
public void Continue()
{
BeforeStatement();
bool useLeave = false;
foreach (Block blk in blocks)
{
ExceptionBlock xb = blk as ExceptionBlock;
if (xb != null)
{
if (xb.IsFinally)
throw new InvalidOperationException(Properties.Messages.ErrInvalidFinallyBranch);
useLeave = true;
}
IContinuable cntBlock = blk as IContinuable;
if (cntBlock != null)
{
il.Emit(useLeave ? OpCodes.Leave : OpCodes.Br, cntBlock.GetContinueTarget());
reachable = false;
return;
}
}
throw new InvalidOperationException(Properties.Messages.ErrInvalidContinue);
}
public void Return()
{
if (context.ReturnType != null && context.ReturnType != typeof(void))
throw new InvalidOperationException(Properties.Messages.ErrMethodMustReturnValue);
BeforeStatement();
ExceptionBlock xb = GetAnyTryBlock();
if (xb == null)
{
il.Emit(OpCodes.Ret);
}
else if (xb.IsFinally)
{
throw new InvalidOperationException(Properties.Messages.ErrInvalidFinallyBranch);
}
else
{
EnsureReturnVariable();
il.Emit(OpCodes.Leave, retLabel);
}
reachable = false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "'Operand' required as type to use provided implicit conversions")]
public void Return(Operand value)
{
if (context.ReturnType == null || context.ReturnType == typeof(void))
throw new InvalidOperationException(Properties.Messages.ErrVoidMethodReturningValue);
BeforeStatement();
EmitGetHelper(value, context.ReturnType, false);
ExceptionBlock xb = GetAnyTryBlock();
if (xb == null)
{
il.Emit(OpCodes.Ret);
}
else if (xb.IsFinally)
{
throw new InvalidOperationException(Properties.Messages.ErrInvalidFinallyBranch);
}
else
{
EnsureReturnVariable();
il.Emit(OpCodes.Stloc, retVar);
il.Emit(OpCodes.Leave, retLabel);
}
reachable = false;
}
public void Throw()
{
BeforeStatement();
il.Emit(OpCodes.Rethrow);
reachable = false;
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Design", "CA1011:ConsiderPassingBaseTypesAsParameters", Justification = "'Operand' required as type to use provided implicit conversions")]
public void Throw(Operand exception)
{
BeforeStatement();
EmitGetHelper(exception, typeof(Exception), false);
il.Emit(OpCodes.Throw);
reachable = false;
}
public void For(IStatement init, Operand test, IStatement iterator)
{
Begin(new LoopBlock(init, test, iterator));
}
public void While(Operand test)
{
Begin(new LoopBlock(null, test, null));
}
public Operand ForEach<T>(Operand expression)
{
return ForEach(typeof(T), expression);
}
public Operand ForEach(Type elementType, Operand expression)
{
ForeachBlock fb = new ForeachBlock(elementType, expression);
Begin(fb);
return fb.Element;
}
public void If(Operand condition)
{
Begin(new IfBlock(condition));
}
public void Else()
{
IfBlock ifBlk = GetBlock() as IfBlock;
if (ifBlk == null)
throw new InvalidOperationException(Properties.Messages.ErrElseWithoutIf);
blocks.Pop();
Begin(new ElseBlock(ifBlk));
}
public void Try()
{
Begin(new ExceptionBlock());
}
ExceptionBlock GetTryBlock()
{
ExceptionBlock tryBlk = GetBlock() as ExceptionBlock;
if (tryBlk == null)
throw new InvalidOperationException(Properties.Messages.ErrInvalidExceptionStatement);
return tryBlk;
}
ExceptionBlock GetAnyTryBlock()
{
foreach (Block blk in blocks)
{
ExceptionBlock tryBlk = blk as ExceptionBlock;
if (tryBlk != null)
return tryBlk;
}
return null;
}
public Operand Catch(Type exceptionType)
{
return GetTryBlock().BeginCatch(exceptionType);
}
[System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1702:CompoundWordsShouldBeCasedCorrectly", Justification = "Intentional")]
public void CatchAll()
{
GetTryBlock().BeginCatchAll();
}
public void Fault()
{
GetTryBlock().BeginFault();
}
public void Finally()
{
GetTryBlock().BeginFinally();
}
public void Switch(Operand expression)
{
Begin(new SwitchBlock(expression));
}
SwitchBlock GetSwitchBlock()
{
SwitchBlock switchBlk = GetBlock() as SwitchBlock;
if (switchBlk == null)
throw new InvalidOperationException(Properties.Messages.ErrInvalidSwitchStatement);
return switchBlk;
}
public void Case(object value)
{
IConvertible conv = value as IConvertible;
if (conv == null)
throw new ArgumentException(Properties.Messages.ErrArgMustImplementIConvertible, "value");
GetSwitchBlock().Case(conv);
}
public void DefaultCase()
{
GetSwitchBlock().Case(null);
}
#endregion
Block GetBlock()
{
if (blocks.Count == 0)
return null;
return blocks.Peek();
}
Block GetBlockForVariable()
{
if (blocks.Count == 0)
return null;
Block b = blocks.Peek();
b.EnsureScope();
return b;
}
void Begin(Block b)
{
blocks.Push(b);
b.g = this;
b.Begin();
}
public void End()
{
if (blocks.Count == 0)
throw new InvalidOperationException(Properties.Messages.ErrNoOpenBlocks);
blocks.Peek().End();
blocks.Pop();
}
abstract class Block
{
bool hasScope;
internal CodeGen g;
public void EnsureScope()
{
if (!hasScope)
{
if (g.context.SupportsScopes)
g.il.BeginScope();
hasScope = true;
}
}
protected void EndScope()
{
if (hasScope)
{
if (g.context.SupportsScopes)
g.il.EndScope();
hasScope = false;
}
}
public void Begin()
{
BeginImpl();
}
public void End()
{
EndImpl();
EndScope();
}
protected abstract void BeginImpl();
protected abstract void EndImpl();
}
class IfBlock : Block
{
Operand condition;
public IfBlock(Operand condition)
{
if (condition.Type != typeof(bool))
this.condition = condition.IsTrue();
else
this.condition = condition;
}
Label lbSkip;
protected override void BeginImpl()
{
g.BeforeStatement();
lbSkip = g.il.DefineLabel();
condition.EmitBranch(g, BranchSet.Inverse, lbSkip);
}
protected override void EndImpl()
{
g.il.MarkLabel(lbSkip);
g.reachable = true;
}
}
class ElseBlock : Block
{
IfBlock ifBlk;
Label lbSkip;
bool canSkip;
public ElseBlock(IfBlock ifBlk)
{
this.ifBlk = ifBlk;
}
protected override void BeginImpl()
{
if (canSkip = g.reachable)
{
lbSkip = g.il.DefineLabel();
g.il.Emit(OpCodes.Br, lbSkip);
}
ifBlk.End();
}
protected override void EndImpl()
{
if (canSkip)
{
g.il.MarkLabel(lbSkip);
g.reachable = true;
}
}
}
class LoopBlock : Block, IBreakable, IContinuable
{
IStatement init;
Operand test;
IStatement iter;
public LoopBlock(IStatement init, Operand test, IStatement iter)
{
this.init = init;
this.test = test;
this.iter = iter;
if (test.Type != typeof(bool))
test = test.IsTrue();
}
Label lbLoop, lbTest, lbEnd, lbIter;
bool endUsed = false, iterUsed = false;
protected override void BeginImpl()
{
g.BeforeStatement();
lbLoop = g.il.DefineLabel();
lbTest = g.il.DefineLabel();
if (init != null)
init.Emit(g);
g.il.Emit(OpCodes.Br, lbTest);
g.il.MarkLabel(lbLoop);
}
protected override void EndImpl()
{
if (iter != null)
{
if (iterUsed)
g.il.MarkLabel(lbIter);
iter.Emit(g);
}
g.il.MarkLabel(lbTest);
test.EmitBranch(g, BranchSet.Normal, lbLoop);
if (endUsed)
g.il.MarkLabel(lbEnd);
g.reachable = true;
}
public Label GetBreakTarget()
{
if (!endUsed)
{
lbEnd = g.il.DefineLabel();
endUsed = true;
}
return lbEnd;
}
public Label GetContinueTarget()
{
if (iter == null)
return lbTest;
if (!iterUsed)
{
lbIter = g.il.DefineLabel();
iterUsed = true;
}
return lbIter;
}
}
// TODO: proper implementation, including dispose
class ForeachBlock : Block, IBreakable, IContinuable
{
Type elementType;
Operand collection;
public ForeachBlock(Type elementType, Operand collection)
{
this.elementType = elementType;
this.collection = collection;
}
Operand enumerator, element;
Label lbLoop, lbTest, lbEnd;
bool endUsed = false;
public Operand Element { get { return element; } }
protected override void BeginImpl()
{
g.BeforeStatement();
enumerator = g.Local();
lbLoop = g.il.DefineLabel();
lbTest = g.il.DefineLabel();
if (typeof(IEnumerable).IsAssignableFrom(collection.Type))
collection = collection.Cast(typeof(IEnumerable));
g.Assign(enumerator, collection.Invoke("GetEnumerator"));
g.il.Emit(OpCodes.Br, lbTest);
g.il.MarkLabel(lbLoop);
element = g.Local(elementType);
g.Assign(element, enumerator.Property("Current"), true);
}
protected override void EndImpl()
{
g.il.MarkLabel(lbTest);
enumerator.Invoke("MoveNext").EmitGet(g);
g.il.Emit(OpCodes.Brtrue, lbLoop);
if (endUsed)
g.il.MarkLabel(lbEnd);
g.reachable = true;
}
public Label GetBreakTarget()
{
if (!endUsed)
{
lbEnd = g.il.DefineLabel();
endUsed = true;
}
return lbEnd;
}
public Label GetContinueTarget()
{
return lbTest;
}
}
class ExceptionBlock : Block
{
bool endReachable = false;
bool isFinally = false;
protected override void BeginImpl()
{
g.il.BeginExceptionBlock();
}
public void BeginCatchAll()
{
EndScope();
if (g.reachable)
endReachable = true;
g.il.BeginCatchBlock(typeof(object));
g.il.Emit(OpCodes.Pop);
g.reachable = true;
}
public Operand BeginCatch(Type t)
{
EndScope();
if (g.reachable)
endReachable = true;
g.il.BeginCatchBlock(t);
LocalBuilder lb = g.il.DeclareLocal(t);
g.il.Emit(OpCodes.Stloc, lb);
g.reachable = true;
return new _Local(g, lb);
}
public void BeginFault()
{
EndScope();
g.il.BeginFaultBlock();
g.reachable = true;
isFinally = true;
}
public void BeginFinally()
{
EndScope();
g.il.BeginFinallyBlock();
g.reachable = true;
isFinally = true;
}
protected override void EndImpl()
{
g.il.EndExceptionBlock();
g.reachable = endReachable;
}
public bool IsFinally { get { return isFinally; } }
}
class SwitchBlock : Block, IBreakable
{
static Type[] validTypes = {
typeof(sbyte), typeof(byte), typeof(short), typeof(ushort), typeof(int), typeof(uint), typeof(long), typeof(ulong), typeof(char), typeof(string)
};
static MethodInfo strCmp = typeof(string).GetMethod("Equals", BindingFlags.Public | BindingFlags.Static,
null, new Type[] { typeof(string), typeof(string) }, null);
Operand expression;
Conversion conv;
Type govType;
Label lbDecision;
Label lbEnd;
Label lbDefault;
LocalBuilder exp;
bool defaultExists = false;
bool endReachable = false;
SortedList<IComparable, Label> cases = new SortedList<IComparable, Label>();
public SwitchBlock(Operand expression)
{
this.expression = expression;
Type exprType = expression.Type;
if (Array.IndexOf(validTypes, exprType) != -1)
govType = exprType;
else if (exprType.IsEnum)
govType = Enum.GetUnderlyingType(exprType);
else
{
// if a single implicit coversion from expression to one of the valid types exists, it's ok
foreach (Type t in validTypes)
{
Conversion tmp = Conversion.GetImplicit(expression, t, false);
if (tmp.IsValid)
{
if (conv == null)
{
conv = tmp;
govType = t;
}
else
throw new AmbiguousMatchException(Properties.Messages.ErrAmbiguousSwitchExpression);
}
}
}
}
protected override void BeginImpl()
{
lbDecision = g.il.DefineLabel();
lbDefault = lbEnd = g.il.DefineLabel();
expression.EmitGet(g);
if (conv != null)
conv.Emit(g, expression.Type, govType);
exp = g.il.DeclareLocal(govType);
g.il.Emit(OpCodes.Stloc, exp);
g.il.Emit(OpCodes.Br, lbDecision);
g.reachable = false;
}
public void Case(IConvertible value)
{
bool duplicate;
// make sure the value is of the governing type
IComparable val = value == null ? null : (IComparable)value.ToType(govType, System.Globalization.CultureInfo.InvariantCulture);
if (value == null)
duplicate = defaultExists;
else
duplicate = cases.ContainsKey(val);
if (duplicate)
throw new InvalidOperationException(Properties.Messages.ErrDuplicateCase);
if (g.reachable)
g.il.Emit(OpCodes.Br, lbEnd);
EndScope();
Label lb = g.il.DefineLabel();
g.il.MarkLabel(lb);
if (value == null)
{
defaultExists = true;
lbDefault = lb;
}
else
{
cases[val] = lb;
}
g.reachable = true;
}
static int Diff(IConvertible val1, IConvertible val2)
{
ulong diff;
switch (val1.GetTypeCode())
{
case TypeCode.UInt64:
diff = val2.ToUInt64(null) - val1.ToUInt64(null);
break;
case TypeCode.Int64:
diff = (ulong)(val2.ToInt64(null) - val1.ToInt64(null));
break;
case TypeCode.UInt32:
diff = val2.ToUInt32(null) - val1.ToUInt32(null);
break;
default:
diff = (ulong)(val2.ToInt32(null) - val1.ToInt32(null));
break;
}
if (diff >= int.MaxValue)
return int.MaxValue;
else
return (int)diff;
}
void Finish(List<Label> labels)
{
switch (labels.Count)
{
case 0: break;
case 1:
g.il.Emit(OpCodes.Beq, labels[0]);
break;
default:
g.il.Emit(OpCodes.Sub);
g.il.Emit(OpCodes.Switch, labels.ToArray());
break;
}
}
void EmitValue(IConvertible val)
{
switch (val.GetTypeCode())
{
case TypeCode.UInt64:
g.EmitI8Helper(unchecked((long)val.ToUInt64(null)), false);
break;
case TypeCode.Int64:
g.EmitI8Helper(val.ToInt64(null), true);
break;
case TypeCode.UInt32:
g.EmitI4Helper(unchecked((int)val.ToUInt64(null)));
break;
default:
g.EmitI4Helper(val.ToInt32(null));
break;
}
}
protected override void EndImpl()
{
if (g.reachable)
{
g.il.Emit(OpCodes.Br, lbEnd);
endReachable = true;
}
EndScope();
g.il.MarkLabel(lbDecision);
if (govType == typeof(string))
{
foreach (KeyValuePair<IComparable, Label> kvp in cases)
{
g.il.Emit(OpCodes.Ldloc, exp);
g.il.Emit(OpCodes.Ldstr, kvp.Key.ToString());
g.il.Emit(OpCodes.Call, strCmp);
g.il.Emit(OpCodes.Brtrue, kvp.Value);
}
}
else
{
bool first = true;
IConvertible prev = null;
List<Label> labels = new List<Label>();
foreach (KeyValuePair<IComparable, Label> kvp in cases)
{
IConvertible val = (IConvertible)kvp.Key;
if (prev != null)
{
int diff = Diff(prev, val);
if (diff > 3)
{
Finish(labels);
labels.Clear();
prev = null;
first = true;
}
else while (diff-- > 1)
labels.Add(lbDefault);
}
if (first)
{
g.il.Emit(OpCodes.Ldloc, exp);
EmitValue(val);
first = false;
}
labels.Add(kvp.Value);
prev = val;
}
Finish(labels);
}
if (lbDefault != lbEnd)
g.il.Emit(OpCodes.Br, lbDefault);
g.il.MarkLabel(lbEnd);
g.reachable = endReachable;
}
public Label GetBreakTarget()
{
endReachable = true;
return lbEnd;
}
}
}
}
| |
using System;
using System.IO;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Reflection;
using RestSharp;
using NUnit.Framework;
using HostMe.Sdk.Client;
using HostMe.Sdk.Api;
using HostMe.Sdk.Model;
namespace HostMe.Sdk.Test
{
/// <summary>
/// Class for testing AdminWaitingManagementApi
/// </summary>
/// <remarks>
/// This file is automatically generated by Swagger Codegen.
/// Please update the test case below to test the API endpoint.
/// </remarks>
[TestFixture]
public class AdminWaitingManagementApiTests
{
private AdminWaitingManagementApi instance;
/// <summary>
/// Setup before each unit test
/// </summary>
[SetUp]
public void Init()
{
instance = new AdminWaitingManagementApi();
}
/// <summary>
/// Clean up after each unit test
/// </summary>
[TearDown]
public void Cleanup()
{
}
/// <summary>
/// Test an instance of AdminWaitingManagementApi
/// </summary>
[Test]
public void InstanceTest()
{
Assert.IsInstanceOf<AdminWaitingManagementApi> (instance, "instance is a AdminWaitingManagementApi");
}
/// <summary>
/// Test AddConfirmedWaiting
/// </summary>
[Test]
public void AddConfirmedWaitingTest()
{
// TODO: add unit test for the method 'AddConfirmedWaiting'
int? restaurantId = null; // TODO: replace null with proper value
PanelConfirmation conf = null; // TODO: replace null with proper value
var response = instance.AddConfirmedWaiting(restaurantId, conf);
Assert.IsInstanceOf<WaitingItem> (response, "response is WaitingItem");
}
/// <summary>
/// Test AddNewWaiting
/// </summary>
[Test]
public void AddNewWaitingTest()
{
// TODO: add unit test for the method 'AddNewWaiting'
int? restaurantId = null; // TODO: replace null with proper value
var response = instance.AddNewWaiting(restaurantId);
Assert.IsInstanceOf<WaitingItem> (response, "response is WaitingItem");
}
/// <summary>
/// Test CallWaitingParty
/// </summary>
[Test]
public void CallWaitingPartyTest()
{
// TODO: add unit test for the method 'CallWaitingParty'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
string tableNumber = null; // TODO: replace null with proper value
instance.CallWaitingParty(restaurantId, waitingItemId, tableNumber);
}
/// <summary>
/// Test Close
/// </summary>
[Test]
public void CloseTest()
{
// TODO: add unit test for the method 'Close'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
instance.Close(restaurantId, waitingItemId);
}
/// <summary>
/// Test CloseAsCanceled
/// </summary>
[Test]
public void CloseAsCanceledTest()
{
// TODO: add unit test for the method 'CloseAsCanceled'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
string origin = null; // TODO: replace null with proper value
instance.CloseAsCanceled(restaurantId, waitingItemId, origin);
}
/// <summary>
/// Test CloseAsSeated
/// </summary>
[Test]
public void CloseAsSeatedTest()
{
// TODO: add unit test for the method 'CloseAsSeated'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
instance.CloseAsSeated(restaurantId, waitingItemId);
}
/// <summary>
/// Test Confirm
/// </summary>
[Test]
public void ConfirmTest()
{
// TODO: add unit test for the method 'Confirm'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
PanelConfirmation conf = null; // TODO: replace null with proper value
var response = instance.Confirm(restaurantId, waitingItemId, conf);
Assert.IsInstanceOf<WaitingItem> (response, "response is WaitingItem");
}
/// <summary>
/// Test GetAllWaitings
/// </summary>
[Test]
public void GetAllWaitingsTest()
{
// TODO: add unit test for the method 'GetAllWaitings'
int? restaurantId = null; // TODO: replace null with proper value
string queryOptions = null; // TODO: replace null with proper value
string area = null; // TODO: replace null with proper value
int? groupSize = null; // TODO: replace null with proper value
var response = instance.GetAllWaitings(restaurantId, queryOptions, area, groupSize);
Assert.IsInstanceOf<List<WaitingItem>> (response, "response is List<WaitingItem>");
}
/// <summary>
/// Test GetMessages
/// </summary>
[Test]
public void GetMessagesTest()
{
// TODO: add unit test for the method 'GetMessages'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
var response = instance.GetMessages(restaurantId, waitingItemId);
Assert.IsInstanceOf<List<Message>> (response, "response is List<Message>");
}
/// <summary>
/// Test GetRestaurantWaitingsStatistic
/// </summary>
[Test]
public void GetRestaurantWaitingsStatisticTest()
{
// TODO: add unit test for the method 'GetRestaurantWaitingsStatistic'
int? restaurantId = null; // TODO: replace null with proper value
string area = null; // TODO: replace null with proper value
var response = instance.GetRestaurantWaitingsStatistic(restaurantId, area);
Assert.IsInstanceOf<WaitingsStatistic> (response, "response is WaitingsStatistic");
}
/// <summary>
/// Test GetTodayStats
/// </summary>
[Test]
public void GetTodayStatsTest()
{
// TODO: add unit test for the method 'GetTodayStats'
int? restaurantId = null; // TODO: replace null with proper value
var response = instance.GetTodayStats(restaurantId);
Assert.IsInstanceOf<WaitingStats> (response, "response is WaitingStats");
}
/// <summary>
/// Test GetUnreadMessagesCount
/// </summary>
[Test]
public void GetUnreadMessagesCountTest()
{
// TODO: add unit test for the method 'GetUnreadMessagesCount'
int? restaurantId = null; // TODO: replace null with proper value
var response = instance.GetUnreadMessagesCount(restaurantId);
Assert.IsInstanceOf<Count> (response, "response is Count");
}
/// <summary>
/// Test GetWaitingById
/// </summary>
[Test]
public void GetWaitingByIdTest()
{
// TODO: add unit test for the method 'GetWaitingById'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
var response = instance.GetWaitingById(restaurantId, waitingItemId);
Assert.IsInstanceOf<WaitingItem> (response, "response is WaitingItem");
}
/// <summary>
/// Test GetWaitingSettings
/// </summary>
[Test]
public void GetWaitingSettingsTest()
{
// TODO: add unit test for the method 'GetWaitingSettings'
int? restaurantId = null; // TODO: replace null with proper value
var response = instance.GetWaitingSettings(restaurantId);
Assert.IsInstanceOf<WaitingSettings> (response, "response is WaitingSettings");
}
/// <summary>
/// Test GetWaitingTimeByGroup
/// </summary>
[Test]
public void GetWaitingTimeByGroupTest()
{
// TODO: add unit test for the method 'GetWaitingTimeByGroup'
int? restaurantId = null; // TODO: replace null with proper value
DateTimeOffset? from = null; // TODO: replace null with proper value
DateTimeOffset? to = null; // TODO: replace null with proper value
var response = instance.GetWaitingTimeByGroup(restaurantId, from, to);
Assert.IsInstanceOf<List<WaitingsStatReportItem>> (response, "response is List<WaitingsStatReportItem>");
}
/// <summary>
/// Test GetWaitingTimeByHour
/// </summary>
[Test]
public void GetWaitingTimeByHourTest()
{
// TODO: add unit test for the method 'GetWaitingTimeByHour'
int? restaurantId = null; // TODO: replace null with proper value
DateTimeOffset? from = null; // TODO: replace null with proper value
DateTimeOffset? to = null; // TODO: replace null with proper value
var response = instance.GetWaitingTimeByHour(restaurantId, from, to);
Assert.IsInstanceOf<List<WaitingsStatReportItem>> (response, "response is List<WaitingsStatReportItem>");
}
/// <summary>
/// Test GetWaitingTimeByLine
/// </summary>
[Test]
public void GetWaitingTimeByLineTest()
{
// TODO: add unit test for the method 'GetWaitingTimeByLine'
int? restaurantId = null; // TODO: replace null with proper value
DateTimeOffset? from = null; // TODO: replace null with proper value
DateTimeOffset? to = null; // TODO: replace null with proper value
var response = instance.GetWaitingTimeByLine(restaurantId, from, to);
Assert.IsInstanceOf<List<WaitingsStatReportItem>> (response, "response is List<WaitingsStatReportItem>");
}
/// <summary>
/// Test GetWaitingTimeByMeal
/// </summary>
[Test]
public void GetWaitingTimeByMealTest()
{
// TODO: add unit test for the method 'GetWaitingTimeByMeal'
int? restaurantId = null; // TODO: replace null with proper value
DateTimeOffset? from = null; // TODO: replace null with proper value
DateTimeOffset? to = null; // TODO: replace null with proper value
var response = instance.GetWaitingTimeByMeal(restaurantId, from, to);
Assert.IsInstanceOf<List<WaitingsStatReportItem>> (response, "response is List<WaitingsStatReportItem>");
}
/// <summary>
/// Test GetWaitingTimeByWeek
/// </summary>
[Test]
public void GetWaitingTimeByWeekTest()
{
// TODO: add unit test for the method 'GetWaitingTimeByWeek'
int? restaurantId = null; // TODO: replace null with proper value
DateTimeOffset? from = null; // TODO: replace null with proper value
DateTimeOffset? to = null; // TODO: replace null with proper value
var response = instance.GetWaitingTimeByWeek(restaurantId, from, to);
Assert.IsInstanceOf<List<WaitingsStatReportItem>> (response, "response is List<WaitingsStatReportItem>");
}
/// <summary>
/// Test GetWaitingTimeByWeekDay
/// </summary>
[Test]
public void GetWaitingTimeByWeekDayTest()
{
// TODO: add unit test for the method 'GetWaitingTimeByWeekDay'
int? restaurantId = null; // TODO: replace null with proper value
DateTimeOffset? from = null; // TODO: replace null with proper value
DateTimeOffset? to = null; // TODO: replace null with proper value
var response = instance.GetWaitingTimeByWeekDay(restaurantId, from, to);
Assert.IsInstanceOf<List<WaitingsStatReportItem>> (response, "response is List<WaitingsStatReportItem>");
}
/// <summary>
/// Test GetWaitingsForPeriod
/// </summary>
[Test]
public void GetWaitingsForPeriodTest()
{
// TODO: add unit test for the method 'GetWaitingsForPeriod'
int? restaurantId = null; // TODO: replace null with proper value
DateTimeOffset? from = null; // TODO: replace null with proper value
DateTimeOffset? to = null; // TODO: replace null with proper value
var response = instance.GetWaitingsForPeriod(restaurantId, from, to);
Assert.IsInstanceOf<List<WaitingReportItem>> (response, "response is List<WaitingReportItem>");
}
/// <summary>
/// Test GetWaitingsGroupBy
/// </summary>
[Test]
public void GetWaitingsGroupByTest()
{
// TODO: add unit test for the method 'GetWaitingsGroupBy'
int? restaurantId = null; // TODO: replace null with proper value
string groupBy = null; // TODO: replace null with proper value
DateTimeOffset? from = null; // TODO: replace null with proper value
DateTimeOffset? to = null; // TODO: replace null with proper value
var response = instance.GetWaitingsGroupBy(restaurantId, groupBy, from, to);
Assert.IsInstanceOf<List<WaitingsStatReportItem>> (response, "response is List<WaitingsStatReportItem>");
}
/// <summary>
/// Test Incoming
/// </summary>
[Test]
public void IncomingTest()
{
// TODO: add unit test for the method 'Incoming'
string from = null; // TODO: replace null with proper value
string to = null; // TODO: replace null with proper value
string body = null; // TODO: replace null with proper value
var response = instance.Incoming(from, to, body);
Assert.IsInstanceOf<Object> (response, "response is Object");
}
/// <summary>
/// Test MarkAllMessagesAsRead
/// </summary>
[Test]
public void MarkAllMessagesAsReadTest()
{
// TODO: add unit test for the method 'MarkAllMessagesAsRead'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
instance.MarkAllMessagesAsRead(restaurantId, waitingItemId);
}
/// <summary>
/// Test PutOnHold
/// </summary>
[Test]
public void PutOnHoldTest()
{
// TODO: add unit test for the method 'PutOnHold'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
instance.PutOnHold(restaurantId, waitingItemId);
}
/// <summary>
/// Test ReOpenWaiting
/// </summary>
[Test]
public void ReOpenWaitingTest()
{
// TODO: add unit test for the method 'ReOpenWaiting'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
var response = instance.ReOpenWaiting(restaurantId, waitingItemId);
Assert.IsInstanceOf<WaitingItem> (response, "response is WaitingItem");
}
/// <summary>
/// Test SendMessage
/// </summary>
[Test]
public void SendMessageTest()
{
// TODO: add unit test for the method 'SendMessage'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
string origin = null; // TODO: replace null with proper value
CreateMessage createMessage = null; // TODO: replace null with proper value
var response = instance.SendMessage(restaurantId, waitingItemId, origin, createMessage);
Assert.IsInstanceOf<Message> (response, "response is Message");
}
/// <summary>
/// Test SetWaitingSettings
/// </summary>
[Test]
public void SetWaitingSettingsTest()
{
// TODO: add unit test for the method 'SetWaitingSettings'
int? restaurantId = null; // TODO: replace null with proper value
WaitingSettings settings = null; // TODO: replace null with proper value
instance.SetWaitingSettings(restaurantId, settings);
}
/// <summary>
/// Test TakeOffHold
/// </summary>
[Test]
public void TakeOffHoldTest()
{
// TODO: add unit test for the method 'TakeOffHold'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
instance.TakeOffHold(restaurantId, waitingItemId);
}
/// <summary>
/// Test UpdateWaiting
/// </summary>
[Test]
public void UpdateWaitingTest()
{
// TODO: add unit test for the method 'UpdateWaiting'
int? restaurantId = null; // TODO: replace null with proper value
int? waitingItemId = null; // TODO: replace null with proper value
UpdateWaitingItem item = null; // TODO: replace null with proper value
var response = instance.UpdateWaiting(restaurantId, waitingItemId, item);
Assert.IsInstanceOf<WaitingItem> (response, "response is WaitingItem");
}
}
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.